From 1e8a7db39e5d68f39bc53ea40c1699b1f98bf37b Mon Sep 17 00:00:00 2001 From: mosskappa <205706019+mosskappa@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:42:01 +0800 Subject: [PATCH] fix(verify): avoid duplicate SAS confirmation on stale state --- packages/cli/src/commands/verify.ts | 6 +- packages/cli/src/lib/app-state.ts | 37 ++++- .../cli/test/verify-sas-regression.test.ts | 133 ++++++++++++++++++ 3 files changed, 173 insertions(+), 3 deletions(-) create mode 100644 packages/cli/test/verify-sas-regression.test.ts diff --git a/packages/cli/src/commands/verify.ts b/packages/cli/src/commands/verify.ts index a95b8ab1..5f520a0f 100644 --- a/packages/cli/src/commands/verify.ts +++ b/packages/cli/src/commands/verify.ts @@ -10,6 +10,10 @@ export default class AuthVerify extends BeeperCommand { async run(): Promise { 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') } } diff --git a/packages/cli/src/lib/app-state.ts b/packages/cli/src/lib/app-state.ts index 7f420e22..50cfaf6a 100644 --- a/packages/cli/src/lib/app-state.ts +++ b/packages/cli/src/lib/app-state.ts @@ -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 { +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 { 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() + 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 @@ -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('POST', `/v1/app/setup/verifications/${encodeURIComponent(id)}/sas/confirm`, options)).session + try { + state = (await appRequest('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 } diff --git a/packages/cli/test/verify-sas-regression.test.ts b/packages/cli/test/verify-sas-regression.test.ts new file mode 100644 index 00000000..5e8a6b9e --- /dev/null +++ b/packages/cli/test/verify-sas-regression.test.ts @@ -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, +) { + 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(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) + }) + }) +})