diff --git a/docs/incoming-migration.md b/docs/incoming-migration.md index 9ad9536..984c5b2 100644 --- a/docs/incoming-migration.md +++ b/docs/incoming-migration.md @@ -604,16 +604,16 @@ provisioned, and the caller resumes through `recover` from C3 instead. Errors. Each code is stable and mapped explicitly, and no message carries a secret. -| Condition | Error code | HTTP status | -| -------------------------------------------------------- | --------------------------- | ----------- | -| Body fails schema | `InvalidRequest` | 400 | -| Missing or stale OTP proof | `ArrivalProofRequired` | 403 | -| Unknown operation or verified principal is not its owner | `AccountNotFound` | 404 | -| Saved arrival is no longer actionable | `ArrivalExpired` | 409 | -| `expectedVersion` differs from the saved version | `OperationConflict` | 409 | -| Concurrent work for the DID is admitted | `OperationPending` | 409 | -| Per-IP or per-subject budget exhausted | `RateLimitExceeded` | 429 | -| Dispatch state makes cancellation unsafe | `OperationRecoveryRequired` | 409 | +| Condition | Error code | HTTP status | +| ------------------------------------------------------------------------------------------------ | --------------------------- | ----------- | +| Body fails schema | `InvalidRequest` | 400 | +| Missing or stale OTP proof | `ArrivalProofRequired` | 403 | +| Unknown operation or verified principal is not its owner | `AccountNotFound` | 404 | +| Arrival is no longer actionable, or the presented arrival code is superseded, unknown or expired | `ArrivalExpired` | 409 | +| `expectedVersion` differs from the saved version | `OperationConflict` | 409 | +| Concurrent work for the DID is admitted | `OperationPending` | 409 | +| Per-IP or per-subject budget exhausted | `RateLimitExceeded` | 429 | +| Dispatch state makes cancellation unsafe, or renewal finds an uncertain allocation | `OperationRecoveryRequired` | 409 | Replay. `prepare` with the same verified user, DID and handle is idempotent and returns the same saved operation while that operation is still actionable. A changed @@ -642,6 +642,46 @@ recoverArrival(principal, proof, {operationId, expectedVersion}) -> standard tracked credential fields ``` +Implemented behavior of the first two lifecycle callables, both taking +`(request, otp, {operationId, expectedVersion})` and adapted to HTTP by plan 012. +Each validates the body after origin/CSRF and session checks but before the OTP is +verified, so a malformed body spends neither code nor budget. It then re-verifies a +fresh destination OTP and spends the existing challenge budget under `incoming-renew` +or `incoming-cancel`. A request that loses a race with a finished claim maps to its +stable outcome (an idempotent cancelled result, or `ArrivalExpired` for renewal) +rather than a lost-claim error. + +Cancellation first refuses any persisted allocation, signed operation, admission, +attempt, progress or unacknowledged external attempt, then requires the canonical +PLC head to equal the saved head. That directory observation happens outside the +storage transaction. The residual risk is bounded because a pre-intent arrival has +no signed handoff or destination move, so no Entryway-signed operation can exist for +it, so a concurrent head change is necessarily client-made. A cancelled arrival is not +reconciled afterwards (`reconcileArrival` returns not found for it), so such a change +is not observed by Entryway after cancel. A retry for an already cancelled arrival returns +the saved cancelled state without a version check and completes any claim left +pending by a crash after the local cancel commit. + +Renewal matches C1: it is refused with `ArrivalExpired` once the arrival is cancelled +or provisioned, and with `OperationRecoveryRequired` while the saved allocation is +uncertain. Admissions already recorded survive renewal. Continuations do not +re-verify the request digest or any credential. They check the owner, DID, method and +that the recorded code generation is at least 1 and no greater than the current one, +then dispatch only saved or freshly journaled signed facts. At admission, before any request +comparison, the presented code must be the current, unexpired code for the arrival; +a superseded, unknown or expired code fails with `ArrivalExpired` whether or not an +admission exists for that body, and neither consumes the code nor advances the +arrival version. A new +admission, such as creation after a handoff admission, therefore needs the current +code. Renewal never reserves, signs, dispatches or releases anything. Request digests +include the code generation, so an already admitted body re-submitted with the new +code can never match; C1 is silent on this case, so it stays `OperationConflict` +with a message directing the client to resume the saved arrival. + +Accepted decision (proof and budget): renewal and cancellation each require a fresh +destination OTP and spend their own existing-limit buckets, `incoming-renew` and +`incoming-cancel`. + Accepted decision M1 (budgets). Arrival wiring reuses the existing limits in [existing policy](#existing-policy-these-contracts-reuse) and adds no new numeric budget. Reservation requests keep the existing 30-per-IP limit in diff --git a/src/compose-incoming-arrival.mjs b/src/compose-incoming-arrival.mjs index 003b1a4..faca00a 100644 --- a/src/compose-incoming-arrival.mjs +++ b/src/compose-incoming-arrival.mjs @@ -8,6 +8,7 @@ import { createProtocolChallenges } from "./accounts/challenges.mjs"; import { createPdsAccountClient } from "./pds/account-client.mjs"; import { ArrivalPdsClient } from "./pds/arrival-client.js"; import { createIncomingAuthorization } from "./features/external-migration/incoming-authorization.js"; +import { createArrivalLifecycle } from "./features/external-migration/manage-arrival.js"; import { createAuthenticatedArrival } from "./features/external-migration/submit-handoff.js"; import { readIncomingObservation } from "./plc/incoming-observation.js"; @@ -50,6 +51,15 @@ export async function composeIncomingArrival({ }).reserveSigningKey(did); }, }); + const lifecycle = createArrivalLifecycle({ + arrivals, + ownership: accounts.ownership, + authentication, + checkCsrf: browserFlow.checkCsrf, + loadBrowser: browserFlow.loadBrowser, + rateLimit, + plcClient: accounts.plcClient, + }); const admission = createArrivalAdmission({ db, arrivals, invitation }); const authenticated = createAuthenticatedArrival({ arrivals, @@ -111,6 +121,8 @@ export async function composeIncomingArrival({ return { ...admission, prepareArrival, + renewArrival: lifecycle.renew, + cancelArrival: lifecycle.cancel, admitIncoming: async (request, input) => authenticated.admit({ ...input, diff --git a/src/features/external-migration/arrival-types.ts b/src/features/external-migration/arrival-types.ts index dbd1b19..7e9b013 100644 --- a/src/features/external-migration/arrival-types.ts +++ b/src/features/external-migration/arrival-types.ts @@ -174,3 +174,19 @@ export interface ArrivalAggregate { readonly reason: string; }[]; } + +/** An admission is valid for continuation if it was recorded under a code + * generation that has existed: renewal supersedes the code for new admissions but + * never strands one already recorded. Storage records the generation only inside + * the transaction that verified the then-current code, and generations only + * increase, so a recorded value above the current one is inconsistent. */ +export function isRecordedAdmissionGeneration( + admissionGeneration: number, + arrivalGeneration: number, +): boolean { + return ( + Number.isSafeInteger(admissionGeneration) && + admissionGeneration >= 1 && + admissionGeneration <= arrivalGeneration + ); +} diff --git a/src/features/external-migration/fresh-proof.ts b/src/features/external-migration/fresh-proof.ts new file mode 100644 index 0000000..4943ba0 --- /dev/null +++ b/src/features/external-migration/fresh-proof.ts @@ -0,0 +1,55 @@ +import type { + BrowserAuthentication, + BrowserRequest, +} from "../../authentication/port.js"; +import { HttpError } from "../../http/http-error.mjs"; + +/** One fresh destination proof for every saved-user arrival operation. The + * browser origin/CSRF check precedes any session or code work, the existing + * challenge budget is spent before the code is verified, and the verified + * identity must be exactly the saved browser principal. */ +export function createFreshArrivalProof({ + authentication, + checkCsrf, + loadBrowser, + rateLimit, +}: { + authentication: BrowserAuthentication; + checkCsrf: (request: BrowserRequest, browser: unknown) => void; + loadBrowser: (request: BrowserRequest) => Promise; + rateLimit: (subject: string) => Promise; +}) { + return async function requireFreshProof( + request: BrowserRequest, + otp: string, + purpose: string, + /** Input-only validation. It runs before the OTP budget or code is spent and + * reveals nothing about any saved operation. */ + beforeProof?: () => void, + ) { + const browser = await loadBrowser(request); + checkCsrf(request, browser); + const principal = await authentication.requireSession(request); + const proofRequired = () => + new HttpError( + 403, + "ArrivalProofRequired", + "Verify the destination email again", + ); + if (!principal?.emailVerified || !otp) throw proofRequired(); + beforeProof?.(); + await rateLimit(`${purpose}:${principal.userId}`); + const proof = await authentication.verifySignInCode({ + email: principal.email, + otp, + }); + const identity = proof.ok ? proof.principal : null; + if ( + !identity?.emailVerified || + identity.userId !== principal.userId || + identity.email !== principal.email + ) + throw proofRequired(); + return identity; + }; +} diff --git a/src/features/external-migration/manage-arrival.ts b/src/features/external-migration/manage-arrival.ts new file mode 100644 index 0000000..fefcb35 --- /dev/null +++ b/src/features/external-migration/manage-arrival.ts @@ -0,0 +1,295 @@ +import type * as plc from "@did-plc/lib"; +import type { + BrowserAuthentication, + BrowserRequest, +} from "../../authentication/port.js"; +import { DomainError } from "../../accounts/errors.js"; +import type { OperationOwnership } from "../../accounts/operation-ownership.js"; +import type { ArrivalTransactor } from "../../database/migration-journal.port.js"; +import type { OperationClaim } from "../../database/operation-ownership.port.js"; +import { HttpError } from "../../http/http-error.mjs"; +import { readIncomingObservation } from "../../plc/incoming-observation.js"; +import type { ArrivalAggregate } from "./arrival-types.js"; +import { createFreshArrivalProof } from "./fresh-proof.js"; +import { generateArrivalCode } from "./prepare-arrival.js"; + +export interface ArrivalLifecycleInput { + readonly operationId: string; + readonly expectedVersion: number; +} + +/** Secret-free outcome. Renewal alone carries the one-time replacement code. */ +export interface RenewedArrival { + readonly operationId: string; + readonly version: number; + readonly arrivalCode: string; + readonly expiresAt: number; +} + +export interface CancelledArrival { + readonly operationId: string; + readonly version: number; + readonly state: "cancelled"; +} + +const notFound = () => + new DomainError("AccountNotFound", 404, "Arrival not found"); + +const versionConflict = () => + new DomainError( + "OperationConflict", + 409, + "The saved arrival changed; reload the operation and retry", + ); + +const parseInput = (input: unknown): ArrivalLifecycleInput => { + const value = input as Record | null; + if ( + !value || + typeof value !== "object" || + typeof value.operationId !== "string" || + value.operationId.length < 1 || + value.operationId.length > 200 || + typeof value.expectedVersion !== "number" || + !Number.isSafeInteger(value.expectedVersion) || + value.expectedVersion < 1 + ) + throw new HttpError( + 400, + "InvalidRequest", + "An operation and expected version are required", + ); + return { + operationId: value.operationId, + expectedVersion: value.expectedVersion, + }; +}; + +/** Saved-user renewal and cancellation. They select the arrival only through + * the verified browser owner, never mutate a private workflow journal beyond + * the 009 conditional primitives and cannot release persisted obligations. */ +export function createArrivalLifecycle({ + arrivals, + ownership, + authentication, + checkCsrf, + loadBrowser, + rateLimit, + plcClient, +}: { + arrivals: ArrivalTransactor; + ownership: OperationOwnership; + authentication: BrowserAuthentication; + checkCsrf: (request: BrowserRequest, browser: unknown) => void; + loadBrowser: (request: BrowserRequest) => Promise; + rateLimit: (subject: string) => Promise; + plcClient: plc.Client; +}) { + const requireFreshProof = createFreshArrivalProof({ + authentication, + checkCsrf, + loadBrowser, + rateLimit, + }); + /** Unknown operation and another user's operation are the same 404. */ + const read = async ( + operationId: string, + userId: string, + ): Promise => { + const aggregate = await arrivals.readArrivalAggregate(operationId, userId); + if (!aggregate) throw notFound(); + return aggregate; + }; + const underOwner = async ( + aggregate: ArrivalAggregate, + work: (owner: OperationClaim, current: ArrivalAggregate) => Promise, + /** Another request finished the pending claim first. Maps the re-read + * state to its stable outcome, or returns to rethrow the original error. */ + finished: (current: ArrivalAggregate) => T | undefined, + ): Promise => { + const saved = aggregate.arrival; + try { + return await resumeUnderOwner(saved, work); + } catch (error) { + if ( + !( + error instanceof DomainError && + error.code === "OperationNoLongerPending" + ) + ) + throw error; + const outcome = finished(await read(saved.operationId, saved.userId)); + if (outcome === undefined) throw error; + return outcome; + } + }; + const resumeUnderOwner = ( + saved: ArrivalAggregate["arrival"], + work: (owner: OperationClaim, current: ArrivalAggregate) => Promise, + ): Promise => { + return ownership.resumePending( + `arrival:${saved.did}`, + saved.operationId, + { + kind: "public-arrival", + request: { + did: saved.did, + handle: saved.handle, + userId: saved.userId, + }, + }, + async () => { + const owner = ownership.currentClaim; + if (!owner) + throw new DomainError( + "OperationLeaseLost", + 409, + "Arrival owner unavailable", + ); + await ownership.assertActive(); + return work(owner, await read(saved.operationId, saved.userId)); + }, + ); + }; + const refuseInactive = (aggregate: ArrivalAggregate): void => { + if ( + aggregate.arrival.cancelledAt !== null || + aggregate.progress.provisionedAt !== null + ) + throw new HttpError( + 409, + "ArrivalExpired", + "This arrival is no longer actionable", + ); + }; + const refuseUnsafe = (message: string): never => { + throw new DomainError("OperationRecoveryRequired", 409, message); + }; + return { + /** A fresh destination proof issues a replacement one-time code for the same + * arrival. It performs no allocation, dispatch or obligation release. */ + async renew( + request: BrowserRequest, + otp: string, + input: unknown, + ): Promise { + let parsed: ArrivalLifecycleInput | undefined; + const principal = await requireFreshProof( + request, + otp, + "incoming-renew", + () => { + parsed = parseInput(input); + }, + ); + const { operationId, expectedVersion } = parsed!; + const initial = await read(operationId, principal.userId); + // A finished or cancelled arrival has no pending owner to resume. + refuseInactive(initial); + return underOwner( + initial, + async (_owner, aggregate) => { + const saved = aggregate.arrival; + if (saved.version !== expectedVersion) throw versionConflict(); + refuseInactive(aggregate); + // Recorded admissions survive rotation; only new use of the old code ends. + const code = generateArrivalCode(); + const renewed = await arrivals.rotateArrivalCode({ + operationId, + expectedVersion, + ownerUserId: principal.userId, + codeHash: code.hash, + codeExpiresAt: code.expiresAt, + }); + return { + operationId: renewed.operationId, + version: renewed.version, + arrivalCode: code.code, + expiresAt: code.expiresAt, + }; + }, + (current) => { + refuseInactive(current); + return undefined; + }, + ); + }, + /** Cancels only an internal pre-intent arrival: no allocation, signed + * operation, admission, attempt or progress, and an unchanged canonical PLC + * head. It never claims to release a remote reservation or private material. */ + async cancel( + request: BrowserRequest, + otp: string, + input: unknown, + ): Promise { + let parsed: ArrivalLifecycleInput | undefined; + const principal = await requireFreshProof( + request, + otp, + "incoming-cancel", + () => { + parsed = parseInput(input); + }, + ); + const { operationId, expectedVersion } = parsed!; + const initial = await read(operationId, principal.userId); + const cancelled = (aggregate: ArrivalAggregate): CancelledArrival => ({ + operationId, + version: aggregate.arrival.version, + state: "cancelled", + }); + return underOwner( + initial, + async (owner, aggregate) => { + if (aggregate.arrival.cancelledAt !== null) { + // A crash between the local cancel and completing its pending claim + // must not leave the DID blocked, so an exact retry completes it. + await ownership.checkpoint("complete", null); + return cancelled(aggregate); + } + const saved = aggregate.arrival; + if (saved.version !== expectedVersion) throw versionConflict(); + const progress = aggregate.progress; + if ( + aggregate.reservation !== null || + aggregate.signedOperations.length > 0 || + aggregate.admissions.length > 0 || + aggregate.attempts.length > 0 || + progress.provisionedAt !== null || + progress.deactivatedAt !== null || + progress.boundAt !== null || + progress.completedAt !== null || + progress.canonicalHandoffCid !== null + ) + refuseUnsafe( + "Cancellation cannot release remote obligations for this arrival", + ); + // An unacknowledged external attempt is a remote obligation by definition. + if (await ownership.pendingExternal(`arrival:${saved.did}`)) + refuseUnsafe( + "Cancellation cannot release remote obligations for this arrival", + ); + const directory = await readIncomingObservation(plcClient, saved.did); + if (directory.sourcePlcHead !== saved.sourcePlcHead) + refuseUnsafe( + "Canonical identity changed; keep the arrival pending", + ); + const result = await arrivals.cancelArrival({ + owner, + operationId, + expectedVersion, + ownerUserId: principal.userId, + noRemoteObligation: true, + plcStateUnchanged: true, + }); + if (result.kind === "reconciliation-required") + return refuseUnsafe("Cancellation requires reconciliation"); + await ownership.checkpoint("complete", null); + return { operationId, version: result.version, state: "cancelled" }; + }, + (current) => + current.arrival.cancelledAt !== null ? cancelled(current) : undefined, + ); + }, + }; +} diff --git a/src/features/external-migration/prepare-arrival.ts b/src/features/external-migration/prepare-arrival.ts index aa2fcf6..0380e78 100644 --- a/src/features/external-migration/prepare-arrival.ts +++ b/src/features/external-migration/prepare-arrival.ts @@ -2,9 +2,9 @@ import { createHash, randomBytes } from "node:crypto"; import { ensureValidHandle } from "@atproto/syntax"; import type { BrowserAuthentication, - BrowserPrincipal, BrowserRequest, } from "../../authentication/port.js"; +import { createFreshArrivalProof } from "./fresh-proof.js"; import type { createOperationOwnership } from "../../accounts/operation-ownership.js"; import { incomingRotationKeys } from "../../plc/policy.js"; import { readIncomingObservation } from "../../plc/incoming-observation.js"; @@ -159,34 +159,18 @@ export function createIncomingPreparation({ reserveSigningKey: (request: ReservationRequest) => Promise; }) { const reservation = createArrivalPreparation({ arrivals, reserveSigningKey }); + const requireFreshProof = createFreshArrivalProof({ + authentication, + checkCsrf, + loadBrowser, + rateLimit, + }); return async function prepareArrival( request: BrowserRequest, otp: string, input: { did: string; handle: string }, ) { - const browser = await loadBrowser(request); - checkCsrf(request, browser); - const principal: BrowserPrincipal | null = - await authentication.requireSession(request); - const proofRequired = () => - new HttpError( - 403, - "ArrivalProofRequired", - "Verify the destination email again", - ); - if (!principal?.emailVerified || !otp) throw proofRequired(); - await rateLimit(`incoming-prepare:${principal.userId}`); - const proof = await authentication.verifySignInCode({ - email: principal.email, - otp, - }); - const identity = proof.ok ? proof.principal : null; - if ( - !identity?.emailVerified || - identity.userId !== principal.userId || - identity.email !== principal.email - ) - throw proofRequired(); + const identity = await requireFreshProof(request, otp, "incoming-prepare"); if (!/^did:plc:[a-z2-7]{24}$/.test(input.did)) throw new HttpError(400, "InvalidRequest", "A PLC DID is required"); ensureValidHandle(input.handle); @@ -198,7 +182,7 @@ export function createIncomingPreparation({ request: { did: input.did, handle: input.handle, - userId: principal.userId, + userId: identity.userId, }, }, async () => { diff --git a/src/features/external-migration/provision-arrival.ts b/src/features/external-migration/provision-arrival.ts index 1958e30..5361b44 100644 --- a/src/features/external-migration/provision-arrival.ts +++ b/src/features/external-migration/provision-arrival.ts @@ -7,7 +7,10 @@ import type { OperationClaim } from "../../database/operation-ownership.port.js" import { incomingCreationMethod } from "./incoming-authorization.js"; import type { OperationOwnership } from "../../accounts/operation-ownership.js"; import type { OperationOwnershipStore } from "../../database/operation-ownership.port.js"; -import type { ArrivalAggregate } from "./arrival-types.js"; +import { + isRecordedAdmissionGeneration, + type ArrivalAggregate, +} from "./arrival-types.js"; import type { Secp256k1MigrationPlcSigner } from "../../plc/signing.js"; import * as Plc from "@did-plc/lib"; import { validateIncomingHandoff } from "../../plc/policy.js"; @@ -68,7 +71,7 @@ export function createDurableArrivalProvisioning({ !accepted || accepted.userId !== saved.userId || accepted.did !== saved.did || - accepted.generation !== saved.generation + !isRecordedAdmissionGeneration(accepted.generation, saved.generation) ) throw new DomainError( "AccountMismatch", diff --git a/src/features/external-migration/submit-handoff.ts b/src/features/external-migration/submit-handoff.ts index dd54763..5c82496 100644 --- a/src/features/external-migration/submit-handoff.ts +++ b/src/features/external-migration/submit-handoff.ts @@ -3,8 +3,12 @@ import type { OperationClaim } from "../../database/operation-ownership.port.js" import { cidForCbor } from "@atproto/common"; import type * as plc from "@did-plc/lib"; import { DomainError } from "../../accounts/errors.js"; +import { HttpError } from "../../http/http-error.mjs"; import type { OperationOwnership } from "../../accounts/operation-ownership.js"; -import type { ArrivalAggregate } from "./arrival-types.js"; +import { + isRecordedAdmissionGeneration, + type ArrivalAggregate, +} from "./arrival-types.js"; import { incomingHandoffMethod, incomingCreationMethod, @@ -99,7 +103,7 @@ export function createAuthenticatedArrival({ !handoff || admission.userId !== saved.userId || admission.did !== saved.did || - admission.generation !== saved.generation + !isRecordedAdmissionGeneration(admission.generation, saved.generation) ) throw new DomainError( "AccountMismatch", @@ -188,7 +192,36 @@ export function createAuthenticatedArrival({ input.userId, async (owner, aggregate) => { const saved = aggregate.arrival; + // Before any request comparison or credential work, so a superseded, + // garbage or expired code fails identically whether or not an + // admission exists for the body. This read neither consumes the code + // nor advances the saved version. + const current = + typeof input.arrivalCode === "string" + ? await arrivals.consumeArrivalCode({ + codeHash: arrivalCodeHash(input.arrivalCode), + did: saved.did, + method: input.method, + }) + : null; + if (current?.operationId !== saved.operationId) + throw new HttpError( + 409, + "ArrivalExpired", + "This arrival code is no longer valid", + ); const parsed = parseArrivalRequest(saved, input.method, input.body); + const recorded = aggregate.admissions.find( + (item) => item.method === input.method, + ); + // The digest binds the code generation, so a body admitted before a + // renewal can never match again; resubmission cannot succeed. + if (recorded && recorded.requestDigest !== parsed.requestDigest) + throw new DomainError( + "OperationConflict", + 409, + "This request was already admitted; resume the saved arrival instead of resubmitting", + ); const authorization = await verify({ presentation: input.presentation, method: input.method, @@ -265,7 +298,10 @@ export function createAuthenticatedArrival({ !accepted || accepted.userId !== aggregate.arrival.userId || accepted.did !== aggregate.arrival.did || - accepted.generation !== aggregate.arrival.generation + !isRecordedAdmissionGeneration( + accepted.generation, + aggregate.arrival.generation, + ) ) throw new DomainError( "AccountMismatch", diff --git a/tests/contracts/incoming-arrival-composition.test.mjs b/tests/contracts/incoming-arrival-composition.test.mjs index eb66e42..a58760a 100644 --- a/tests/contracts/incoming-arrival-composition.test.mjs +++ b/tests/contracts/incoming-arrival-composition.test.mjs @@ -7,6 +7,7 @@ import { incomingHandoffMethod, incomingCreationMethod, } from "../../dist/src/features/external-migration/incoming-authorization.js"; +import { arrivalCodeHash } from "../../dist/src/features/external-migration/prepare-arrival.js"; import { parseArrivalRequest } from "../../dist/src/features/external-migration/arrival-request.js"; import { mkdtempSync, rmSync } from "node:fs"; import { join } from "node:path"; @@ -154,9 +155,11 @@ async function fixture(t, mode = "modern", mutation = "", fault = "") { kind: "better-auth", authenticatedAt: new Date(), }; + let verifications = 0; const authentication = { requireSession: async () => principal, verifySignInCode: async ({ email: destinationEmail, otp }) => { + verifications++; assert.equal(destinationEmail, email); return { ok: otp === "fresh-otp", @@ -183,6 +186,14 @@ async function fixture(t, mode = "modern", mutation = "", fault = "") { store: { ...store, async checkpoint(...args) { + if ( + fault === "after-commit-complete-fails" && + args[1].phase === "complete" && + !completionFailed + ) { + completionFailed = true; + throw new Error("completion interrupted"); + } if (fault === "before-checkpoint") throw new Error("checkpoint fault"); await store.checkpoint(...args); if (fault === "after-checkpoint") throw new Error("checkpoint fault"); @@ -191,6 +202,7 @@ async function fixture(t, mode = "modern", mutation = "", fault = "") { }, heartbeatMs: 0, }); + let completionFailed = false; let publicationMode = "normal"; let directoryReads = 0; let credentialsIssued = 0; @@ -423,6 +435,7 @@ async function fixture(t, mode = "modern", mutation = "", fault = "") { repository, composed, reservations: () => reservations, + verifications: () => verifications, prepare: (otp = "fresh-otp") => composed.prepareArrival(request, otp, { did, handle }), }; @@ -467,6 +480,8 @@ for (const mode of ["modern", "legacy"]) { "admitCreation", "bindPending", "prepareArrival", + "renewArrival", + "cancelArrival", "admitIncoming", "continueHandoff", "continueCreation", @@ -1547,3 +1562,692 @@ test("existing actor under handoff cannot reconcile a previously saved move", as receipt.id, ); }); + +const renew = (f, operationId, expectedVersion, otp = "fresh-otp") => + f.composed.renewArrival(f.request, otp, { operationId, expectedVersion }); +const cancel = (f, operationId, expectedVersion, otp = "fresh-otp") => + f.composed.cancelArrival(f.request, otp, { operationId, expectedVersion }); +const consume = (f, code) => + f.arrivals.consumeArrivalCode({ + codeHash: arrivalCodeHash(code), + did: f.did, + method: "com.atproto.server.createAccount", + }); +const stored = async (f) => ({ + arrivals: await query(f.db, "SELECT * FROM arrivals"), + code: await query(f.db, "SELECT * FROM arrival_code"), + reservations: await query(f.db, "SELECT * FROM arrival_reservations"), +}); + +test("renewal recovers a lost preparation response without another allocation", async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + assert.equal(f.reservations(), 1); + const renewed = await renew(f, prepared.operationId, prepared.version); + assert.deepEqual(Object.keys(renewed).sort(), [ + "arrivalCode", + "expiresAt", + "operationId", + "version", + ]); + assert.equal(renewed.operationId, prepared.operationId); + assert.equal(renewed.version, prepared.version + 1); + assert.notEqual(renewed.arrivalCode, prepared.arrivalCode); + // The prior generation fails the same way an unknown code does. + assert.equal(await consume(f, prepared.arrivalCode), null); + assert.equal( + (await consume(f, renewed.arrivalCode)).operationId, + prepared.operationId, + ); + const rows = await stored(f); + assert.equal(rows.arrivals.length, 1); + assert.equal(rows.reservations.length, 1); + assert.equal(f.reservations(), 1); + assert.equal( + JSON.stringify(rows).includes(renewed.arrivalCode), + false, + "only a hash is persisted", + ); + // The reservation obligation is untouched and no second operation exists. + assert.equal(rows.reservations[0].signing_key, f.repository.did()); + assert.equal( + (await query(f.db, "SELECT * FROM operation_admissions")).length, + 1, + ); +}); + +test("renewal after a lost reservation response keeps the pending allocation", async (t) => { + const f = await fixture(t, "modern", "lost"); + await assert.rejects(f.prepare()); + const saved = (await stored(f)).arrivals[0]; + const renewed = await renew(f, saved.operation_id, saved.version); + assert.equal(renewed.version, saved.version + 1); + assert.equal(f.reservations(), 1); + const rows = await stored(f); + assert.equal(rows.reservations.length, 1); + assert.equal(rows.reservations[0].signing_key, null); +}); + +test("stale or simultaneous renewal conflicts and one generation survives", async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + const results = await Promise.allSettled([ + renew(f, prepared.operationId, prepared.version), + renew(f, prepared.operationId, prepared.version), + ]); + assert.equal(results.filter((item) => item.status === "fulfilled").length, 1); + const failed = results.find((item) => item.status === "rejected"); + assert.equal(failed.reason.code, "OperationConflict"); + const winner = results.find((item) => item.status === "fulfilled").value; + assert.equal((await consume(f, winner.arrivalCode)) !== null, true); + assert.equal((await stored(f)).code[0].generation, 2); + await assert.rejects(renew(f, prepared.operationId, prepared.version), { + code: "OperationConflict", + }); + // The saved version, not a guess, advances the next renewal. + const second = await renew(f, prepared.operationId, winner.version); + assert.equal(await consume(f, winner.arrivalCode), null); + assert.notEqual(await consume(f, second.arrivalCode), null); +}); + +for (const operation of [renew, cancel]) { + test(`${operation === renew ? "renewal" : "cancellation"} treats another owner and an unknown operation identically`, async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + const before = await stored(f); + const unknown = await operation(f, "unknown-operation", 1).catch( + (error) => error, + ); + f.principal.userId = "other-user"; + const foreign = await operation(f, prepared.operationId, 1).catch( + (error) => error, + ); + f.principal.userId = "destination-user"; + for (const error of [unknown, foreign]) { + assert.equal(error.code, "AccountNotFound"); + assert.equal(error.status, 404); + } + assert.equal(foreign.message, unknown.message); + assert.deepEqual(await stored(f), before); + }); + + test(`${operation === renew ? "renewal" : "cancellation"} refuses missing proof, stale proof and browser origin or CSRF violations`, async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + const before = await stored(f); + const call = (otp) => operation(f, prepared.operationId, 1, otp); + for (const otp of ["", "stale-otp"]) + await assert.rejects(call(otp), { + error: "ArrivalProofRequired", + status: 403, + }); + f.request.headers.origin = "https://wrong.example.test"; + await assert.rejects(call("fresh-otp")); + f.request.headers.origin = "https://entryway.example.test"; + const csrf = f.request.body.csrf; + f.request.body.csrf = "wrong"; + await assert.rejects(call("fresh-otp")); + f.request.body.csrf = csrf; + f.principal.emailVerified = false; + await assert.rejects(call("fresh-otp"), { + error: "ArrivalProofRequired", + status: 403, + }); + f.principal.emailVerified = true; + for (const body of [ + { operationId: prepared.operationId }, + { operationId: prepared.operationId, expectedVersion: "1" }, + { operationId: prepared.operationId, expectedVersion: 0 }, + { operationId: 7, expectedVersion: 1 }, + ]) + await assert.rejects( + f.composed[operation === renew ? "renewArrival" : "cancelArrival"]( + f.request, + "fresh-otp", + body, + ), + { error: "InvalidRequest", status: 400 }, + ); + assert.deepEqual(await stored(f), before); + assert.equal(f.reservations(), 1); + }); +} + +const inviteFor = async (f) => { + const { createInvites } = + await import("../../dist/src/features/account-registration/invites.mjs"); + const invites = await createInvites({ + db: f.db, + config: f.config, + accounts: { get: async () => null }, + }); + return (await invites.createInviteCode({ useCount: 1 })).code; +}; +const admitHandoff = async (f, prepared) => + f.composed.admitIncoming(f.request, { + operationId: prepared.operationId, + method: incomingHandoffMethod, + body: { operation: await plc.signOperation(prepared.handoff, f.source) }, + presentation: await f.credential(), + arrivalCode: prepared.arrivalCode, + }); +const admitCreation = async (f, prepared, arrivalCode, inviteCode) => + f.composed.admitIncoming(f.request, { + operationId: prepared.operationId, + method: incomingCreationMethod, + body: { handle, inviteCode }, + presentation: await f.credential(incomingCreationMethod), + arrivalCode, + }); +const versionOf = async (f, prepared) => + (await f.arrivals.readArrival(prepared.operationId, "destination-user")) + .version; + +test("renewal after the handoff admission keeps its continuation and supersedes the old code for new admissions", async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + await admitHandoff(f, prepared); + const signed = await query(f.db, "SELECT * FROM arrival_signed_operations"); + const admissions = await query(f.db, "SELECT * FROM arrival_replay"); + const renewed = await renew( + f, + prepared.operationId, + await versionOf(f, prepared), + ); + // The recorded admission and signed facts are untouched and nothing new is + // reserved, signed or published by renewal. + assert.deepEqual( + await query(f.db, "SELECT * FROM arrival_replay"), + admissions, + ); + assert.deepEqual( + await query(f.db, "SELECT * FROM arrival_signed_operations"), + signed, + ); + assert.equal(f.reservations(), 1); + assert.equal(f.publicationAttempts.length, 1); + assert.equal(admissions[0].generation, 1); + const continued = await f.composed.continueHandoff( + f.request, + prepared.operationId, + ); + assert.equal(continued.state, "published"); + assert.equal(f.publicationAttempts.length, 1); + // A superseded code admits nothing new and consumes nothing; the new one does. + const invite = await inviteFor(f); + await assert.rejects( + admitCreation(f, prepared, prepared.arrivalCode, invite), + { + error: "ArrivalExpired", + status: 409, + }, + ); + assert.equal((await query(f.db, "SELECT * FROM arrival_replay")).length, 1); + assert.equal( + (await admitCreation(f, prepared, renewed.arrivalCode, invite)).state, + "admitted", + ); + const replay = await query(f.db, "SELECT * FROM arrival_replay"); + assert.deepEqual(replay.map((row) => row.generation).sort(), [1, 2]); + const result = await f.composed.continueCreation( + f.request, + prepared.operationId, + ); + assert.equal(result.state, "pending"); + assert.equal(f.backendState.creates, 1); + assert.equal(f.reservations(), 1); + assert.equal(f.publicationAttempts.length, 1); + assert.equal( + (await query(f.db, "SELECT * FROM arrival_signed_operations")).length, + 2, + ); +}); + +test("renewal after the creation admission leaves the creation continuation able to complete", async (t) => { + const f = await fixture(t); + const prepared = await admitProvisioning(f); + const admissions = await query(f.db, "SELECT * FROM arrival_replay"); + const renewed = await renew( + f, + prepared.operationId, + await versionOf(f, prepared), + ); + assert.notEqual(renewed.arrivalCode, prepared.arrivalCode); + assert.deepEqual( + await query(f.db, "SELECT * FROM arrival_replay"), + admissions, + ); + assert.equal(await consume(f, prepared.arrivalCode), null); + const result = await f.composed.continueCreation( + f.request, + prepared.operationId, + ); + assert.equal(result.state, "pending"); + assert.equal(f.backendState.creates, 1); + assert.equal(f.reservations(), 1); + assert.equal(f.publicationAttempts.length, 1); + // Reconciliation also resumes from the saved admissions, not the new code. + await f.composed.reconcileArrival(f.request, prepared.operationId); + assert.equal(f.backendState.creates, 1); + assert.equal(f.reservations(), 1); +}); + +test("an admission recorded above the current generation is never continued", async (t) => { + const f = await fixture(t); + const prepared = await admitProvisioning(f); + await f.db.update( + "arrival_replay", + { generation: 5 }, + eq(f.db.tables.arrival_replay.operation_id, prepared.operationId), + ); + await assert.rejects( + f.composed.continueCreation(f.request, prepared.operationId), + { code: "AccountMismatch" }, + ); + assert.equal(f.backendState.creates, 0); +}); + +test("cancelling a prepared arrival retains every obligation", async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + const before = await stored(f); + const admissions = await query(f.db, "SELECT * FROM operation_admissions"); + await assert.rejects(cancel(f, prepared.operationId, prepared.version), { + code: "OperationRecoveryRequired", + status: 409, + }); + assert.deepEqual(await stored(f), before); + assert.deepEqual( + await query(f.db, "SELECT * FROM operation_admissions"), + admissions, + ); + assert.equal((await stored(f)).arrivals[0].cancelled_at, null); + assert.notEqual(await consume(f, prepared.arrivalCode), null); + assert.equal(f.reservations(), 1); +}); + +test("cancelling an admitted arrival with signed facts retains every obligation", async (t) => { + const g = await fixture(t); + const admitted = await admitProvisioning(g); + const saved = await g.arrivals.readArrival( + admitted.operationId, + "destination-user", + ); + const kept = await stored(g); + await assert.rejects(cancel(g, admitted.operationId, saved.version), { + code: "OperationRecoveryRequired", + }); + assert.deepEqual(await stored(g), kept); +}); + +test("cancelling a stale version conflicts before any obligation check", async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + await assert.rejects(cancel(f, prepared.operationId, prepared.version + 5), { + code: "OperationConflict", + }); +}); + +test("pre-intent cancellation releases local state only with unchanged canonical PLC head and is idempotent", async (t) => { + const f = await fixture(t, "modern", "", "after-commit-release"); + await assert.rejects(f.prepare(), /interrupted before allocation intent/); + const saved = (await stored(f)).arrivals[0]; + assert.equal((await stored(f)).reservations.length, 0); + // A changed canonical head blocks cancellation. + const { sig: _signature, ...unsigned } = f.predecessor; + const descendant = await plc.signOperation( + { + ...unsigned, + prev: f.head, + alsoKnownAs: ["at://changed.example.test"], + }, + f.source, + ); + f.audit.push({ + did: f.did, + operation: descendant, + cid: String(await cidForCbor(descendant)), + nullified: false, + createdAt: new Date().toISOString(), + }); + await assert.rejects(cancel(f, saved.operation_id, saved.version), { + code: "OperationRecoveryRequired", + }); + assert.equal((await stored(f)).arrivals[0].active, 1); + f.audit.pop(); + const cancelled = await cancel(f, saved.operation_id, saved.version); + assert.deepEqual(cancelled, { + operationId: saved.operation_id, + version: saved.version + 1, + state: "cancelled", + }); + const rows = await stored(f); + assert.equal(rows.arrivals[0].active, 0); + assert.notEqual(rows.arrivals[0].cancelled_at, null); + assert.equal(rows.reservations.length, 0); + assert.equal( + (await query(f.db, "SELECT * FROM operation_admissions")).length, + 0, + ); + assert.equal(f.reservations(), 0); + // History is retained and an exact retry is idempotent, even after the + // saved version has advanced. + assert.deepEqual( + await cancel(f, saved.operation_id, saved.version), + cancelled, + ); + assert.deepEqual( + await cancel(f, saved.operation_id, cancelled.version), + cancelled, + ); + await assert.rejects(renew(f, saved.operation_id, cancelled.version), { + error: "ArrivalExpired", + status: 409, + }); +}); + +const preIntent = async (t, fault = "after-commit-release") => { + const f = await fixture(t, "modern", "", fault); + await assert.rejects(f.prepare(), /interrupted before allocation intent/); + return { f, saved: (await stored(f)).arrivals[0] }; +}; +const pendingOperations = async (f) => + (await query(f.db, "SELECT * FROM authority_operations")).filter((row) => + Boolean(row.pending), + ).length; +const admissionRows = async (f) => + (await query(f.db, "SELECT * FROM operation_admissions")).length; + +test("concurrent cancellations are both idempotent and never leak a lost-claim error", async (t) => { + const { f, saved } = await preIntent(t); + const results = await Promise.allSettled([ + cancel(f, saved.operation_id, saved.version), + cancel(f, saved.operation_id, saved.version), + ]); + assert.deepEqual( + results.map((item) => item.status), + ["fulfilled", "fulfilled"], + ); + assert.deepEqual(results[1].value, results[0].value); + assert.equal(results[0].value.state, "cancelled"); + assert.equal(await pendingOperations(f), 0); +}); + +test("renewal racing a cancellation reports the arrival as no longer actionable", async (t) => { + const { f, saved } = await preIntent(t); + const [cancelled, renewed] = await Promise.allSettled([ + cancel(f, saved.operation_id, saved.version), + renew(f, saved.operation_id, saved.version), + ]); + assert.equal(cancelled.status, "fulfilled"); + assert.equal(renewed.status, "rejected"); + assert.equal(renewed.reason.error, "ArrivalExpired"); + assert.equal(renewed.reason.status, 409); +}); + +test("a crash after the local cancel commit leaves the claim pending until an exact retry completes it", async (t) => { + const { f, saved } = await preIntent(t, "after-commit-complete-fails"); + assert.equal(await pendingOperations(f), 1); + assert.equal(await admissionRows(f), 1); + await assert.rejects( + cancel(f, saved.operation_id, saved.version), + /completion interrupted/, + ); + const rows = (await stored(f)).arrivals[0]; + assert.notEqual(rows.cancelled_at, null); + assert.equal(rows.active, 0); + assert.equal(await pendingOperations(f), 1); + assert.equal(await admissionRows(f), 1); + const retried = await cancel(f, saved.operation_id, saved.version); + assert.deepEqual(retried, { + operationId: saved.operation_id, + version: saved.version + 1, + state: "cancelled", + }); + assert.equal(await pendingOperations(f), 0); + assert.equal(await admissionRows(f), 0); +}); + +for (const operation of [renew, cancel]) { + test(`${operation === renew ? "renewal" : "cancellation"} origin and CSRF failures spend no proof or budget`, async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + const purpose = operation === renew ? "incoming-renew" : "incoming-cancel"; + const budget = () => + f.db.get("entryway:limits", `${purpose}:destination-user`); + const verified = f.verifications(); + const before = await budget(); + f.request.headers.origin = "https://wrong.example.test"; + const origin = await operation(f, prepared.operationId, 1).catch((e) => e); + f.request.headers.origin = "https://entryway.example.test"; + const csrf = f.request.body.csrf; + f.request.body.csrf = "wrong"; + const token = await operation(f, prepared.operationId, 1).catch((e) => e); + f.request.body.csrf = csrf; + for (const error of [origin, token]) { + assert.ok(error instanceof Error); + assert.equal(typeof error.status, "number"); + assert.ok(error.status >= 400 && error.status < 500); + assert.notEqual(error.error, "ArrivalProofRequired"); + } + assert.equal(f.verifications(), verified); + assert.deepEqual(await budget(), before); + // A malformed body is refused before the code is verified or budget spent. + await assert.rejects( + f.composed[operation === renew ? "renewArrival" : "cancelArrival"]( + f.request, + "fresh-otp", + { operationId: prepared.operationId }, + ), + { error: "InvalidRequest", status: 400 }, + ); + assert.equal(f.verifications(), verified); + assert.deepEqual(await budget(), before); + }); +} + +test("storage compare-and-swap rejects a stale or racing renewal directly", async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + const rotate = (hash, expectedVersion) => + f.arrivals.rotateArrivalCode({ + operationId: prepared.operationId, + ownerUserId: "destination-user", + expectedVersion, + codeHash: arrivalCodeHash(hash), + codeExpiresAt: Date.now() + 86_400_000, + }); + const results = await Promise.allSettled([ + rotate("first", prepared.version), + rotate("second", prepared.version), + ]); + assert.equal(results.filter((item) => item.status === "fulfilled").length, 1); + assert.equal( + results.find((item) => item.status === "rejected").reason.code, + "OperationConflict", + ); + await assert.rejects(rotate("third", prepared.version), { + code: "OperationConflict", + }); + assert.equal((await stored(f)).code[0].generation, 2); +}); + +test("renewal refuses a provisioned or completed arrival and an uncertain allocation", async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + const table = f.db.tables.arrival_reservations; + await f.db.update( + "arrival_reservations", + { uncertain_reason: "response-lost", uncertain_at: Date.now() }, + eq(table.operation_id, prepared.operationId), + ); + await assert.rejects(renew(f, prepared.operationId, prepared.version), { + code: "OperationRecoveryRequired", + }); + await f.db.update( + "arrival_reservations", + { uncertain_reason: null, uncertain_at: null }, + eq(table.operation_id, prepared.operationId), + ); + const now = Date.now(); + await f.db.update( + "arrivals", + { provisioned_at: now }, + eq(f.db.tables.arrivals.operation_id, prepared.operationId), + ); + await assert.rejects(renew(f, prepared.operationId, prepared.version), { + error: "ArrivalExpired", + status: 409, + }); + await f.db.update( + "arrivals", + { + deactivated_at: now, + bound_at: now, + activation_at: now, + activation_method: "com.atproto.server.activateAccount", + completed_at: now, + }, + eq(f.db.tables.arrivals.operation_id, prepared.operationId), + ); + await assert.rejects(renew(f, prepared.operationId, prepared.version), { + error: "ArrivalExpired", + status: 409, + }); +}); + +test("cancellation refuses a pending external attempt as a remote obligation", async (t) => { + const { f, saved } = await preIntent(t); + const pending = f.ownership.pendingExternal; + f.ownership.pendingExternal = async () => ({ id: "attempt" }); + await assert.rejects(cancel(f, saved.operation_id, saved.version), { + code: "OperationRecoveryRequired", + }); + f.ownership.pendingExternal = pending; + assert.equal((await stored(f)).arrivals[0].active, 1); +}); + +test("a superseded, garbage or expired code fails identically with the contract's expired error", async (t) => { + const f = await fixture(t); + const prepared = await f.prepare(); + const handoff = { + operationId: prepared.operationId, + method: incomingHandoffMethod, + body: { operation: await plc.signOperation(prepared.handoff, f.source) }, + presentation: await f.credential(), + arrivalCode: prepared.arrivalCode, + }; + const admit = (input) => f.composed.admitIncoming(f.request, input); + const snapshot = async () => ({ + stored: await stored(f), + replay: await query(f.db, "SELECT * FROM arrival_replay"), + signed: await query(f.db, "SELECT * FROM arrival_signed_operations"), + attempts: f.publicationAttempts.length, + }); + const outcome = async (input) => { + const before = await snapshot(); + const error = await admit(input).catch((reason) => reason); + assert.deepEqual(await snapshot(), before); + return { error: error.error, status: error.status, message: error.message }; + }; + const expired = { + error: "ArrivalExpired", + status: 409, + message: "This arrival code is no longer valid", + }; + // Exact replay with the current code is idempotent: same facts, no new effects. + assert.equal((await admit(handoff)).state, "published"); + const settled = await snapshot(); + assert.equal((await admit(handoff)).state, "published"); + assert.deepEqual(await snapshot(), settled); + assert.equal(f.publicationAttempts.length, 1); + // Garbage code on an exact replay of an admitted body, before any renewal. + assert.deepEqual( + await outcome({ ...handoff, arrivalCode: "garbage" }), + expired, + ); + assert.deepEqual( + await outcome({ ...handoff, arrivalCode: undefined }), + expired, + ); + // Garbage code on a body with no admission is the same refusal. + const invite = await inviteFor(f); + const creation = { + operationId: prepared.operationId, + method: incomingCreationMethod, + body: { handle, inviteCode: invite }, + presentation: await f.credential(incomingCreationMethod), + arrivalCode: "garbage", + }; + assert.deepEqual(await outcome(creation), expired); + // Superseded code, on both the admitted and the unadmitted body. + const renewed = await renew( + f, + prepared.operationId, + await versionOf(f, prepared), + ); + assert.deepEqual(await outcome(handoff), expired); + assert.deepEqual( + await outcome({ ...creation, arrivalCode: prepared.arrivalCode }), + expired, + ); + // An admitted body re-submitted with the new code can never match again and + // is told to resume instead of "reload and retry". + const resubmit = await admit({ + ...handoff, + arrivalCode: renewed.arrivalCode, + }).catch((e) => e); + assert.equal(resubmit.error, "OperationConflict"); + assert.match(resubmit.message, /already admitted; resume/); + // An expired current code is refused the same way. + await f.db.update( + "arrival_code", + { expires_at: (await stored(f)).code[0].issued_at + 1 }, + eq(f.db.tables.arrival_code.operation_id, prepared.operationId), + ); + assert.deepEqual( + await outcome({ ...creation, arrivalCode: renewed.arrivalCode }), + expired, + ); +}); + +test("isRecordedAdmissionGeneration accepts only generations that have existed", async () => { + const { isRecordedAdmissionGeneration: ok } = + await import("../../dist/src/features/external-migration/arrival-types.js"); + for (const [recorded, current, expected] of [ + [0, 3, false], + [-1, 3, false], + [1.5, 3, false], + [Number.NaN, 3, false], + [Number.MAX_SAFE_INTEGER + 1, Number.MAX_SAFE_INTEGER + 2, false], + [4, 3, false], + [3, 3, true], + [2, 3, true], + [1, 3, true], + ]) + assert.equal(ok(recorded, current), expected, `${recorded}/${current}`); +}); + +test("a too-high recorded generation is refused by the handoff and creation continuations", async (t) => { + const f = await fixture(t); + const prepared = await admitProvisioning(f); + await f.db.update( + "arrival_replay", + { generation: 9 }, + eq(f.db.tables.arrival_replay.operation_id, prepared.operationId), + ); + await assert.rejects( + f.composed.continueHandoff(f.request, prepared.operationId), + { code: "AccountMismatch" }, + ); + await assert.rejects( + f.composed.continueCreation(f.request, prepared.operationId), + { code: "AccountMismatch" }, + ); + const attempts = f.publicationAttempts.length; + await assert.rejects( + f.composed.reconcileArrival(f.request, prepared.operationId), + ); + assert.equal(f.publicationAttempts.length, attempts); + assert.equal(f.backendState.creates, 0); +});