Skip to content
Draft
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
6 changes: 5 additions & 1 deletion packages/cli/src/commands/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export default class AuthVerify extends BeeperCommand {
async run(): Promise<void> {
const { flags } = await this.parse(AuthVerify)
ensureWritable(flags)
await printData(await driveVerification({ baseURL: flags['base-url'], target: flags.target, userID: flags.user, yes: flags.yes }), flags.json ? 'json' : 'human')
const state = await driveVerification({ baseURL: flags['base-url'], target: flags.target, userID: flags.user, yes: flags.yes })
if (!flags.json && state.state === 'needs-verification') {
process.stderr.write('Verification is pending. Approve on another signed-in device, then rerun `beeper verify`.\n')
}
await printData(state, flags.json ? 'json' : 'human')
}
}
37 changes: 35 additions & 2 deletions packages/cli/src/lib/app-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,30 @@ export async function resolveVerificationID(client: VerificationLister, id?: str
return active.id
}

export async function driveVerification(options: { baseURL?: string; target?: string; userID?: string; yes?: boolean } = {}): Promise<AppState> {
function isCompletedVerificationConflict(error: unknown): boolean {
if (!(error instanceof Error)) return false
const match = /failed: 409 (\{.*\})$/s.exec(error.message)
if (!match) return false
try {
const body = JSON.parse(match[1]!) as { code?: string; details?: { state?: string } }
return body.code === 'verification_action_not_available' && body.details?.state === 'done'
} catch {
return false
}
}

export async function driveVerification(options: { baseURL?: string; target?: string; token?: string | false; userID?: string; yes?: boolean } = {}): Promise<AppState> {
let state = await getAppState(options)
if (state.state === 'ready') return state
if (state.state === 'needs-login') throw new Error('Target is not signed in. Run `beeper setup` after signing in to Beeper Desktop.')

// A successful local SAS confirmation may return the previous availableActions.
// Never send sas.confirm twice for the same verification in one run.
const confirmedSAS = new Set<string>()

for (;;) {
// Once setup has moved past verification, do not create a new request.
if (state.state !== 'needs-verification') return state
const verification = state.verification
const actions = new Set(verification?.availableActions ?? [])
const id = verification?.id
Expand All @@ -98,12 +116,27 @@ export async function driveVerification(options: { baseURL?: string; target?: st
}

if (actions.has('sas.confirm') && id) {
if (confirmedSAS.has(id)) {
// The POST snapshot can still advertise sas.confirm even though the local
// confirmation was accepted. Re-read once; if still stale, return pending.
const latest = await getAppState(options)
if (latest.verification?.id === id && latest.verification.availableActions?.includes('sas.confirm')) return latest
state = latest
continue
}
const sas = state.verification?.sas
if (!options.yes) {
process.stdout.write(`Verify that this matches on the other device:\n${sas?.emojis ?? sas?.decimals ?? '(no SAS data)'}\n`)
if (!await promptYesNo('Do they match?')) throw new Error('Verification cancelled.')
}
state = (await appRequest<SASConfirmResponse>('POST', `/v1/app/setup/verifications/${encodeURIComponent(id)}/sas/confirm`, options)).session
try {
state = (await appRequest<SASConfirmResponse>('POST', `/v1/app/setup/verifications/${encodeURIComponent(id)}/sas/confirm`, options)).session
} catch (error) {
// A 409 with state=done is a raced completion, not a failed verification.
if (!isCompletedVerificationConflict(error)) throw error
return getAppState(options)
}
confirmedSAS.add(id)
continue
}

Expand Down
133 changes: 133 additions & 0 deletions packages/cli/test/verify-sas-regression.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { afterAll, describe, expect, it } from 'bun:test'
import { createServer } from 'node:http'
import { once } from 'node:events'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { driveVerification } from '../src/lib/app-state.js'

const configDir = mkdtempSync(join(tmpdir(), 'beeper-verify-sas-'))
process.env.BEEPER_CLI_CONFIG_DIR = configDir
afterAll(() => rmSync(configDir, { recursive: true, force: true }))

const sas = { id: 'verification-123', purpose: 'device', direction: 'outgoing',
state: 'sas_ready', availableActions: ['sas.confirm'], sas: { emojis: '🐼🔒🏁✈🎅🎺👍' } }
const pending = { state: 'needs-verification', verification: sas }
const ready = { state: 'needs-first-sync' }

async function withSetupServer(
route: (method: string, path: string) => { status?: number; body: unknown },
run: (baseURL: string) => Promise<void>,
) {
const server = createServer((req, res) => {
const result = route(req.method ?? '', req.url ?? '')
res.writeHead(result.status ?? 200, { 'content-type': 'application/json' })
res.end(JSON.stringify(result.body))
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
try {
const address = server.address()
if (!address || typeof address === 'string') throw new Error('Missing test server port')
await run(`http://127.0.0.1:${address.port}`)
} finally {
await new Promise<void>(resolve => server.close(() => resolve()))
}
}

describe('SAS device verification regression (#62)', () => {
it('posts sas.confirm once when the POST response still lists the same action', async () => {
let confirms = 0, gets = 0, creates = 0
await withSetupServer((method, path) => {
if (method === 'GET' && path === '/v1/app/setup') {
gets++
return { body: gets === 1 ? pending : ready }
}
if (method === 'POST' && path.endsWith('/sas/confirm')) {
confirms++
return { body: { session: pending } }
}
if (method === 'POST') creates++
return { status: 404, body: {} }
}, async baseURL => {
const result = await driveVerification({ baseURL, token: false, yes: true })
expect(result.state).toBe('needs-first-sync')
expect(confirms).toBe(1)
expect(creates).toBe(0)
expect(gets).toBe(2)
})
})

it('returns pending without a second confirm when the refreshed state is still stale', async () => {
let confirms = 0, gets = 0
await withSetupServer((method, path) => {
if (method === 'GET' && path === '/v1/app/setup') {
gets++
return { body: pending }
}
if (method === 'POST' && path.endsWith('/sas/confirm')) {
confirms++
return { body: { session: pending } }
}
return { status: 404, body: {} }
}, async baseURL => {
const state = await driveVerification({ baseURL, token: false, yes: true })
expect(state.state).toBe('needs-verification')
expect(confirms).toBe(1)
expect(gets).toBe(2)
})
})

it('re-reads readiness when a raced 409 says verification is done', async () => {
let confirms = 0
await withSetupServer((method, path) => {
if (method === 'GET') return { body: confirms ? ready : pending }
if (method === 'POST' && path.endsWith('/sas/confirm')) {
confirms++
return { status: 409, body: {
code: 'verification_action_not_available',
details: { state: 'done' },
} }
}
return { status: 404, body: {} }
}, async baseURL => {
expect((await driveVerification({ baseURL, token: false, yes: true })).state).toBe('needs-first-sync')
expect(confirms).toBe(1)
})
})

it('does not suppress other 409 errors', async () => {
await withSetupServer((method, path) => {
if (method === 'GET') return { body: pending }
if (method === 'POST' && path.endsWith('/sas/confirm')) {
return { status: 409, body: {
code: 'verification_action_not_available',
details: { state: 'requested' },
} }
}
return { status: 404, body: {} }
}, async baseURL => {
await expect(driveVerification({ baseURL, token: false, yes: true })).rejects.toThrow('409')
})
})

it('starts a request once and returns pending when the other device has not acted', async () => {
let starts = 0
await withSetupServer((method, path) => {
if (method === 'GET' && path === '/v1/app/setup') {
return { body: { state: 'needs-verification' } }
}
if (method === 'POST' && path === '/v1/app/setup/verifications') {
starts++
return { body: { session: {
state: 'needs-verification',
verification: { id: 'pending-1', state: 'requested', availableActions: [] },
} } }
}
return { status: 404, body: {} }
}, async baseURL => {
expect((await driveVerification({ baseURL, token: false, yes: true })).state).toBe('needs-verification')
expect(starts).toBe(1)
})
})
})