Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,14 @@
"@inquirer/prompts": "^8.4.2",
"commander": "^14.0.3",
"fintoc": "^1.19.0",
"smol-toml": "^1.6.1"
"smol-toml": "^1.6.1",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@antfu/eslint-config": "^8.2.0",
"@types/node": "^25.6.0",
"@types/ws": "^8.18.1",
"eslint": "^10.2.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.5",
Expand Down
10 changes: 10 additions & 0 deletions src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ describe('help consistency', () => {
expect(stdout).toContain('Auth:')
expect(stdout).toContain('Resources:')
expect(stdout).toContain('Utilities:')
expect(stdout).toContain('webhooks')
expect(stdout).toContain('Get started: fintoc login')
})
})
Expand All @@ -70,6 +71,15 @@ describe('help consistency', () => {
})
})

describe('when webhooks command is called without a verb', () => {
test('exits 0 and shows webhooks help', () => {
const { stdout, exitCode } = run(['webhooks'])
expect(exitCode).toBe(0)
expect(stdout).toContain('Listen for webhook events')
expect(stdout).toContain('listen')
})
})

describe('when operation --help is shown', () => {
test('shows operation-specific options and global options', () => {
const { stdout, exitCode } = run(['payment_intents', 'list', '--help'])
Expand Down
69 changes: 69 additions & 0 deletions src/commands/webhooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { Command } from 'commander'
import { listenToRelay } from '../lib/action-cable.js'
import { resolveAuth } from '../lib/auth.js'
import { addDefaultAction } from '../lib/commands.js'
import { handleError } from '../lib/errors.js'
import { hint, info } from '../lib/output.js'
import { createWebhookRelayHandlers } from '../lib/webhooks/handlers.js'
import { createCliSession } from '../lib/webhooks/sessions.js'

type RootOpts = {
apiKey?: string
json?: boolean
}

export const webhooksCommand = (program: Command) => {
const cmd = program.command('webhooks').description('Listen for webhook events')
cmd.configureHelp({ showGlobalOptions: true })
addDefaultAction(cmd)

cmd
.command('listen')
.description('Listen for webhook events in real time')
.action(async (_opts: unknown, actionCmd: Command) => {
const rootOpts = actionCmd.parent!.parent!.opts<RootOpts>()
const auth = resolveAuth(rootOpts)
Comment on lines +23 to +25

const shutdown = () => {
process.exit(0)
}

process.once('SIGINT', shutdown)
process.once('SIGTERM', shutdown)

let caughtError: unknown
try {
const session = await createCliSession({
secretKey: auth.secretKey,
streamType: 'webhook_event',
})

if (!rootOpts.json) {
const whsMessage = session.webhook_secret
? ` Your webhook signing secret is ${session.webhook_secret}`
: ''

info(`Listening for webhooks.${whsMessage}`)
info('Press Ctrl+C to stop.')

hint('')
}

await listenToRelay({
websocketUrl: session.websocket_url,
sessionId: session.id,
secret: session.secret,
handlers: createWebhookRelayHandlers({ json: rootOpts.json }),
})
} catch (err) {
caughtError = err
} finally {
process.off('SIGINT', shutdown)
process.off('SIGTERM', shutdown)
}

if (caughtError) {
handleError(caughtError, { json: rootOpts.json })
}
})
}
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { doctorCommand } from './commands/doctor.js'
import { loginCommand } from './commands/login.js'
import { logoutCommand } from './commands/logout.js'
import { openCommand } from './commands/open.js'
import { webhooksCommand } from './commands/webhooks.js'
import { addDefaultAction } from './lib/commands.js'
import { error } from './lib/output.js'
import { registerResourceCommands } from './resources/factory.js'
Expand All @@ -15,7 +16,7 @@ declare const __CLI_VERSION__: string
const versionString = `fintoc/${__CLI_VERSION__} ${process.platform} node-${process.version}`

const AUTH_COMMANDS = new Set(['login', 'logout', 'config'])
const UTILITY_COMMANDS = new Set(['doctor', 'open'])
const UTILITY_COMMANDS = new Set(['doctor', 'open', 'webhooks'])

type HelpEntry = { name: () => string; description: () => string }

Expand Down Expand Up @@ -76,6 +77,7 @@ logoutCommand(program)
configCommand(program)
doctorCommand(program)
openCommand(program)
webhooksCommand(program)
registerResourceCommands(program, v1Resources)

const v2Cmd = program.command('v2').description('API v2 resources')
Expand Down
64 changes: 64 additions & 0 deletions src/lib/__tests__/action-cable.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { Buffer } from 'node:buffer'
import { describe, expect, test } from 'vitest'
import {
createSubscribeCommand,
createSubscriptionIdentifier,
originForWebSocketUrl,
parseActionCableMessage,
} from '../action-cable.js'

describe('ActionCable relay', () => {
test('creates subscription identifier with session credentials', () => {
expect(JSON.parse(createSubscriptionIdentifier('clisess_123', 'whsec_test_123'))).toEqual({
channel: 'CliSessionsChannel',
session_id: 'clisess_123',
secret: 'whsec_test_123',
})
})

test('creates ActionCable subscribe command', () => {
const payload = JSON.parse(createSubscribeCommand('clisess_123', 'whsec_test_123'))

expect(payload).toEqual({
command: 'subscribe',
identifier: createSubscriptionIdentifier('clisess_123', 'whsec_test_123'),
})
})

test('derives an allowed Origin from the websocket URL', () => {
expect(originForWebSocketUrl('ws://api.localhost:3000/cable')).toBe('http://api.localhost:3000')
expect(originForWebSocketUrl('wss://api.fintoc.com/cable')).toBe('https://api.fintoc.com')
})

test('parses valid ActionCable messages', () => {
const payload = {
identifier: 'subscription-id',
message: {
type: 'webhook_event',
event: { id: 'evt_123' },
},
}

expect(parseActionCableMessage(Buffer.from(JSON.stringify(payload)))).toEqual({
message: payload.message,
})
})

test('ignores invalid JSON', () => {
expect(parseActionCableMessage(Buffer.from('{'))).toBeUndefined()
})

test('ignores malformed ActionCable messages', () => {
expect(
parseActionCableMessage(
Buffer.from(
JSON.stringify({
message: {
type: 123,
},
}),
),
),
).toBeUndefined()
})
})
Loading
Loading