diff --git a/.changeset/incoming-arrival-authority.md b/.changeset/incoming-arrival-authority.md new file mode 100644 index 00000000..a45368a4 --- /dev/null +++ b/.changeset/incoming-arrival-authority.md @@ -0,0 +1,66 @@ +--- +"hypercerts-entryway": minor +--- + +For operators initializing fresh state, the database schema now includes durable +storage for dormant incoming arrivals: an immutable +`{operation, incoming DID, selected PDS and endpoint}` tuple with the saved +verified user and email, a hashed 24-hour arrival authorization, conditional +persistence of the reserved public repository key, and one live arrival per DID +with completed history retained. + +Storage and shared-claim behavior: + +- A destination email used by an individual arrival must be unique. It is no + longer shared with another identity's claim, reservation or live arrival. + Whole-server association imports keep their existing shared-claim behaviour, + so the two paths stay explicitly distinct. +- An arrival authorization is stored only as a hash and must expire no later than + 24 hours after issue. The ceiling is enforced when the code is written and again + by a database constraint, so a reissued or shortened lifetime cannot exceed a + day and code expiry does not release destination reservations or erase progress. +- A saved public key is immutable for its arrival and is included when a valid + arrival code resolves the saved arrival. Reservation-result validation checks + the expected version and owner first: stale versions return `OperationConflict` + and lost ownership returns `OperationLeaseLost`. With current ownership and + version, saved allocation uncertainty returns `OperationRecoveryRequired` before + tuple comparison; otherwise a changed DID, host or endpoint is + `OperationConflict`. A different key for the unchanged tuple returns + `reconciliation-required` with reason `saved-key-differs`. Nothing silently + reallocates or switches placement. +- Cancellation releases local reservations only when the arrival recorded no + allocation at all. The allocation intent is saved before the destination host is + asked for a signing key, so a recorded intent whose key is not yet known already + means dispatch began or is still in flight; cancelling then requires + `OperationRecoveryRequired` and the arrival stays pending for verified recovery. + Cancellation also needs the owning operation's claim and the caller's own + no-remote-obligation and unchanged-PLC evidence; an expired lease authorizes + nothing. Local cancellation never claims remote private material was removed. +- A signed public PLC operation is journaled before it is dispatched. The + source-authorized handoff and the Entryway-signed destination move are stored + with their exact bytes, CID and kind, in the same fenced transaction that + advances the arrival, so an accepted operation is durable before directory + submission and a destination move cannot be recorded ahead of its handoff. + Recorded bytes are immutable: repeating the same operation and CID is + idempotent and changes nothing, while a different operation or CID for the same + kind is a conflict rather than an overwrite. A stale worker records nothing. + Private key material never enters this table, and no new status value is added. +- Preparation requires the actual signed source predecessor, its CID, source + public facts and approved ordered custody. The original source endpoint is + saved from those facts. Signed handoffs and moves must match that authority, + their signed CIDs and the saved destination reservation. +- Accepted admissions are immutable per method and bind the saved principal, + DID, request digest, code generation and verified credential issuer and ID. + Exact retries under current ownership do not advance the version. Creation + admission and invitation reservation can commit together; pending account + binding and invitation completion can also commit together. Bearer credentials, + arrival codes and invitation codes are not stored in arrival admissions. + +Operators must initialize fresh state for the changed database schema. This is +not a database-upgrade procedure or a qualification of public account migration. +- Migration-pending access is derived from the current operation, not a new + account status. An arrival does not gain ordinary access or activation from + storage alone, and no readiness or completeness claim is made here. + +No public route, remote write, credential signing or activation is added by this +change. Readiness and public exposure remain separately gated. diff --git a/.changeset/incoming-arrival-claim-exclusion.md b/.changeset/incoming-arrival-claim-exclusion.md new file mode 100644 index 00000000..2f37e1db --- /dev/null +++ b/.changeset/incoming-arrival-claim-exclusion.md @@ -0,0 +1,7 @@ +--- +"hypercerts-entryway": patch +--- + +For operators managing incoming migrations, active arrivals now reserve their destination email, handle and DID against competing account and migration writes. Existing claims also prevent a conflicting arrival from starting. Expired arrival codes do not release pending reservations; the arrival's own validated binding remains atomic, and established shared-primary-email associations remain supported. + +Cancellation now refuses persisted remote obligations, including a signed source handoff even when no repository-key allocation exists. Keep these arrivals pending for verified recovery rather than releasing their claims. No configuration change is required. diff --git a/.sonarcloud.properties b/.sonarcloud.properties new file mode 100644 index 00000000..c22fa602 --- /dev/null +++ b/.sonarcloud.properties @@ -0,0 +1 @@ +sonar.cpd.exclusions=src/database/schema/postgresql.ts,src/database/schema/sqlite.ts diff --git a/docs/incoming-migration.md b/docs/incoming-migration.md index 0e0cb873..384e741c 100644 --- a/docs/incoming-migration.md +++ b/docs/incoming-migration.md @@ -562,8 +562,17 @@ outcome, and none overwrites an already-saved tuple member. recordAllocationIntent(tx, owner, expectedVersion, {operationId, did, pdsId, endpoint}) recordReservationResult(tx, owner, expectedVersion, {operationId, did, pdsId, endpoint, signingKey}) retainUncertainAttempt(tx, owner, expectedVersion, attemptBinding) +recordSignedOperation(tx, owner, expectedVersion, {operationId, did, kind, operation, cid}) ``` +`recordSignedOperation` journals a signed public PLC operation before it is +dispatched, where `kind` is `handoff` or `destination-move`. The CID must match the +normalized operation bytes, a destination move cannot be recorded before its +handoff, and private key material is rejected. Repeating the same operation and CID +for a kind is idempotent and does not advance the version; a different operation or +CID for that kind is a conflict. A caller holding the pre-record version may receive +`already-settled`, so it must not treat that version as a fresh baseline. + Binding rules these calls must enforce: - The tuple `{operationId, did, pdsId, endpoint}` is immutable after intent. A @@ -616,9 +625,10 @@ derived from the current operation and never stored as a permanent imported-acco category. Account status values remain `provisioning`, `active`, `deactivated` and `deleted` as enforced at `src/accounts/rules.ts:19-39`; no new status value is added. -Pending projection. Existing evidence is `hasPendingExternalMigration` at -`src/database/drizzle/account-storage.ts:631-641`, true while any migration -reservation is not complete. The proposed richer projection is owned by plan 009: +Pending projection. `hasPendingExternalMigration` in +`src/database/drizzle/account-storage.ts` checks both incomplete migration +reservations and active incoming arrivals whose completion checkpoint is absent. +The richer arrival projection is owned by plan 009: ```text readArrivalAccess(did) -> {operationId, version, did, userId, pdsId, provisioned, diff --git a/src/accounts/types.ts b/src/accounts/types.ts index 23939c25..403a8add 100644 --- a/src/accounts/types.ts +++ b/src/accounts/types.ts @@ -92,7 +92,7 @@ export interface ExternalMigrationReservation { targetPdsUrl: string; } -export interface FinalizeImportedAccount { +export interface BindProvisionedArrival { workflowId: string; did: string; userId: string; @@ -102,7 +102,7 @@ export interface FinalizeImportedAccount { pdsUrl: string; } -export interface ActivateImportedAccount { +export interface ActivateBoundArrival { workflowId: string; did: string; userId: string; diff --git a/src/accounts/values.ts b/src/accounts/values.ts index 2b9cb988..6b1b7a6f 100644 --- a/src/accounts/values.ts +++ b/src/accounts/values.ts @@ -9,11 +9,11 @@ export type { } from "../database/accounts.port.js"; export type { AccountRow, - ActivateImportedAccount, + ActivateBoundArrival, AccountStatus, BindVerifiedIdentity, ExternalMigrationReservation, - FinalizeImportedAccount, + BindProvisionedArrival, LegacyVerifiedEmail, OwnerSession, VerifiedBinding, diff --git a/src/database/accounts.port.ts b/src/database/accounts.port.ts index f52d8aa2..069283db 100644 --- a/src/database/accounts.port.ts +++ b/src/database/accounts.port.ts @@ -3,10 +3,10 @@ import type { EmailClaim, StoredEmailClaimPurpose, ExternalEmailReservation, - ActivateImportedAccount, + ActivateBoundArrival, BindVerifiedIdentity, ExternalMigrationReservation, - FinalizeImportedAccount, + BindProvisionedArrival, LegacyVerifiedEmail, OwnerSession, VerifiedBinding, @@ -34,6 +34,8 @@ export interface AccountReader { getVerifiedBinding(did: string): Promise; getVerifiedOwner(input: OwnerSession): Promise; hasPendingExternalMigration(did: string): Promise; + /** Observation only: whether this DID already has a saved published PLC operation. */ + hadPublishedPlcOperation(did: string): Promise; listAccounts(): Promise; } @@ -52,8 +54,8 @@ export interface AccountTransactor extends AccountReader { /** Bind an account to its verified email user. Callers must validate mailbox proof first. */ bindAccountToVerifiedEmailUser(input: LegacyVerifiedEmail): Promise; reserveExternalMigration(input: ExternalMigrationReservation): Promise; - finalizeImportedAccount(input: FinalizeImportedAccount): Promise; - activateImportedAccount(input: ActivateImportedAccount): Promise; + bindProvisionedArrival(input: BindProvisionedArrival): Promise; + activateBoundArrival(input: ActivateBoundArrival): Promise; reserveEmail( email: string, did: string, diff --git a/src/database/drizzle/account-authority.mjs b/src/database/drizzle/account-authority.mjs index 9e6a618a..5c65c212 100644 --- a/src/database/drizzle/account-authority.mjs +++ b/src/database/drizzle/account-authority.mjs @@ -96,6 +96,15 @@ export function createAccountAuthority({ db, accounts }) { } = {}, ) => { email = normalizeEmail(email); + const arrival = await db.read("arrivals", { + where: and( + eq(t.arrivals.active, 1), + eq(sql`lower(${t.arrivals.email})`, email), + ), + limit: 1, + }); + if (arrival.length > 0) + throw fail(409, "EmailNotAvailable", "This email address cannot be used"); const isCurrentEmail = normalizeEmail((await account(did)).email) === email; let existing = await claims(email); for (const pending of existing.filter( diff --git a/src/database/drizzle/account-storage.ts b/src/database/drizzle/account-storage.ts index f135bdfc..7b1b4dd0 100644 --- a/src/database/drizzle/account-storage.ts +++ b/src/database/drizzle/account-storage.ts @@ -1,5 +1,5 @@ import { randomUUID } from "node:crypto"; -import { and, asc, desc, eq, ne, sql } from "drizzle-orm"; +import { and, asc, desc, eq, ne, or, sql } from "drizzle-orm"; import { assertAccountShape, assertBindingMatchesAccount, @@ -187,6 +187,38 @@ export function createAccountStorage( return null; return { userId: user.id, email: user.email, authenticatedAt }; }; + const assertNoActiveArrival = async ( + email: string, + did?: string, + handle?: string, + ) => { + const arrivals = await db.read("arrivals", { + where: and( + eq(t.arrivals.active, 1), + or( + eq(sql`lower(${t.arrivals.email})`, normalizeEmail(email)), + did ? eq(t.arrivals.did, did) : undefined, + handle + ? eq(sql`lower(${t.arrivals.handle})`, handle.trim().toLowerCase()) + : undefined, + ), + ), + }); + if (arrivals.some((arrival) => arrival.did === did)) + throw new DomainError( + "IdentityConflict", + 409, + "Identity has a pending arrival", + ); + if (arrivals.some((arrival) => arrival.email === normalizeEmail(email))) + throw new DomainError( + "EmailNotAvailable", + 409, + "Email address is reserved", + ); + if (arrivals.length > 0) + throw new DomainError("HandleNotAvailable", 409, "Handle is reserved"); + }; const reserveEmail = async ( email: string, did: string, @@ -195,6 +227,7 @@ export function createAccountStorage( ) => db.transact(async () => { email = normalizeEmail(email); + await assertNoActiveArrival(email, did); const [claims, reservations] = await Promise.all([ db.read("email_claims", { where: eq(sql`lower(${t.email_claims.email})`, email), @@ -242,6 +275,18 @@ export function createAccountStorage( const reserveHandle = async (handle: string, did: string) => db.transact(async () => { handle = handle.trim().toLowerCase(); + const arrival = await one( + "arrivals", + and( + eq(t.arrivals.active, 1), + or( + eq(sql`lower(${t.arrivals.handle})`, handle), + eq(t.arrivals.did, did), + ), + )!, + ); + if (arrival) + throw new DomainError("HandleNotAvailable", 409, "Handle is reserved"); const external = await one( "migration_reservations", eq(t.migration_reservations.handle, handle), @@ -281,6 +326,7 @@ export function createAccountStorage( assertPds(row); try { await db.transact(async () => { + await assertNoActiveArrival(row.email, row.did, row.handle); const previous = ( await db.read("accounts", { orderBy: [desc(t.accounts.sequence)], @@ -309,6 +355,7 @@ export function createAccountStorage( assertPds(row); try { await db.transact(async () => { + await assertNoActiveArrival(row.email, row.did, row.handle); const previous = await getByDid(row.did); if (!previous) throw new DomainError("AccountNotFound", 404, "Account not found"); @@ -499,6 +546,7 @@ export function createAccountStorage( "Recent verified owner session required", ); const email = normalizeEmail(owner.email); + await assertNoActiveArrival(email, input.did, input.handle); const [emailClaims, emailReservations] = await Promise.all([ db.read("email_claims", { where: eq(sql`lower(${t.email_claims.email})`, email), @@ -618,14 +666,24 @@ export function createAccountStorage( ); }, async hasPendingExternalMigration(did) { - return Boolean( - await one( + const [adopting, arrival] = await Promise.all([ + one( "migration_reservations", and( eq(t.migration_reservations.did, did), ne(t.migration_reservations.state, "complete"), )!, ), + one( + "arrivals", + and(eq(t.arrivals.did, did), eq(t.arrivals.active, 1))!, + ), + ]); + return Boolean(adopting || arrival); + }, + async hadPublishedPlcOperation(did) { + return Boolean( + await one("custody_operations", eq(t.custody_operations.did, did)), ); }, async listAccounts() { @@ -659,7 +717,7 @@ export function createAccountStorage( and(eq(t.handle_claims.handle, handle), eq(t.handle_claims.did, did))!, ); }, - async finalizeImportedAccount(input) { + async bindProvisionedArrival(input) { return db.transact(async () => { const reservation = await one( "migration_reservations", @@ -735,7 +793,7 @@ export function createAccountStorage( return row; }); }, - async activateImportedAccount(input) { + async activateBoundArrival(input) { return db.transact(async () => { const reservation = await one( "migration_reservations", diff --git a/src/database/drizzle/migration-arrival.ts b/src/database/drizzle/migration-arrival.ts new file mode 100644 index 00000000..d5774a26 --- /dev/null +++ b/src/database/drizzle/migration-arrival.ts @@ -0,0 +1,1513 @@ +import * as plc from "@did-plc/lib"; +import { cidForCbor } from "@atproto/common"; +import { and, desc, eq, isNull, ne, or, sql } from "drizzle-orm"; +import { DomainError } from "../../accounts/errors.js"; +import { normalizeEmail } from "../../accounts/rules.js"; +import type { ArrivalTransactor } from "../migration-journal.port.js"; +import type { OperationClaim } from "../operation-ownership.port.js"; +import type { DatabaseExecutor, StoredRow } from "../executor.js"; +import { isObservedArrivalActivation } from "../../features/external-migration/arrival-types.js"; +import type { + ArrivalAccess, + ArrivalRecord, + ArrivalSignedOperationRecord, +} from "../../features/external-migration/arrival-types.js"; +import { PlcError } from "../../plc/errors.js"; +import { + validateHistoryOperation, + validateIncomingHandoff, + publicRotationKey, +} from "../../plc/policy.js"; + +const signingKeyPattern = /^did:key:z[1-9A-HJ-NP-Za-km-z]+$/; +const digestPattern = /^[a-f0-9]{64}$/; +const arrivalLifetimeMs = 86_400_000; + +const versionConflict = () => + new DomainError( + "OperationConflict", + 409, + "The saved arrival changed; reload the operation and retry", + ); +const notActionable = () => + new DomainError( + "OperationConflict", + 409, + "This arrival is no longer actionable", + ); +const recoveryRequired = () => + new DomainError( + "OperationRecoveryRequired", + 409, + "The saved arrival allocation is uncertain. Keep the arrival pending for verified recovery.", + ); +const immutableTuple = () => + new DomainError( + "OperationConflict", + 409, + "The arrival operation, DID, host and endpoint cannot change", + ); + +/** Account-authority writes the arrival transaction must compose atomically. */ +export interface ArrivalAuthority { + readAccount(did: string): Promise; + readBinding(did: string): Promise; + reserveEmailClaim( + email: string, + did: string, + purpose: "primary", + ownerUserId: string, + ): Promise; + reserveHandleClaim(handle: string, did: string): Promise; + insertPlacedAccount(input: { + did: string; + email: string; + handle: string; + pdsId: string; + pdsUrl: string; + userId: string; + }): Promise; + recordSavedUserBinding(did: string, userId: string): Promise; +} + +const canonicalFact = (value: unknown): string => { + if (Array.isArray(value)) return `[${value.map(canonicalFact).join(",")}]`; + if (typeof value === "object" && value !== null) + return `{${Object.entries(value) + .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) + .map(([key, item]) => `${JSON.stringify(key)}:${canonicalFact(item)}`) + .join(",")}}`; + return JSON.stringify(value); +}; +const carriesPrivateMaterial = (value: Record): boolean => + ["signature", "privateKey", "privateKeys"].some((key) => key in value); +const sameTuple = ( + saved: StoredRow<"arrival_signed_operations">, + input: ArrivalSignedOperationRecord, +): boolean => + saved.did === input.did && + saved.cid === input.cid && + canonicalFact(JSON.parse(saved.operation)) === canonicalFact(input.operation); +function arrivalRecord( + row: StoredRow<"arrivals">, + reservation: StoredRow<"arrival_reservations"> | undefined, + code: StoredRow<"arrival_code"> | undefined, +): ArrivalRecord { + return { + operationId: row.operation_id, + did: row.did, + userId: row.user_id, + email: row.email, + handle: row.handle, + pdsId: row.pds_id, + endpoint: row.endpoint, + sourcePlcHead: row.source_plc_head, + sourcePredecessor: JSON.parse(row.source_predecessor), + source: JSON.parse(row.source_facts), + approvedRotationKeys: JSON.parse(row.approved_rotation_keys), + version: row.version, + codeHash: code?.code_hash ?? "", + codeGeneration: code?.generation ?? 0, + codeExpiresAt: code?.expires_at ?? 0, + generation: row.generation, + signingKey: reservation?.signing_key ?? null, + codeDelivered: code !== undefined, + cancelledAt: row.cancelled_at, + }; +} + +export function createArrivalStorage( + db: DatabaseExecutor, + configuredPds: readonly { readonly id: string; readonly url: string }[], + authority: ArrivalAuthority, +): ArrivalTransactor { + const table = db.tables.arrivals; + const codeTable = db.tables.arrival_code; + const reservationTable = db.tables.arrival_reservations; + const replayTable = db.tables.arrival_replay; + const familyTable = db.tables.arrival_families; + const signedTable = db.tables.arrival_signed_operations; + + const row = async (operationId: string) => + ( + await db.read("arrivals", { + where: eq(table.operation_id, operationId), + limit: 1, + }) + )[0]; + const reservation = async (operationId: string) => + ( + await db.read("arrival_reservations", { + where: eq(reservationTable.operation_id, operationId), + limit: 1, + }) + )[0]; + const code = async (operationId: string) => + ( + await db.read("arrival_code", { + where: eq(codeTable.operation_id, operationId), + limit: 1, + }) + )[0]; + + const current = async (operationId: string, expectedVersion: number) => { + const saved = await row(operationId); + if (!saved) + throw new DomainError("AccountNotFound", 404, "Arrival not found"); + if ( + !Number.isSafeInteger(expectedVersion) || + saved.version !== expectedVersion + ) + throw versionConflict(); + return saved; + }; + + const currentOwnedArrival = async ( + operationId: string, + ownerUserId: string, + expectedVersion: number, + ) => { + const saved = ( + await db.read("arrivals", { + where: and( + eq(table.operation_id, operationId), + eq(table.user_id, ownerUserId), + ), + limit: 1, + }) + )[0]; + if (!saved) + throw new DomainError("AccountNotFound", 404, "Arrival not found"); + if ( + !Number.isSafeInteger(expectedVersion) || + saved.version !== expectedVersion + ) + throw versionConflict(); + return saved; + }; + + const immutable = ( + saved: StoredRow<"arrivals">, + input: { + readonly operationId: string; + readonly did: string; + readonly pdsId: string; + readonly endpoint: string; + }, + ) => { + if ( + saved.operation_id !== input.operationId || + saved.did !== input.did || + saved.pds_id !== input.pdsId || + saved.endpoint !== input.endpoint + ) + throw immutableTuple(); + }; + + const assertConfiguredHost = (pdsId: string, endpoint: string) => { + if (!configuredPds.some((pds) => pds.id === pdsId && pds.url === endpoint)) + throw new DomainError("InvalidAccount", 400, "Unknown target data host"); + }; + + const assertExpiry = async (issuedAt: number, expiresAt: number) => { + if ( + !Number.isSafeInteger(expiresAt) || + expiresAt <= issuedAt || + expiresAt > issuedAt + arrivalLifetimeMs + ) + throw new DomainError( + "InvalidAccount", + 400, + "An arrival authorization lasts at most 24 hours from issue", + ); + }; + + const assertClaim = (owner: OperationClaim) => { + if (!owner?.operationId || !owner.workerId || !owner.attemptId) + throw new DomainError( + "OperationScopeMismatch", + 409, + "A current operation owner is required", + ); + }; + + const assertArrivalOwnership = async ( + owner: OperationClaim, + saved: StoredRow<"arrivals">, + ) => { + await db.assertOperationFence(owner); + const admissions = db.tables.operation_admissions; + const binding = ( + await db.read("operation_admissions", { + where: and( + eq(admissions.resource, `arrival:${saved.did}`), + eq(admissions.operation_id, owner.operationId), + ), + limit: 1, + }) + )[0]; + if (!binding) throw versionConflict(); + }; + + const externalReceipt = async ( + owner: OperationClaim, + saved: StoredRow<"arrivals">, + input: import("../../features/external-migration/arrival-types.js").ArrivalExternalAttempt, + ) => { + await assertArrivalOwnership(owner, saved); + if (saved.did !== input.did || saved.active === 0) throw immutableTuple(); + const receipt = ( + await db.read("external_operation_attempts", { + where: eq( + db.tables.external_operation_attempts.id, + input.externalAttemptId, + ), + limit: 1, + }) + )[0]; + const method = + input.step === "incoming-creation" + ? "com.atproto.server.createAccount" + : input.step === "incoming-pause" + ? "com.atproto.admin.updateSubjectStatus" + : null; + if ( + !receipt || + receipt.operation_id !== owner.operationId || + receipt.step !== input.step || + receipt.target !== saved.endpoint || + receipt.method !== method + ) + throw immutableTuple(); + return receipt; + }; + + const assertFreeDestination = async ( + email: string, + did: string, + handle: string, + ignoreOperationId: string, + ) => { + if ( + (await authority.readAccount(did)) || + (await authority.readBinding(did)) + ) + throw new DomainError("IdentityConflict", 409, "Identity already hosted"); + const hosted = await db.read("accounts", { + where: eq(sql`lower(${db.tables.accounts.handle})`, handle), + limit: 1, + }); + if (hosted.length > 0) + throw new DomainError( + "HandleNotAvailable", + 409, + "Handle is already hosted", + ); + const handleClaims = await db.read("handle_claims", { + where: eq(sql`lower(${db.tables.handle_claims.handle})`, handle), + limit: 1, + }); + if (handleClaims.length > 0) + throw new DomainError("HandleNotAvailable", 409, "Handle is reserved"); + const migrationClaims = await db.read("migration_reservations", { + where: and( + ne(db.tables.migration_reservations.state, "complete"), + or( + eq(db.tables.migration_reservations.did, did), + eq(sql`lower(${db.tables.migration_reservations.handle})`, handle), + ), + ), + }); + if (migrationClaims.some((claim) => claim.did === did)) + throw new DomainError("IdentityConflict", 409, "Identity is reserved"); + if (migrationClaims.length > 0) + throw new DomainError("HandleNotAvailable", 409, "Handle is reserved"); + const emailAccounts = await db.read("accounts", { + where: eq(sql`lower(${db.tables.accounts.email})`, email), + limit: 1, + }); + if (emailAccounts.length > 0) + throw new DomainError( + "EmailNotAvailable", + 409, + "Destination email is already hosted", + ); + const claims = await db.read("email_claims", { + where: eq(sql`lower(${db.tables.email_claims.email})`, email), + }); + if (claims.length > 0) + throw new DomainError( + "EmailNotAvailable", + 409, + "Destination email is already claimed", + ); + const adopting = await db.read("migration_reservations", { + where: eq(sql`lower(${db.tables.migration_reservations.email})`, email), + }); + if (adopting.some(({ state }) => state !== "complete")) + throw new DomainError( + "EmailNotAvailable", + 409, + "Destination email is reserved by another operation", + ); + const pending = await db.read("arrivals", { + where: and(eq(sql`lower(${table.email})`, email), eq(table.active, 1)), + }); + if (pending.some(({ operation_id }) => operation_id !== ignoreOperationId)) + throw new DomainError( + "EmailNotAvailable", + 409, + "Destination email is reserved by another arrival", + ); + const handleHolders = await db.read("arrivals", { + where: and(eq(sql`lower(${table.handle})`, handle), eq(table.active, 1)), + }); + if ( + handleHolders.some( + ({ operation_id, provisioned_at }) => + operation_id !== ignoreOperationId && provisioned_at === null, + ) + ) + throw new DomainError( + "HandleNotAvailable", + 409, + "Handle is reserved by another arrival", + ); + }; + + const advance = async ( + saved: StoredRow<"arrivals">, + values: Partial>, + ) => { + const version = saved.version + 1; + const updated_at = await db.databaseTime(); + const changed = await db.update( + "arrivals", + { ...values, version, updated_at }, + and( + eq(table.operation_id, saved.operation_id), + eq(table.version, saved.version), + )!, + ); + if (changed !== 1) throw versionConflict(); + return version; + }; + + return { + async readArrivalAggregate(operationId, ownerUserId) { + return db.transact(async () => { + const saved = await row(operationId); + if (!saved || saved.user_id !== ownerUserId) return null; + const binding = await reservation(operationId); + const signed = await db.read("arrival_signed_operations", { + where: eq(signedTable.operation_id, operationId), + }); + const admissions = await db.read("arrival_replay", { + where: eq(replayTable.operation_id, operationId), + }); + const attempts = await db.read("arrival_attempts", { + where: eq(db.tables.arrival_attempts.operation_id, operationId), + }); + return { + arrival: arrivalRecord(saved, binding, await code(operationId)), + signedOperations: signed.map((item) => ({ + operationId, + did: item.did, + kind: item.kind as "handoff" | "destination-move", + cid: item.cid, + operation: JSON.parse(item.operation), + ...(item.kind === "destination-move" + ? { repositoryKey: binding!.signing_key! } + : {}), + })) as ArrivalSignedOperationRecord[], + admissions: admissions.map((item) => ({ + operationId, + did: item.did, + userId: item.user_id, + method: item.method, + requestDigest: item.request_digest, + credentialIssuer: item.credential_issuer, + credentialJti: item.credential_jti, + generation: item.generation, + })), + reservation: binding + ? { + signingKey: binding.signing_key, + uncertainReason: binding.uncertain_reason, + } + : null, + progress: { + provisionedAt: saved.provisioned_at, + deactivatedAt: saved.deactivated_at, + boundAt: saved.bound_at, + completedAt: saved.completed_at, + canonicalHandoffCid: saved.canonical_handoff_cid, + }, + attempts: attempts.map((item) => ({ + ownershipOperationId: item.ownership_operation_id, + attemptId: item.attempt_id, + fence: item.fence, + reason: item.reason, + })), + }; + }); + }, + async recordCanonicalHandoff(owner, expectedVersion, input) { + assertClaim(owner); + return db.transact(async () => + db.withOperationFence(owner, async () => { + await db.assertOperationFence(owner); + const saved = await row(input.operationId); + if (!saved) throw notActionable(); + await assertArrivalOwnership(owner, saved); + if (saved.did !== input.did || saved.active === 0) + throw notActionable(); + const handoff = ( + await db.read("arrival_signed_operations", { + where: and( + eq(signedTable.operation_id, input.operationId), + eq(signedTable.kind, "handoff"), + ), + limit: 1, + }) + )[0]; + if (!handoff || handoff.cid !== input.cid) throw immutableTuple(); + if (saved.canonical_handoff_cid === input.cid) + return { kind: "already-settled" as const, version: saved.version }; + if (saved.version !== expectedVersion) throw versionConflict(); + return { + kind: "applied" as const, + version: await advance(saved, { canonical_handoff_cid: input.cid }), + }; + }), + ); + }, + async createArrival(input) { + const email = normalizeEmail(input.email); + try { + const predecessor = plc.def.compatibleOp.parse(input.sourcePredecessor); + if ( + canonicalFact(predecessor) !== canonicalFact(input.sourcePredecessor) + ) + throw immutableTuple(); + const normalized = plc.normalizeOp(predecessor); + const { sig: _signature, ...sourceFacts } = normalized; + validateHistoryOperation(sourceFacts); + if (String(await cidForCbor(predecessor)) !== input.sourcePlcHead) + throw immutableTuple(); + const source = { + services: normalized.services, + verificationMethods: normalized.verificationMethods, + alsoKnownAs: normalized.alsoKnownAs, + }; + if (canonicalFact(source) !== canonicalFact(input.source)) + throw immutableTuple(); + if ( + input.approvedRotationKeys.length < 2 || + input.approvedRotationKeys.length > 5 || + new Set(input.approvedRotationKeys).size !== + input.approvedRotationKeys.length + ) + throw immutableTuple(); + input.approvedRotationKeys.forEach(publicRotationKey); + } catch { + throw new DomainError( + "InvalidAccount", + 400, + "Actual signed source preparation authority is required", + ); + } + if ( + !input.operationId || + !input.did.startsWith("did:") || + !input.handle || + input.handle !== input.handle.trim().toLowerCase() || + !input.sourcePlcHead + ) + throw new DomainError( + "InvalidAccount", + 400, + "Invalid arrival operation", + ); + assertConfiguredHost(input.pdsId, input.endpoint); + await assertExpiry(await db.databaseTime(), input.codeExpiresAt); + const saved = await row(input.operationId); + if (saved) { + if ( + saved.did !== input.did || + saved.user_id !== input.userId || + saved.email !== email || + saved.handle !== input.handle || + saved.pds_id !== input.pdsId || + saved.endpoint !== input.endpoint || + saved.source_plc_head !== input.sourcePlcHead || + canonicalFact(JSON.parse(saved.source_predecessor)) !== + canonicalFact(input.sourcePredecessor) || + canonicalFact(JSON.parse(saved.source_facts)) !== + canonicalFact(input.source) || + canonicalFact(JSON.parse(saved.approved_rotation_keys)) !== + canonicalFact(input.approvedRotationKeys) + ) + throw immutableTuple(); + if (saved.active === 0) throw notActionable(); + return arrivalRecord( + saved, + await reservation(saved.operation_id), + await code(saved.operation_id), + ); + } + await db.transact(async () => { + const user = ( + await db.read("user", { + where: eq(db.tables.user.id, input.userId), + limit: 1, + }) + )[0]; + if (!user?.emailVerified || user.email !== email) + throw new DomainError( + "AccountMismatch", + 403, + "A verified destination owner is required", + ); + await assertFreeDestination( + email, + input.did, + input.handle, + input.operationId, + ); + const now = await db.databaseTime(); + await db.insert("arrivals", { + operation_id: input.operationId, + did: input.did, + did_root: input.did, + active: 1, + user_id: input.userId, + email, + handle: input.handle, + pds_id: input.pdsId, + endpoint: input.endpoint, + source_plc_head: input.sourcePlcHead, + source_endpoint: input.source.services.atproto_pds?.endpoint, + source_predecessor: JSON.stringify(input.sourcePredecessor), + source_facts: JSON.stringify(input.source), + approved_rotation_keys: JSON.stringify(input.approvedRotationKeys), + version: 1, + generation: 1, + created_at: now, + updated_at: now, + }); + await db.insert("arrival_code", { + operation_id: input.operationId, + code_hash: input.codeHash, + generation: 1, + issued_at: now, + expires_at: input.codeExpiresAt, + }); + }); + return arrivalRecord( + (await row(input.operationId))!, + await reservation(input.operationId), + await code(input.operationId), + ); + }, + + async readArrival(operationId, ownerUserId) { + const saved = await row(operationId); + if (!saved || saved.user_id !== ownerUserId || saved.active === 0) + return null; + return arrivalRecord( + saved, + await reservation(operationId), + await code(operationId), + ); + }, + + async consumeArrivalCode({ codeHash, did, method }) { + if (!digestPattern.test(codeHash) || !method.startsWith("com.atproto.")) + return null; + return db.transact(async () => { + const saved = ( + await db.read("arrival_code", { + where: eq(codeTable.code_hash, codeHash), + limit: 1, + }) + )[0]; + if (!saved) return null; + const owner = await row(saved.operation_id); + if (!owner || owner.active === 0 || owner.did !== did) return null; + if (saved.expires_at <= (await db.databaseTime())) return null; + if (saved.generation !== owner.generation) return null; + return arrivalRecord( + owner, + await reservation(saved.operation_id), + saved, + ); + }); + }, + + async rotateArrivalCode(input) { + return db.transact(async () => { + const saved = await currentOwnedArrival( + input.operationId, + input.ownerUserId, + input.expectedVersion, + ); + if (saved.active === 0) throw notActionable(); + await assertExpiry(await db.databaseTime(), input.codeExpiresAt); + const binding = await reservation(input.operationId); + if (binding?.uncertain_reason) throw recoveryRequired(); + if (saved.provisioned_at !== null) throw notActionable(); + const now = await db.databaseTime(); + const generation = saved.generation + 1; + await db.update( + "arrival_code", + { + code_hash: input.codeHash, + generation, + issued_at: now, + expires_at: input.codeExpiresAt, + }, + eq(codeTable.operation_id, input.operationId), + ); + await advance(saved, { generation }); + return arrivalRecord( + { ...saved, generation, version: saved.version + 1 }, + binding, + { + operation_id: input.operationId, + code_hash: input.codeHash, + generation, + issued_at: now, + expires_at: input.codeExpiresAt, + }, + ); + }); + }, + + async recordAllocationIntent(owner, expectedVersion, input) { + assertClaim(owner); + return db.transact(async () => { + const saved = await current(input.operationId, expectedVersion); + await assertArrivalOwnership(owner, saved); + immutable(saved, input); + if (saved.active === 0) throw notActionable(); + return db.withOperationFence(owner, async () => { + const existing = await reservation(input.operationId); + if (existing?.signing_key || existing?.uncertain_reason) + throw immutableTuple(); + const now = await db.databaseTime(); + if (!existing) + await db.insert("arrival_reservations", { + operation_id: input.operationId, + signing_key: null, + uncertain_reason: null, + uncertain_at: null, + recorded_at: now, + }); + return { + kind: "applied" as const, + version: await advance(saved, {}), + }; + }); + }); + }, + + async recordReservationResult(owner, expectedVersion, input) { + assertClaim(owner); + if (!signingKeyPattern.test(input.signingKey)) + throw new DomainError( + "InvalidAccount", + 400, + "A validated public did:key is required", + ); + return db.transact(async () => { + const saved = await current(input.operationId, expectedVersion); + await assertArrivalOwnership(owner, saved); + const uncertain = (await reservation(input.operationId)) + ?.uncertain_reason; + if (uncertain) throw recoveryRequired(); + immutable(saved, input); + if (saved.active === 0) throw notActionable(); + return db.withOperationFence(owner, async () => { + const existing = await reservation(input.operationId); + if (!existing || existing.uncertain_reason) throw recoveryRequired(); + if (existing.signing_key && existing.signing_key !== input.signingKey) + return { + kind: "reconciliation-required" as const, + reason: "saved-key-differs" as const, + }; + const now = await db.databaseTime(); + if (!existing.signing_key) + await db.update( + "arrival_reservations", + { + signing_key: input.signingKey, + uncertain_reason: null, + uncertain_at: null, + recorded_at: now, + }, + eq(reservationTable.operation_id, input.operationId), + ); + return { + kind: "applied" as const, + version: await advance(saved, {}), + }; + }); + }); + }, + + async recordSignedOperation(owner, expectedVersion, input) { + assertClaim(owner); + if (!input.operationId || !input.did.startsWith("did:")) + throw new DomainError( + "InvalidAccount", + 400, + "A signed operation belongs to one arrival and DID", + ); + if ( + "repositoryKey" in input && + !signingKeyPattern.test(input.repositoryKey) + ) + throw new DomainError( + "InvalidAccount", + 400, + "A destination move names one validated public repository key", + ); + if (carriesPrivateMaterial(input.operation)) + throw new DomainError( + "InvalidAccount", + 400, + "Signed public facts never carry private material", + ); + const { sig, ...facts } = input.operation; + if (typeof sig !== "string" || sig.length === 0) + throw new DomainError( + "InvalidAccount", + 400, + "A signed PLC operation is required", + ); + let validated: unknown; + try { + validated = validateHistoryOperation(facts); + } catch (error) { + if (!(error instanceof PlcError)) throw error; + throw new DomainError( + "InvalidAccount", + 400, + "A normalized public PLC operation is required", + ); + } + const signedOperation = { + ...(validated as Record), + sig, + }; + if (input.cid !== String(await cidForCbor(signedOperation))) + throw new DomainError( + "OperationConflict", + 409, + "The signed operation does not match its CID", + ); + return db.transact(async () => { + const saved = await row(input.operationId); + if (!saved) + throw new DomainError("AccountNotFound", 404, "Arrival not found"); + await assertArrivalOwnership(owner, saved); + if (saved.did !== input.did) throw immutableTuple(); + if (saved.active === 0) throw notActionable(); + return db.withOperationFence(owner, async () => { + await db.assertOperationFence(owner); + const savedKinds = await db.read("arrival_signed_operations", { + where: eq(signedTable.operation_id, input.operationId), + }); + const recorded = savedKinds.find( + (savedRow) => savedRow.kind === input.kind, + ); + if (recorded) { + if (!sameTuple(recorded, input)) throw immutableTuple(); + return { + kind: "already-settled" as const, + version: saved.version, + }; + } + if ( + !Number.isSafeInteger(expectedVersion) || + saved.version !== expectedVersion + ) + throw versionConflict(); + if (input.kind === "destination-move") { + if (!savedKinds.some((savedRow) => savedRow.kind === "handoff")) + throw new DomainError( + "OperationConflict", + 409, + "A destination move follows a saved source handoff", + ); + if ( + input.repositoryKey !== + (await reservation(input.operationId))?.signing_key + ) + throw immutableTuple(); + const handoff = savedKinds.find( + (savedRow) => savedRow.kind === "handoff", + )!; + const approved: string[] = JSON.parse(saved.approved_rotation_keys); + const move = plc.def.operation.parse(signedOperation); + if ( + move.verificationMethods.atproto !== input.repositoryKey || + move.prev !== handoff.cid || + move.services.atproto_pds?.endpoint !== saved.endpoint || + move.services.atproto_pds?.type !== "AtprotoPersonalDataServer" || + !move.alsoKnownAs.includes(`at://${saved.handle}`) || + canonicalFact(move.rotationKeys) !== canonicalFact(approved) + ) + throw immutableTuple(); + try { + await plc.assureValidSig(approved, move); + } catch { + throw immutableTuple(); + } + } else { + try { + await validateIncomingHandoff({ + operation: signedOperation, + expectedPredecessor: JSON.parse(saved.source_predecessor), + approvedRotationKeys: JSON.parse(saved.approved_rotation_keys), + source: JSON.parse(saved.source_facts), + }); + if (facts.prev !== saved.source_plc_head) throw immutableTuple(); + } catch { + throw immutableTuple(); + } + } + await db.insert("arrival_signed_operations", { + operation_id: input.operationId, + kind: input.kind, + did: input.did, + cid: input.cid, + operation: JSON.stringify(signedOperation), + kind_operation_cid: `${input.kind}:${input.cid}`, + recorded_at: await db.databaseTime(), + }); + return { + kind: "applied" as const, + version: await advance(saved, {}), + }; + }); + }); + }, + + async retainUncertainAttempt(owner, expectedVersion, input) { + assertClaim(owner); + return db.transact(async () => { + const saved = await current(input.operationId, expectedVersion); + await assertArrivalOwnership(owner, saved); + immutable(saved, input); + return db.withOperationFence(owner, async () => { + const existing = await reservation(input.operationId); + if (!existing) throw recoveryRequired(); + const now = await db.databaseTime(); + if (!existing.uncertain_reason) + await db.update( + "arrival_reservations", + { + uncertain_reason: input.reason, + uncertain_at: now, + recorded_at: now, + }, + eq(reservationTable.operation_id, input.operationId), + ); + await db.insert( + "arrival_attempts", + { + attempt_binding: `${input.operationId}:${owner.attemptId}:${owner.fence}`, + ownership_operation_id: owner.operationId, + attempt_id: owner.attemptId, + operation_id: input.operationId, + reason: input.reason, + recorded_at: now, + fence: owner.fence, + }, + { ignoreConflict: true }, + ); + await advance(saved, {}); + return { + kind: "reconciliation-required" as const, + reason: "uncertain-attempt" as const, + }; + }); + }); + }, + + async associateArrivalAttempt(owner, expectedVersion, input) { + assertClaim(owner); + return db.transact(() => + db.withOperationFence(owner, async () => { + const saved = await current(input.operationId, expectedVersion); + const receipt = await externalReceipt(owner, saved, input); + const attemptBinding = `${input.operationId}:external:${receipt.id}`; + const existing = ( + await db.read("arrival_attempts", { + where: eq( + db.tables.arrival_attempts.attempt_binding, + attemptBinding, + ), + limit: 1, + }) + )[0]; + if (existing) { + if ( + existing.ownership_operation_id !== receipt.operation_id || + existing.attempt_id !== receipt.id || + existing.fence !== receipt.fence + ) + throw immutableTuple(); + return { kind: "already-settled" as const, version: saved.version }; + } + // A recovered receipt may belong to an older dispatcher. Only an already + // acknowledged receipt can be associated after that dispatcher's fence. + if ( + receipt.state !== "acknowledged" && + (receipt.fence !== owner.fence || + receipt.execution_attempt_id !== owner.attemptId || + receipt.worker_id !== owner.workerId) + ) + throw versionConflict(); + await db.insert("arrival_attempts", { + attempt_binding: attemptBinding, + ownership_operation_id: receipt.operation_id, + attempt_id: receipt.id, + operation_id: input.operationId, + reason: `external:${input.step}`, + recorded_at: await db.databaseTime(), + fence: receipt.fence, + }); + return { + kind: "applied" as const, + version: await advance(saved, {}), + }; + }), + ); + }, + + async settleArrivalAttempt(owner, expectedVersion, input) { + assertClaim(owner); + return db.transact(() => + db.withOperationFence(owner, async () => { + const saved = await current(input.operationId, expectedVersion); + const receipt = await externalReceipt(owner, saved, input); + if (receipt.state !== "acknowledged" || receipt.result !== "null") + throw recoveryRequired(); + const attemptBinding = `${input.operationId}:external:${receipt.id}`; + const association = ( + await db.read("arrival_attempts", { + where: eq( + db.tables.arrival_attempts.attempt_binding, + attemptBinding, + ), + limit: 1, + }) + )[0]; + if ( + !association || + association.ownership_operation_id !== receipt.operation_id || + association.attempt_id !== receipt.id || + association.fence !== receipt.fence || + ![`external:${input.step}`, `settled:${input.step}`].includes( + association.reason, + ) + ) + throw immutableTuple(); + if (association.reason === `settled:${input.step}`) + return { kind: "already-settled" as const, version: saved.version }; + await db.update( + "arrival_attempts", + { reason: `settled:${input.step}` }, + eq(db.tables.arrival_attempts.attempt_binding, attemptBinding), + ); + return { + kind: "applied" as const, + version: await advance(saved, {}), + }; + }), + ); + }, + + async recordArrivalReplay(owner, expectedVersion, facts, proof) { + assertClaim(owner); + if ( + !facts.operationId || + ![ + "com.atproto.identity.submitPlcOperation", + "com.atproto.server.createAccount", + ].includes(facts.method) || + !digestPattern.test(facts.requestDigest) || + !facts.credentialIssuer || + !facts.credentialJti || + facts.credentialIssuer.split("#")[0] !== facts.did + ) + throw versionConflict(); + return db.transact(async () => + db.withOperationFence(owner, async () => { + await db.assertOperationFence(owner); + const saved = await row(facts.operationId); + if (!saved) throw notActionable(); + await assertArrivalOwnership(owner, saved); + if (saved.did !== facts.did || saved.active === 0) + throw notActionable(); + const accepted = ( + await db.read("arrival_replay", { + where: and( + eq(replayTable.operation_id, facts.operationId), + eq(replayTable.method, facts.method), + ), + limit: 1, + }) + )[0]; + if (accepted) { + if ( + accepted.request_digest !== facts.requestDigest || + accepted.did !== facts.did || + accepted.user_id !== saved.user_id || + accepted.credential_issuer !== facts.credentialIssuer || + accepted.credential_jti !== facts.credentialJti + ) + throw versionConflict(); + const credential = ( + await db.read("arrival_replay", { + where: and( + eq(replayTable.credential_issuer, facts.credentialIssuer), + eq(replayTable.credential_jti, facts.credentialJti), + ), + limit: 1, + }) + )[0]; + if ( + credential && + (credential.operation_id !== facts.operationId || + credential.method !== facts.method || + credential.request_digest !== facts.requestDigest) + ) + throw versionConflict(); + return { + operationId: facts.operationId, + generation: accepted.generation, + }; + } + if (saved.version !== expectedVersion) throw versionConflict(); + const authorization = await code(facts.operationId); + if ( + !proof || + !authorization || + authorization.code_hash !== proof.codeHash || + authorization.generation !== proof.codeGeneration || + authorization.generation !== saved.generation || + authorization.expires_at <= (await db.databaseTime()) + ) + throw new DomainError( + "AccountMismatch", + 403, + "A valid current arrival code is required", + ); + const reused = await db.read("arrival_replay", { + where: and( + eq(replayTable.credential_issuer, facts.credentialIssuer), + eq(replayTable.credential_jti, facts.credentialJti), + ), + limit: 1, + }); + if (reused.length) throw versionConflict(); + await db.insert("arrival_replay", { + operation_id: facts.operationId, + method: facts.method, + did: facts.did, + user_id: saved.user_id, + request_digest: facts.requestDigest, + credential_issuer: facts.credentialIssuer, + credential_jti: facts.credentialJti, + generation: saved.generation, + accepted_at: await db.databaseTime(), + }); + await advance(saved, {}); + return { + operationId: facts.operationId, + generation: saved.generation, + }; + }), + ); + }, + + async bindProvisionedArrival(input) { + assertClaim(input.owner); + return db.transact(async () => { + return db.withOperationFence(input.owner, async () => { + const saved = await row(input.operationId); + if (!saved) throw notActionable(); + await assertArrivalOwnership(input.owner, saved); + if ( + saved.did !== input.did || + saved.user_id !== input.userId || + saved.email !== normalizeEmail(input.email) || + saved.handle !== input.handle || + saved.pds_id !== input.pdsId + ) + throw immutableTuple(); + const associations = await db.read("arrival_attempts", { + where: eq( + db.tables.arrival_attempts.operation_id, + input.operationId, + ), + }); + if ( + (await reservation(input.operationId))?.uncertain_reason || + associations.some((association) => + association.reason.startsWith("external:"), + ) + ) + throw recoveryRequired(); + const { provisioned, deactivationObserved } = input.placement; + if (provisioned !== true || deactivationObserved !== true) + throw new DomainError( + "OperationConflict", + 409, + "Observed provisioning and deactivation are required before binding", + ); + if (saved.active === 0) throw notActionable(); + const user = ( + await db.read("user", { + where: eq(db.tables.user.id, input.userId), + limit: 1, + }) + )[0]; + if ( + !user?.emailVerified || + user.email !== normalizeEmail(input.email) + ) + throw new DomainError( + "AccountMismatch", + 403, + "Verified destination owner changed before binding", + ); + if (saved.provisioned_at !== null) { + const account = ( + await db.read("accounts", { + where: eq(db.tables.accounts.did, saved.did), + limit: 1, + }) + )[0]; + const binding = ( + await db.read("account_bindings", { + where: eq(db.tables.account_bindings.did, saved.did), + limit: 1, + }) + )[0]; + const emailClaims = await db.read("email_claims", { + where: eq( + sql`lower(${db.tables.email_claims.email})`, + saved.email, + ), + }); + const handleClaim = ( + await db.read("handle_claims", { + where: eq( + sql`lower(${db.tables.handle_claims.handle})`, + saved.handle, + ), + limit: 1, + }) + )[0]; + const allocation = await reservation(input.operationId); + let payload: unknown; + try { + payload = account ? JSON.parse(account.data) : null; + } catch { + throw versionConflict(); + } + if ( + saved.deactivated_at === null || + saved.bound_at === null || + saved.completed_at !== null || + saved.cancelled_at !== null || + saved.activation_at !== null || + saved.did_root !== saved.did || + !allocation?.signing_key || + allocation.uncertain_reason !== null || + account?.email !== saved.email || + account.handle !== saved.handle || + account.pds_id !== saved.pds_id || + account.status !== "provisioning" || + binding?.user_id !== saved.user_id || + emailClaims.length !== 1 || + emailClaims[0]?.did !== saved.did || + emailClaims[0]?.purpose !== "primary" || + handleClaim?.did !== saved.did || + !payload || + typeof payload !== "object" || + !("did" in payload) || + payload.did !== saved.did || + !("email" in payload) || + payload.email !== saved.email || + !("handle" in payload) || + payload.handle !== saved.handle || + !("pdsId" in payload) || + payload.pdsId !== saved.pds_id || + !("pdsUrl" in payload) || + payload.pdsUrl !== saved.endpoint || + !("status" in payload) || + payload.status !== "provisioning" || + !("emailVerified" in payload) || + payload.emailVerified !== true + ) + throw versionConflict(); + return { kind: "already-settled" as const, version: saved.version }; + } + if ( + !Number.isSafeInteger(input.expectedVersion) || + saved.version !== input.expectedVersion + ) + throw versionConflict(); + if (!(await reservation(input.operationId))?.signing_key) + throw recoveryRequired(); + const email = normalizeEmail(input.email); + await assertFreeDestination( + email, + input.did, + input.handle, + input.operationId, + ); + // Convert only this exact, validated arrival's claims under the same + // transaction lock and owner fence. No other writer can observe the + // temporary release; any failure restores the pending arrival. + await db.update( + "arrivals", + { active: 0, did_root: null }, + eq(table.operation_id, input.operationId), + ); + await authority.insertPlacedAccount({ + did: input.did, + email, + handle: input.handle, + pdsId: input.pdsId, + pdsUrl: saved.endpoint, + userId: input.userId, + }); + await authority.reserveEmailClaim( + email, + input.did, + "primary", + input.userId, + ); + await authority.reserveHandleClaim(input.handle, input.did); + await authority.recordSavedUserBinding(input.did, input.userId); + const now = await db.databaseTime(); + return { + kind: "applied" as const, + version: await advance(saved, { + active: 1, + did_root: saved.did, + provisioned_at: now, + deactivated_at: now, + bound_at: now, + }), + }; + }); + }); + }, + + async completeArrivalActivation(input) { + assertClaim(input.owner); + return db.transact(async () => { + const saved = await current(input.operationId, input.expectedVersion); + await assertArrivalOwnership(input.owner, saved); + if (saved.did !== input.did || saved.user_id !== input.userId) + throw immutableTuple(); + if (saved.active === 0 || saved.bound_at === null) + throw notActionable(); + if (saved.completed_at !== null) + throw new DomainError( + "OperationConflict", + 409, + "This activation is already complete", + ); + if (!isObservedArrivalActivation(input.activation)) + throw new DomainError( + "OperationRecoveryRequired", + 409, + "Activation requires observed backend evidence for this arrival", + ); + return db.withOperationFence(input.owner, async () => { + if (!(await authority.readAccount(input.did))) + throw new DomainError( + "OperationConflict", + 409, + "The bound account is not saved", + ); + await advance(saved, { + activation_method: input.activation!.method, + activation_at: input.activation!.observedAt, + completed_at: await db.databaseTime(), + did_root: null, + active: 0, + }); + return { kind: "applied" as const, version: saved.version + 1 }; + }); + }); + }, + + async readArrivalAccess(did) { + const saved = ( + await db.read("arrivals", { + where: eq(table.did, did), + orderBy: [ + desc(table.active), + desc(table.created_at), + desc(table.updated_at), + desc(table.operation_id), + ], + limit: 1, + }) + )[0]; + if (!saved) return null; + const binding = await reservation(saved.operation_id); + return { + operationId: saved.operation_id, + version: saved.version, + did: saved.did, + userId: saved.user_id, + pdsId: saved.pds_id, + provisioned: saved.provisioned_at !== null, + deactivationObserved: saved.deactivated_at !== null, + bound: saved.bound_at !== null, + complete: saved.completed_at !== null, + unresolvedAttempt: + Boolean(binding?.uncertain_reason) || + ( + await db.read("arrival_attempts", { + where: eq( + db.tables.arrival_attempts.operation_id, + saved.operation_id, + ), + }) + ).some((association) => association.reason.startsWith("external:")), + } satisfies ArrivalAccess; + }, + + async cancelArrival(input) { + assertClaim(input.owner); + return db.transact(async () => { + const saved = await currentOwnedArrival( + input.operationId, + input.ownerUserId, + input.expectedVersion, + ); + await assertArrivalOwnership(input.owner, saved); + if (saved.active === 0) + return { kind: "already-settled" as const, version: saved.version }; + return db.withOperationFence(input.owner, async () => { + const binding = await reservation(input.operationId); + const obligations = await Promise.all( + ( + [ + "arrival_signed_operations", + "arrival_attempts", + "arrival_replay", + "arrival_families", + ] as const + ).map((name) => + db.read(name, { + where: eq(db.tables[name].operation_id, input.operationId), + limit: 1, + }), + ), + ); + if ( + saved.provisioned_at !== null || + saved.deactivated_at !== null || + saved.bound_at !== null || + saved.activation_at !== null || + saved.completed_at !== null || + obligations.some((rows) => rows.length > 0) || + input.noRemoteObligation !== true || + binding !== undefined || + input.plcStateUnchanged !== true + ) + throw new DomainError( + "OperationRecoveryRequired", + 409, + "Cancellation cannot release remote obligations for this arrival", + ); + await advance(saved, { + cancelled_at: await db.databaseTime(), + did_root: null, + active: 0, + }); + return { kind: "applied" as const, version: saved.version + 1 }; + }); + }); + }, + + async recordCredentialFamily(input) { + assertClaim(input.owner); + return db.transact(async () => { + const saved = await current(input.operationId, input.expectedVersion); + await assertArrivalOwnership(input.owner, saved); + if (saved.did !== input.did || saved.pds_id !== input.pdsId) + throw immutableTuple(); + if ( + saved.bound_at === null || + saved.provisioned_at === null || + saved.deactivated_at === null + ) + throw new DomainError( + "OperationConflict", + 409, + "Credentials follow observed provisioning, deactivation and binding", + ); + if (!input.familyId || input.familyId.length > 200) + throw new DomainError( + "InvalidAccount", + 400, + "Invalid credential family", + ); + return db.withOperationFence(input.owner, async () => { + await db.insert( + "arrival_families", + { + family_id: input.familyId, + operation_id: input.operationId, + pds_id: input.pdsId, + created_at: await db.databaseTime(), + revoked_at: null, + }, + { ignoreConflict: true }, + ); + return { + kind: "applied" as const, + version: await advance(saved, {}), + }; + }); + }); + }, + + async revokeArrivalCredentialFamilies(input) { + assertClaim(input.owner); + return db.transact(async () => { + const saved = await current(input.operationId, input.expectedVersion); + await assertArrivalOwnership(input.owner, saved); + if (saved.active === 0) throw notActionable(); + return db.withOperationFence(input.owner, async () => { + await db.update( + "arrival_families", + { revoked_at: await db.databaseTime() }, + and( + eq(familyTable.operation_id, input.operationId), + isNull(familyTable.revoked_at), + )!, + ); + return { + kind: "applied" as const, + version: await advance(saved, {}), + }; + }); + }); + }, + }; +} diff --git a/src/database/migration-journal.port.ts b/src/database/migration-journal.port.ts index 3a93d402..ccc03bd7 100644 --- a/src/database/migration-journal.port.ts +++ b/src/database/migration-journal.port.ts @@ -2,7 +2,25 @@ import type { MigrationWorkflow, SnapshotManifest, } from "../features/external-migration/types.js"; +import type { + ArrivalAccess, + ArrivalExternalAttempt, + ArrivalAggregate, + ArrivalAdmissionProof, + ArrivalPreparationAuthority, + ArrivalActivationEvidence, + ArrivalAllocationIntent, + ArrivalOutcome, + ArrivalPlacementEvidence, + ArrivalRecord, + ArrivalReplayFacts, + ArrivalReplayReuse, + ArrivalReservationResult, + ArrivalSignedOperationRecord, + ArrivalUncertainAttempt, +} from "../features/external-migration/arrival-types.js"; import type { AccountTransactor } from "./accounts.port.js"; +import type { OperationClaim } from "./operation-ownership.port.js"; import type { ExternalMigrationReservation } from "../accounts/types.js"; export interface MigrationStartTransactor { @@ -38,5 +56,137 @@ export interface SnapshotTransactor { } export type DestinationPrincipalPort = Pick< AccountTransactor, - "getVerifiedOwner" | "finalizeImportedAccount" | "activateImportedAccount" + "getVerifiedOwner" | "bindProvisionedArrival" | "activateBoundArrival" >; + +export interface ArrivalTransactor { + readArrivalAggregate( + operationId: string, + ownerUserId: string, + ): Promise; + recordCanonicalHandoff( + owner: OperationClaim, + expectedVersion: number, + input: { operationId: string; did: string; cid: string }, + ): Promise; + createArrival( + input: ArrivalPreparationAuthority & { + operationId: string; + did: string; + userId: string; + email: string; + handle: string; + pdsId: string; + endpoint: string; + sourcePlcHead: string; + codeHash: string; + codeExpiresAt: number; + }, + ): Promise; + /** Selects only this user's live arrival; another owner reads as not found. */ + readArrival( + operationId: string, + ownerUserId: string, + ): Promise; + /** Resolves a presented code hash to its live, unexpired, current generation. */ + consumeArrivalCode(input: { + codeHash: string; + did: string; + method: string; + }): Promise; + rotateArrivalCode(input: { + operationId: string; + expectedVersion: number; + ownerUserId: string; + codeHash: string; + codeExpiresAt: number; + }): Promise; + recordAllocationIntent( + owner: OperationClaim, + expectedVersion: number, + input: ArrivalAllocationIntent, + ): Promise; + recordReservationResult( + owner: OperationClaim, + expectedVersion: number, + input: ArrivalReservationResult, + ): Promise; + /** Immutable signed public handoff or destination move, journaled before dispatch. + * An exact repeat is idempotent without advancing the arrival version; any + * other operation or CID for the same kind conflicts instead of overwriting. */ + recordSignedOperation( + owner: OperationClaim, + expectedVersion: number, + input: ArrivalSignedOperationRecord, + ): Promise; + retainUncertainAttempt( + owner: OperationClaim, + expectedVersion: number, + input: ArrivalUncertainAttempt, + ): Promise; + /** Associate a named generic dispatch under this arrival's persisted resource. */ + associateArrivalAttempt( + owner: OperationClaim, + expectedVersion: number, + input: ArrivalExternalAttempt, + ): Promise; + /** Retire only an associated acknowledged generic receipt, never allocation uncertainty. */ + settleArrivalAttempt( + owner: OperationClaim, + expectedVersion: number, + input: ArrivalExternalAttempt, + ): Promise; + /** Each method admits one immutable request; exact fenced retries do not mutate. */ + recordArrivalReplay( + owner: OperationClaim, + expectedVersion: number, + facts: ArrivalReplayFacts, + proof: ArrivalAdmissionProof, + ): Promise; + /** One fenced transaction: saved user, placement evidence, account and claims. */ + bindProvisionedArrival(input: { + owner: OperationClaim; + expectedVersion: number; + operationId: string; + did: string; + userId: string; + email: string; + handle: string; + pdsId: string; + placement: ArrivalPlacementEvidence; + }): Promise; + /** Separate completion transaction; requires exact version and evidence. */ + completeArrivalActivation(input: { + owner: OperationClaim; + operationId: string; + expectedVersion: number; + did: string; + userId: string; + activation: ArrivalActivationEvidence | null; + }): Promise; + /** Migration-pending projection derived from the current operation. */ + readArrivalAccess(did: string): Promise; + /** Releases local reservations only from caller-supplied safe-point evidence. */ + cancelArrival(input: { + owner: OperationClaim; + operationId: string; + expectedVersion: number; + ownerUserId: string; + noRemoteObligation: boolean; + plcStateUnchanged: boolean; + }): Promise; + /** Never signs or mints a credential; records the association only. */ + recordCredentialFamily(input: { + owner: OperationClaim; + operationId: string; + expectedVersion: number; + familyId: string; + did: string; + pdsId: string; + }): Promise; + revokeArrivalCredentialFamilies(input: { + owner: OperationClaim; + operationId: string; + expectedVersion: number; + }): Promise; +} diff --git a/src/database/schema/postgresql.sql b/src/database/schema/postgresql.sql index bb606dbf..1ae6a054 100644 --- a/src/database/schema/postgresql.sql +++ b/src/database/schema/postgresql.sql @@ -29,6 +29,106 @@ CREATE TABLE "accounts" ( "sequence" bigint NOT NULL UNIQUE ); --> statement-breakpoint +CREATE TABLE "arrival_attempts" ( + "attempt_binding" text PRIMARY KEY, + "ownership_operation_id" text NOT NULL, + "attempt_id" text NOT NULL, + "operation_id" text NOT NULL, + "reason" text NOT NULL, + "recorded_at" bigint NOT NULL, + "fence" bigint NOT NULL +); +--> statement-breakpoint +CREATE TABLE "arrival_code" ( + "operation_id" text PRIMARY KEY, + "code_hash" text NOT NULL, + "generation" bigint NOT NULL, + "issued_at" bigint NOT NULL, + "expires_at" bigint NOT NULL, + CONSTRAINT "arrival_code_lifetime" CHECK ("expires_at" > "issued_at"), + CONSTRAINT "arrival_code_ceiling" CHECK ("expires_at" <= "issued_at" + 86400000) +); +--> statement-breakpoint +CREATE TABLE "arrival_families" ( + "family_id" text PRIMARY KEY, + "operation_id" text NOT NULL, + "pds_id" text NOT NULL, + "created_at" bigint NOT NULL, + "revoked_at" bigint +); +--> statement-breakpoint +CREATE TABLE "arrival_replay" ( + "operation_id" text, + "method" text, + "did" text NOT NULL, + "user_id" text NOT NULL, + "credential_issuer" text NOT NULL, + "credential_jti" text NOT NULL, + "request_digest" text NOT NULL, + "generation" bigint NOT NULL, + "accepted_at" bigint NOT NULL, + CONSTRAINT "arrival_replay_pkey" PRIMARY KEY("operation_id","method"), + CONSTRAINT "arrival_replay_digest" CHECK (length("request_digest") = 64) +); +--> statement-breakpoint +CREATE TABLE "arrival_reservations" ( + "operation_id" text PRIMARY KEY, + "signing_key" text, + "uncertain_reason" text, + "uncertain_at" bigint, + "recorded_at" bigint, + CONSTRAINT "arrival_reservation_evidence" CHECK (("uncertain_reason" IS NULL AND "uncertain_at" IS NULL) OR ("uncertain_reason" IS NOT NULL AND "uncertain_at" IS NOT NULL)), + CONSTRAINT "arrival_reservation_key" CHECK (("signing_key" IS NULL) OR "signing_key" LIKE 'did:key:z%') +); +--> statement-breakpoint +CREATE TABLE "arrival_signed_operations" ( + "operation_id" text, + "kind" text, + "did" text NOT NULL, + "cid" text NOT NULL, + "operation" text NOT NULL, + "kind_operation_cid" text NOT NULL, + "recorded_at" bigint NOT NULL, + CONSTRAINT "arrival_signed_operations_pkey" PRIMARY KEY("operation_id","kind"), + CONSTRAINT "arrival_signed_kind" CHECK ("kind" IN ('handoff','destination-move')), + CONSTRAINT "arrival_signed_did" CHECK ("did" LIKE 'did:%'), + CONSTRAINT "arrival_signed_cid" CHECK ("cid" LIKE 'baf%') +); +--> statement-breakpoint +CREATE TABLE "arrivals" ( + "operation_id" text PRIMARY KEY, + "did" text NOT NULL, + "did_root" text, + "active" integer NOT NULL, + "user_id" text NOT NULL, + "email" text NOT NULL, + "handle" text NOT NULL, + "pds_id" text NOT NULL, + "endpoint" text NOT NULL, + "source_plc_head" text NOT NULL, + "source_endpoint" text, + "canonical_handoff_cid" text, + "source_predecessor" text NOT NULL, + "source_facts" text NOT NULL, + "approved_rotation_keys" text NOT NULL, + "version" bigint NOT NULL, + "generation" bigint NOT NULL, + "created_at" bigint NOT NULL, + "updated_at" bigint NOT NULL, + "cancelled_at" bigint, + "provisioned_at" bigint, + "deactivated_at" bigint, + "bound_at" bigint, + "activation_method" text, + "activation_at" bigint, + "completed_at" bigint, + CONSTRAINT "arrival_active" CHECK ("active" IN (0, 1)), + CONSTRAINT "arrival_tuple" CHECK (("active" = 1 AND "did_root" = "did") OR ("active" = 0 AND "did_root" IS NULL)), + CONSTRAINT "arrival_cancel" CHECK (("cancelled_at" IS NULL) OR ("cancelled_at" IS NOT NULL AND "active" = 0)), + CONSTRAINT "arrival_bound" CHECK (("bound_at" IS NULL) OR ("bound_at" IS NOT NULL AND "deactivated_at" IS NOT NULL)), + CONSTRAINT "arrival_complete" CHECK (("completed_at" IS NULL) OR ("completed_at" IS NOT NULL AND "bound_at" IS NOT NULL AND "activation_method" IS NOT NULL)) +); +--> statement-breakpoint CREATE TABLE "authority_operations" ( "id" text PRIMARY KEY, "kind" text NOT NULL, @@ -221,6 +321,16 @@ CREATE INDEX "account_bindings_user_id" ON "account_bindings" ("user_id");--> st CREATE INDEX "accounts_email_ci" ON "accounts" (lower("email"));--> statement-breakpoint CREATE UNIQUE INDEX "accounts_handle_ci" ON "accounts" (lower("handle"));--> statement-breakpoint CREATE INDEX "accounts_pds_status" ON "accounts" ("pds_id","status");--> statement-breakpoint +CREATE INDEX "arrival_attempt_operation" ON "arrival_attempts" ("operation_id");--> statement-breakpoint +CREATE INDEX "arrival_family_operation" ON "arrival_families" ("operation_id","revoked_at");--> statement-breakpoint +CREATE UNIQUE INDEX "arrival_replay_credential" ON "arrival_replay" ("credential_issuer","credential_jti");--> statement-breakpoint +CREATE UNIQUE INDEX "arrival_signed_kind_cid" ON "arrival_signed_operations" ("operation_id","kind_operation_cid");--> statement-breakpoint +CREATE UNIQUE INDEX "arrivals_did_active" ON "arrivals" ("did_root");--> statement-breakpoint +CREATE INDEX "arrivals_did" ON "arrivals" ("did","created_at");--> statement-breakpoint +CREATE INDEX "arrivals_user" ON "arrivals" ("user_id","created_at");--> statement-breakpoint +CREATE INDEX "arrivals_email" ON "arrivals" (lower("email"));--> statement-breakpoint +CREATE UNIQUE INDEX "arrivals_handle_active" ON "arrivals" (lower("handle")) WHERE "did_root" IS NOT NULL AND "cancelled_at" IS NULL AND "provisioned_at" IS NULL;--> statement-breakpoint +CREATE INDEX "arrivals_handle" ON "arrivals" (lower("handle"),"created_at");--> statement-breakpoint CREATE INDEX "authority_operation_lease" ON "authority_operations" ("state","lease_expires_at");--> statement-breakpoint CREATE UNIQUE INDEX "backup_emails_ci" ON "backup_emails" (lower("email"));--> statement-breakpoint CREATE INDEX "custody_history_did" ON "custody_history" ("did");--> statement-breakpoint @@ -243,6 +353,11 @@ CREATE INDEX "verification_identifier" ON "verification" ("identifier");--> stat ALTER TABLE "account" ADD CONSTRAINT "account_userId_user_id_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint ALTER TABLE "account_bindings" ADD CONSTRAINT "account_bindings_did_accounts_did_fkey" FOREIGN KEY ("did") REFERENCES "accounts"("did");--> statement-breakpoint ALTER TABLE "account_bindings" ADD CONSTRAINT "account_bindings_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id");--> statement-breakpoint +ALTER TABLE "arrival_attempts" ADD CONSTRAINT "arrival_attempts_operation_id_arrivals_operation_id_fkey" FOREIGN KEY ("operation_id") REFERENCES "arrivals"("operation_id");--> statement-breakpoint +ALTER TABLE "arrival_code" ADD CONSTRAINT "arrival_code_operation_id_arrivals_operation_id_fkey" FOREIGN KEY ("operation_id") REFERENCES "arrivals"("operation_id");--> statement-breakpoint +ALTER TABLE "arrival_families" ADD CONSTRAINT "arrival_families_operation_id_arrivals_operation_id_fkey" FOREIGN KEY ("operation_id") REFERENCES "arrivals"("operation_id");--> statement-breakpoint +ALTER TABLE "arrival_reservations" ADD CONSTRAINT "arrival_reservations_operation_id_arrivals_operation_id_fkey" FOREIGN KEY ("operation_id") REFERENCES "arrivals"("operation_id");--> statement-breakpoint +ALTER TABLE "arrival_signed_operations" ADD CONSTRAINT "arrival_signed_operations_lgIMaTRt2yjc_fkey" FOREIGN KEY ("operation_id") REFERENCES "arrivals"("operation_id");--> statement-breakpoint ALTER TABLE "backup_emails" ADD CONSTRAINT "backup_emails_did_accounts_did_fkey" FOREIGN KEY ("did") REFERENCES "accounts"("did");--> statement-breakpoint ALTER TABLE "custody_history" ADD CONSTRAINT "custody_history_Hb73d4yN25nV_fkey" FOREIGN KEY ("supporting_observation_id") REFERENCES "custody_observations"("id");--> statement-breakpoint ALTER TABLE "email_claims" ADD CONSTRAINT "email_claims_did_accounts_did_fkey" FOREIGN KEY ("did") REFERENCES "accounts"("did");--> statement-breakpoint diff --git a/src/database/schema/postgresql.ts b/src/database/schema/postgresql.ts index 13866124..111def55 100644 --- a/src/database/schema/postgresql.ts +++ b/src/database/schema/postgresql.ts @@ -174,6 +174,189 @@ export const migration_reservations = table( ), ], ); +// Immutable arrival tuple and secret-safe lifecycle; only its hash reaches +// arrival_code. did_root retains one active arrival per DID while completed +// rows become history. active is 1 for a live, admitted arrival. +export const arrivals = table( + "arrivals", + { + operation_id: text("operation_id").primaryKey(), + did: text("did").notNull(), + did_root: text("did_root"), + active: integer("active").notNull(), + user_id: text("user_id").notNull(), + email: text("email").notNull(), + handle: text("handle").notNull(), + pds_id: text("pds_id").notNull(), + endpoint: text("endpoint").notNull(), + source_plc_head: text("source_plc_head").notNull(), + source_endpoint: text("source_endpoint"), + canonical_handoff_cid: text("canonical_handoff_cid"), + source_predecessor: text("source_predecessor").notNull(), + source_facts: text("source_facts").notNull(), + approved_rotation_keys: text("approved_rotation_keys").notNull(), + version: count("version").notNull(), + generation: count("generation").notNull(), + created_at: count("created_at").notNull(), + updated_at: count("updated_at").notNull(), + cancelled_at: count("cancelled_at"), + provisioned_at: count("provisioned_at"), + deactivated_at: count("deactivated_at"), + bound_at: count("bound_at"), + activation_method: text("activation_method"), + activation_at: count("activation_at"), + completed_at: count("completed_at"), + }, + (t) => [ + uniqueIndex("arrivals_did_active").on(t.did_root), + index("arrivals_did").on(t.did, t.created_at), + index("arrivals_user").on(t.user_id, t.created_at), + index("arrivals_email").on(sql`lower(${t.email})`), + uniqueIndex("arrivals_handle_active") + .on(sql`lower(${t.handle})`) + .where( + sql`${t.did_root} IS NOT NULL AND ${t.cancelled_at} IS NULL AND ${t.provisioned_at} IS NULL`, + ), + index("arrivals_handle").on(sql`lower(${t.handle})`, t.created_at), + check("arrival_active", sql`${t.active} IN (0, 1)`), + check( + "arrival_tuple", + sql`(${t.active} = 1 AND ${t.did_root} = ${t.did}) OR (${t.active} = 0 AND ${t.did_root} IS NULL)`, + ), + check( + "arrival_cancel", + sql`(${t.cancelled_at} IS NULL) OR (${t.cancelled_at} IS NOT NULL AND ${t.active} = 0)`, + ), + check( + "arrival_bound", + sql`(${t.bound_at} IS NULL) OR (${t.bound_at} IS NOT NULL AND ${t.deactivated_at} IS NOT NULL)`, + ), + check( + "arrival_complete", + sql`(${t.completed_at} IS NULL) OR (${t.completed_at} IS NOT NULL AND ${t.bound_at} IS NOT NULL AND ${t.activation_method} IS NOT NULL)`, + ), + ], +); +export const arrival_code = table( + "arrival_code", + { + operation_id: text("operation_id") + .primaryKey() + .references(() => arrivals.operation_id), + code_hash: text("code_hash").notNull(), + generation: count("generation").notNull(), + issued_at: count("issued_at").notNull(), + expires_at: count("expires_at").notNull(), + }, + (t) => [ + check("arrival_code_lifetime", sql`${t.expires_at} > ${t.issued_at}`), + check( + "arrival_code_ceiling", + sql`${t.expires_at} <= ${t.issued_at} + 86400000`, + ), + ], +); +export const arrival_reservations = table( + "arrival_reservations", + { + operation_id: text("operation_id") + .primaryKey() + .references(() => arrivals.operation_id), + signing_key: text("signing_key"), + uncertain_reason: text("uncertain_reason"), + uncertain_at: count("uncertain_at"), + recorded_at: count("recorded_at"), + }, + (t) => [ + check( + "arrival_reservation_evidence", + sql`(${t.uncertain_reason} IS NULL AND ${t.uncertain_at} IS NULL) OR (${t.uncertain_reason} IS NOT NULL AND ${t.uncertain_at} IS NOT NULL)`, + ), + check( + "arrival_reservation_key", + sql`(${t.signing_key} IS NULL) OR ${t.signing_key} LIKE 'did:key:z%'`, + ), + ], +); +// Signed public PLC bytes for one arrival and signature kind. Private keys never +// reach this table; an operation or CID is immutable once recorded. +export const arrival_signed_operations = table( + "arrival_signed_operations", + { + operation_id: text("operation_id") + .notNull() + .references(() => arrivals.operation_id), + kind: text("kind").notNull(), + did: text("did").notNull(), + cid: text("cid").notNull(), + operation: text("operation").notNull(), + kind_operation_cid: text("kind_operation_cid").notNull(), + recorded_at: count("recorded_at").notNull(), + }, + (t) => [ + primaryKey({ columns: [t.operation_id, t.kind] }), + uniqueIndex("arrival_signed_kind_cid").on( + t.operation_id, + t.kind_operation_cid, + ), + check( + "arrival_signed_kind", + sql`${t.kind} IN ('handoff','destination-move')`, + ), + check("arrival_signed_did", sql`${t.did} LIKE 'did:%'`), + check("arrival_signed_cid", sql`${t.cid} LIKE 'baf%'`), + ], +); +export const arrival_replay = table( + "arrival_replay", + { + operation_id: text("operation_id").notNull(), + method: text("method").notNull(), + did: text("did").notNull(), + user_id: text("user_id").notNull(), + credential_issuer: text("credential_issuer").notNull(), + credential_jti: text("credential_jti").notNull(), + request_digest: text("request_digest").notNull(), + generation: count("generation").notNull(), + accepted_at: count("accepted_at").notNull(), + }, + (t) => [ + primaryKey({ columns: [t.operation_id, t.method] }), + uniqueIndex("arrival_replay_credential").on( + t.credential_issuer, + t.credential_jti, + ), + check("arrival_replay_digest", sql`length(${t.request_digest}) = 64`), + ], +); +export const arrival_attempts = table( + "arrival_attempts", + { + attempt_binding: text("attempt_binding").primaryKey(), + ownership_operation_id: text("ownership_operation_id").notNull(), + attempt_id: text("attempt_id").notNull(), + operation_id: text("operation_id") + .notNull() + .references(() => arrivals.operation_id), + reason: text("reason").notNull(), + recorded_at: count("recorded_at").notNull(), + fence: count("fence").notNull(), + }, + (t) => [index("arrival_attempt_operation").on(t.operation_id)], +); +export const arrival_families = table( + "arrival_families", + { + family_id: text("family_id").primaryKey(), + operation_id: text("operation_id") + .notNull() + .references(() => arrivals.operation_id), + pds_id: text("pds_id").notNull(), + created_at: count("created_at").notNull(), + revoked_at: count("revoked_at"), + }, + (t) => [index("arrival_family_operation").on(t.operation_id, t.revoked_at)], +); export const key_value_state = table( "key_value_state", { diff --git a/src/database/schema/sqlite.sql b/src/database/schema/sqlite.sql index b2ce96ae..9f78bd18 100644 --- a/src/database/schema/sqlite.sql +++ b/src/database/schema/sqlite.sql @@ -32,6 +32,111 @@ CREATE TABLE `accounts` ( `sequence` integer NOT NULL UNIQUE ); --> statement-breakpoint +CREATE TABLE `arrival_attempts` ( + `attempt_binding` text PRIMARY KEY, + `ownership_operation_id` text NOT NULL, + `attempt_id` text NOT NULL, + `operation_id` text NOT NULL, + `reason` text NOT NULL, + `recorded_at` integer NOT NULL, + `fence` integer NOT NULL, + CONSTRAINT `fk_arrival_attempts_operation_id_arrivals_operation_id_fk` FOREIGN KEY (`operation_id`) REFERENCES `arrivals`(`operation_id`) +); +--> statement-breakpoint +CREATE TABLE `arrival_code` ( + `operation_id` text PRIMARY KEY, + `code_hash` text NOT NULL, + `generation` integer NOT NULL, + `issued_at` integer NOT NULL, + `expires_at` integer NOT NULL, + CONSTRAINT `fk_arrival_code_operation_id_arrivals_operation_id_fk` FOREIGN KEY (`operation_id`) REFERENCES `arrivals`(`operation_id`), + CONSTRAINT "arrival_code_lifetime" CHECK("expires_at" > "issued_at"), + CONSTRAINT "arrival_code_ceiling" CHECK("expires_at" <= "issued_at" + 86400000) +); +--> statement-breakpoint +CREATE TABLE `arrival_families` ( + `family_id` text PRIMARY KEY, + `operation_id` text NOT NULL, + `pds_id` text NOT NULL, + `created_at` integer NOT NULL, + `revoked_at` integer, + CONSTRAINT `fk_arrival_families_operation_id_arrivals_operation_id_fk` FOREIGN KEY (`operation_id`) REFERENCES `arrivals`(`operation_id`) +); +--> statement-breakpoint +CREATE TABLE `arrival_replay` ( + `operation_id` text NOT NULL, + `method` text NOT NULL, + `did` text NOT NULL, + `user_id` text NOT NULL, + `credential_issuer` text NOT NULL, + `credential_jti` text NOT NULL, + `request_digest` text NOT NULL, + `generation` integer NOT NULL, + `accepted_at` integer NOT NULL, + CONSTRAINT `arrival_replay_pk` PRIMARY KEY(`operation_id`, `method`), + CONSTRAINT "arrival_replay_digest" CHECK(length("request_digest") = 64) +); +--> statement-breakpoint +CREATE TABLE `arrival_reservations` ( + `operation_id` text PRIMARY KEY, + `signing_key` text, + `uncertain_reason` text, + `uncertain_at` integer, + `recorded_at` integer, + CONSTRAINT `fk_arrival_reservations_operation_id_arrivals_operation_id_fk` FOREIGN KEY (`operation_id`) REFERENCES `arrivals`(`operation_id`), + CONSTRAINT "arrival_reservation_evidence" CHECK(("uncertain_reason" IS NULL AND "uncertain_at" IS NULL) OR ("uncertain_reason" IS NOT NULL AND "uncertain_at" IS NOT NULL)), + CONSTRAINT "arrival_reservation_key" CHECK(("signing_key" IS NULL) OR "signing_key" LIKE 'did:key:z%') +); +--> statement-breakpoint +CREATE TABLE `arrival_signed_operations` ( + `operation_id` text NOT NULL, + `kind` text NOT NULL, + `did` text NOT NULL, + `cid` text NOT NULL, + `operation` text NOT NULL, + `kind_operation_cid` text NOT NULL, + `recorded_at` integer NOT NULL, + CONSTRAINT `arrival_signed_operations_pk` PRIMARY KEY(`operation_id`, `kind`), + CONSTRAINT `fk_arrival_signed_operations_operation_id_arrivals_operation_id_fk` FOREIGN KEY (`operation_id`) REFERENCES `arrivals`(`operation_id`), + CONSTRAINT "arrival_signed_kind" CHECK("kind" IN ('handoff','destination-move')), + CONSTRAINT "arrival_signed_did" CHECK("did" LIKE 'did:%'), + CONSTRAINT "arrival_signed_cid" CHECK("cid" LIKE 'baf%') +); +--> statement-breakpoint +CREATE TABLE `arrivals` ( + `operation_id` text PRIMARY KEY, + `did` text NOT NULL, + `did_root` text, + `active` integer NOT NULL, + `user_id` text NOT NULL, + `email` text NOT NULL, + `handle` text NOT NULL, + `pds_id` text NOT NULL, + `endpoint` text NOT NULL, + `source_plc_head` text NOT NULL, + `source_endpoint` text, + `canonical_handoff_cid` text, + `source_predecessor` text NOT NULL, + `source_facts` text NOT NULL, + `approved_rotation_keys` text NOT NULL, + `version` integer NOT NULL, + `generation` integer NOT NULL, + `created_at` integer NOT NULL, + `updated_at` integer NOT NULL, + `cancelled_at` integer, + `provisioned_at` integer, + `deactivated_at` integer, + `bound_at` integer, + `activation_method` text, + `activation_at` integer, + `completed_at` integer, + CONSTRAINT "arrival_active" CHECK("active" IN (0, 1)), + CONSTRAINT "arrival_tuple" CHECK(("active" = 1 AND "did_root" = "did") OR ("active" = 0 AND "did_root" IS NULL)), + CONSTRAINT "arrival_cancel" CHECK(("cancelled_at" IS NULL) OR ("cancelled_at" IS NOT NULL AND "active" = 0)), + CONSTRAINT "arrival_bound" CHECK(("bound_at" IS NULL) OR ("bound_at" IS NOT NULL AND "deactivated_at" IS NOT NULL)), + CONSTRAINT "arrival_complete" CHECK(("completed_at" IS NULL) OR ("completed_at" IS NOT NULL AND "bound_at" IS NOT NULL AND "activation_method" IS NOT NULL)) +); +--> statement-breakpoint CREATE TABLE `authority_operations` ( `id` text PRIMARY KEY, `kind` text NOT NULL, @@ -233,6 +338,16 @@ CREATE INDEX `account_bindings_user_id` ON `account_bindings` (`user_id`);--> st CREATE INDEX `accounts_email_ci` ON `accounts` (lower("email"));--> statement-breakpoint CREATE UNIQUE INDEX `accounts_handle_ci` ON `accounts` (lower("handle"));--> statement-breakpoint CREATE INDEX `accounts_pds_status` ON `accounts` (`pds_id`,`status`);--> statement-breakpoint +CREATE INDEX `arrival_attempt_operation` ON `arrival_attempts` (`operation_id`);--> statement-breakpoint +CREATE INDEX `arrival_family_operation` ON `arrival_families` (`operation_id`,`revoked_at`);--> statement-breakpoint +CREATE UNIQUE INDEX `arrival_replay_credential` ON `arrival_replay` (`credential_issuer`,`credential_jti`);--> statement-breakpoint +CREATE UNIQUE INDEX `arrival_signed_kind_cid` ON `arrival_signed_operations` (`operation_id`,`kind_operation_cid`);--> statement-breakpoint +CREATE UNIQUE INDEX `arrivals_did_active` ON `arrivals` (`did_root`);--> statement-breakpoint +CREATE INDEX `arrivals_did` ON `arrivals` (`did`,`created_at`);--> statement-breakpoint +CREATE INDEX `arrivals_user` ON `arrivals` (`user_id`,`created_at`);--> statement-breakpoint +CREATE INDEX `arrivals_email` ON `arrivals` (lower("email"));--> statement-breakpoint +CREATE UNIQUE INDEX `arrivals_handle_active` ON `arrivals` (lower("handle")) WHERE "arrivals"."did_root" IS NOT NULL AND "arrivals"."cancelled_at" IS NULL AND "arrivals"."provisioned_at" IS NULL;--> statement-breakpoint +CREATE INDEX `arrivals_handle` ON `arrivals` (lower("handle"),`created_at`);--> statement-breakpoint CREATE INDEX `authority_operation_lease` ON `authority_operations` (`state`,`lease_expires_at`);--> statement-breakpoint CREATE UNIQUE INDEX `backup_emails_ci` ON `backup_emails` (lower("email"));--> statement-breakpoint CREATE INDEX `custody_history_did` ON `custody_history` (`did`);--> statement-breakpoint diff --git a/src/database/schema/sqlite.ts b/src/database/schema/sqlite.ts index 907d80a0..5b2d61ee 100644 --- a/src/database/schema/sqlite.ts +++ b/src/database/schema/sqlite.ts @@ -168,6 +168,189 @@ export const migration_reservations = table( ), ], ); +// Immutable arrival tuple and secret-safe lifecycle; only its hash reaches +// arrival_code. did_root retains one active arrival per DID while completed +// rows become history. active is 1 for a live, admitted arrival. +export const arrivals = table( + "arrivals", + { + operation_id: text("operation_id").primaryKey(), + did: text("did").notNull(), + did_root: text("did_root"), + active: integer("active").notNull(), + user_id: text("user_id").notNull(), + email: text("email").notNull(), + handle: text("handle").notNull(), + pds_id: text("pds_id").notNull(), + endpoint: text("endpoint").notNull(), + source_plc_head: text("source_plc_head").notNull(), + source_endpoint: text("source_endpoint"), + canonical_handoff_cid: text("canonical_handoff_cid"), + source_predecessor: text("source_predecessor").notNull(), + source_facts: text("source_facts").notNull(), + approved_rotation_keys: text("approved_rotation_keys").notNull(), + version: count("version").notNull(), + generation: count("generation").notNull(), + created_at: count("created_at").notNull(), + updated_at: count("updated_at").notNull(), + cancelled_at: count("cancelled_at"), + provisioned_at: count("provisioned_at"), + deactivated_at: count("deactivated_at"), + bound_at: count("bound_at"), + activation_method: text("activation_method"), + activation_at: count("activation_at"), + completed_at: count("completed_at"), + }, + (t) => [ + uniqueIndex("arrivals_did_active").on(t.did_root), + index("arrivals_did").on(t.did, t.created_at), + index("arrivals_user").on(t.user_id, t.created_at), + index("arrivals_email").on(sql`lower(${t.email})`), + uniqueIndex("arrivals_handle_active") + .on(sql`lower(${t.handle})`) + .where( + sql`${t.did_root} IS NOT NULL AND ${t.cancelled_at} IS NULL AND ${t.provisioned_at} IS NULL`, + ), + index("arrivals_handle").on(sql`lower(${t.handle})`, t.created_at), + check("arrival_active", sql`${t.active} IN (0, 1)`), + check( + "arrival_tuple", + sql`(${t.active} = 1 AND ${t.did_root} = ${t.did}) OR (${t.active} = 0 AND ${t.did_root} IS NULL)`, + ), + check( + "arrival_cancel", + sql`(${t.cancelled_at} IS NULL) OR (${t.cancelled_at} IS NOT NULL AND ${t.active} = 0)`, + ), + check( + "arrival_bound", + sql`(${t.bound_at} IS NULL) OR (${t.bound_at} IS NOT NULL AND ${t.deactivated_at} IS NOT NULL)`, + ), + check( + "arrival_complete", + sql`(${t.completed_at} IS NULL) OR (${t.completed_at} IS NOT NULL AND ${t.bound_at} IS NOT NULL AND ${t.activation_method} IS NOT NULL)`, + ), + ], +); +export const arrival_code = table( + "arrival_code", + { + operation_id: text("operation_id") + .primaryKey() + .references(() => arrivals.operation_id), + code_hash: text("code_hash").notNull(), + generation: count("generation").notNull(), + issued_at: count("issued_at").notNull(), + expires_at: count("expires_at").notNull(), + }, + (t) => [ + check("arrival_code_lifetime", sql`${t.expires_at} > ${t.issued_at}`), + check( + "arrival_code_ceiling", + sql`${t.expires_at} <= ${t.issued_at} + 86400000`, + ), + ], +); +export const arrival_reservations = table( + "arrival_reservations", + { + operation_id: text("operation_id") + .primaryKey() + .references(() => arrivals.operation_id), + signing_key: text("signing_key"), + uncertain_reason: text("uncertain_reason"), + uncertain_at: count("uncertain_at"), + recorded_at: count("recorded_at"), + }, + (t) => [ + check( + "arrival_reservation_evidence", + sql`(${t.uncertain_reason} IS NULL AND ${t.uncertain_at} IS NULL) OR (${t.uncertain_reason} IS NOT NULL AND ${t.uncertain_at} IS NOT NULL)`, + ), + check( + "arrival_reservation_key", + sql`(${t.signing_key} IS NULL) OR ${t.signing_key} LIKE 'did:key:z%'`, + ), + ], +); +// Signed public PLC bytes for one arrival and signature kind. Private keys never +// reach this table; an operation or CID is immutable once recorded. +export const arrival_signed_operations = table( + "arrival_signed_operations", + { + operation_id: text("operation_id") + .notNull() + .references(() => arrivals.operation_id), + kind: text("kind").notNull(), + did: text("did").notNull(), + cid: text("cid").notNull(), + operation: text("operation").notNull(), + kind_operation_cid: text("kind_operation_cid").notNull(), + recorded_at: count("recorded_at").notNull(), + }, + (t) => [ + primaryKey({ columns: [t.operation_id, t.kind] }), + uniqueIndex("arrival_signed_kind_cid").on( + t.operation_id, + t.kind_operation_cid, + ), + check( + "arrival_signed_kind", + sql`${t.kind} IN ('handoff','destination-move')`, + ), + check("arrival_signed_did", sql`${t.did} LIKE 'did:%'`), + check("arrival_signed_cid", sql`${t.cid} LIKE 'baf%'`), + ], +); +export const arrival_replay = table( + "arrival_replay", + { + operation_id: text("operation_id").notNull(), + method: text("method").notNull(), + did: text("did").notNull(), + user_id: text("user_id").notNull(), + credential_issuer: text("credential_issuer").notNull(), + credential_jti: text("credential_jti").notNull(), + request_digest: text("request_digest").notNull(), + generation: count("generation").notNull(), + accepted_at: count("accepted_at").notNull(), + }, + (t) => [ + primaryKey({ columns: [t.operation_id, t.method] }), + uniqueIndex("arrival_replay_credential").on( + t.credential_issuer, + t.credential_jti, + ), + check("arrival_replay_digest", sql`length(${t.request_digest}) = 64`), + ], +); +export const arrival_attempts = table( + "arrival_attempts", + { + attempt_binding: text("attempt_binding").primaryKey(), + ownership_operation_id: text("ownership_operation_id").notNull(), + attempt_id: text("attempt_id").notNull(), + operation_id: text("operation_id") + .notNull() + .references(() => arrivals.operation_id), + reason: text("reason").notNull(), + recorded_at: count("recorded_at").notNull(), + fence: count("fence").notNull(), + }, + (t) => [index("arrival_attempt_operation").on(t.operation_id)], +); +export const arrival_families = table( + "arrival_families", + { + family_id: text("family_id").primaryKey(), + operation_id: text("operation_id") + .notNull() + .references(() => arrivals.operation_id), + pds_id: text("pds_id").notNull(), + created_at: count("created_at").notNull(), + revoked_at: count("revoked_at"), + }, + (t) => [index("arrival_family_operation").on(t.operation_id, t.revoked_at)], +); export const key_value_state = table( "key_value_state", { diff --git a/src/features/external-migration/arrival-types.ts b/src/features/external-migration/arrival-types.ts new file mode 100644 index 00000000..dbd1b196 --- /dev/null +++ b/src/features/external-migration/arrival-types.ts @@ -0,0 +1,176 @@ +import type { IncomingSourceFacts } from "../../plc/policy.js"; + +export type ArrivalApplied = { + readonly kind: "applied"; + readonly version: number; +}; + +/** No arrival mutation happened and the saved version did not advance. */ +export type ArrivalAlreadySettled = { + readonly kind: "already-settled"; + readonly version: number; +}; + +export type ArrivalOutcome = + | ArrivalApplied + | ArrivalAlreadySettled + | { + readonly kind: "reconciliation-required"; + readonly reason: "saved-key-differs" | "uncertain-attempt"; + }; + +export interface ArrivalPlacementEvidence { + readonly provisioned: boolean; + readonly deactivationObserved: boolean; +} + +export interface ArrivalActivationEvidence { + readonly backendActiveObserved: boolean; + readonly method: string; + readonly observedAt: number; +} + +/** Completion never infers or manufactures activation evidence. */ +export function isObservedArrivalActivation( + value: ArrivalActivationEvidence | null, +): value is ArrivalActivationEvidence { + return Boolean( + value && + value.backendActiveObserved === true && + typeof value.method === "string" && + value.method.startsWith("com.atproto.") && + Number.isSafeInteger(value.observedAt) && + value.observedAt > 0, + ); +} + +export interface ArrivalPreparationAuthority { + readonly sourcePredecessor: Record; + readonly source: IncomingSourceFacts; + readonly approvedRotationKeys: readonly string[]; +} + +export interface ArrivalRecord extends ArrivalPreparationAuthority { + readonly operationId: string; + readonly did: string; + readonly userId: string; + readonly email: string; + readonly handle: string; + readonly pdsId: string; + readonly endpoint: string; + readonly sourcePlcHead: string; + readonly version: number; + readonly codeHash: string; + readonly codeGeneration: number; + readonly codeExpiresAt: number; + readonly generation: number; + readonly signingKey: string | null; + readonly codeDelivered: boolean; + readonly cancelledAt: number | null; +} + +export interface ArrivalAccess { + readonly operationId: string; + readonly version: number; + readonly did: string; + readonly userId: string; + readonly pdsId: string; + readonly provisioned: boolean; + readonly deactivationObserved: boolean; + readonly bound: boolean; + readonly complete: boolean; + readonly unresolvedAttempt: boolean; +} + +export interface ArrivalAllocationIntent { + readonly operationId: string; + readonly did: string; + readonly pdsId: string; + readonly endpoint: string; +} + +export interface ArrivalReservationResult extends ArrivalAllocationIntent { + readonly signingKey: string; +} + +export interface ArrivalUncertainAttempt extends ArrivalAllocationIntent { + readonly reason: string; +} + +/** Links one generic dispatch receipt without changing repository allocation state. */ +export interface ArrivalExternalAttempt { + readonly operationId: string; + readonly did: string; + readonly externalAttemptId: string; + readonly step: "incoming-creation" | "incoming-pause"; +} + +export interface ArrivalReplayFacts { + readonly operationId: string; + readonly did: string; + readonly method: string; + readonly requestDigest: string; + readonly credentialIssuer: string; + readonly credentialJti: string; +} + +export interface ArrivalAdmissionProof { + readonly codeHash: string; + readonly codeGeneration: number; +} + +export interface ArrivalReplayReuse { + readonly operationId: string; + readonly generation: number; +} + +/** Signed public bytes and their CID stay together; private keys never enter here. */ +export interface ArrivalSignedOperation { + readonly operation: Record; + readonly cid: string; +} + +/** Source-authorized authority-only handoff, recorded before directory submission. */ +export interface ArrivalHandoffRecord extends ArrivalSignedOperation { + readonly kind: "handoff"; + readonly operationId: string; + readonly did: string; +} + +/** Destination move signed for the reserved public repository key. */ +export interface ArrivalDestinationMoveRecord extends ArrivalSignedOperation { + readonly kind: "destination-move"; + readonly operationId: string; + readonly did: string; + readonly repositoryKey: string; +} + +export type ArrivalSignedOperationRecord = + | ArrivalHandoffRecord + | ArrivalDestinationMoveRecord; + +export interface ArrivalAggregate { + readonly arrival: ArrivalRecord; + readonly signedOperations: readonly ArrivalSignedOperationRecord[]; + readonly admissions: readonly (ArrivalReplayFacts & { + readonly userId: string; + readonly generation: number; + })[]; + readonly reservation: { + readonly signingKey: string | null; + readonly uncertainReason: string | null; + } | null; + readonly progress: { + readonly provisionedAt: number | null; + readonly deactivatedAt: number | null; + readonly boundAt: number | null; + readonly completedAt: number | null; + readonly canonicalHandoffCid: string | null; + }; + readonly attempts: readonly { + readonly ownershipOperationId: string; + readonly attemptId: string; + readonly fence: number; + readonly reason: string; + }[]; +} diff --git a/src/features/external-migration/import-account.ts b/src/features/external-migration/import-account.ts index d11b6acc..82a1dc81 100644 --- a/src/features/external-migration/import-account.ts +++ b/src/features/external-migration/import-account.ts @@ -462,7 +462,7 @@ export class ExternalMigrationService { { const n = advance(w, "account-bound"); await this.d.transact(async () => { - await this.d.accounts.finalizeImportedAccount({ + await this.d.accounts.bindProvisionedArrival({ workflowId: w.id, did: w.did, userId: w.ownerUserId, @@ -492,7 +492,7 @@ export class ExternalMigrationService { { const n = advance(w, "complete"); await this.d.transact(async () => { - await this.d.accounts.activateImportedAccount({ + await this.d.accounts.activateBoundArrival({ workflowId: w.id, did: w.did, userId: w.ownerUserId, diff --git a/src/plc/policy.ts b/src/plc/policy.ts index 42d52b1c..ece3fe78 100644 --- a/src/plc/policy.ts +++ b/src/plc/policy.ts @@ -111,6 +111,97 @@ export function validateUnsignedOperation( return op; } +/** Incoming handoff preserves existing priority and adds only Entryway's hot + * authority last. Genesis ordering must never rewrite an existing identity. */ +export function incomingRotationKeys( + current: readonly string[], + entrywayKey: string, +): string[] { + const keys = [...current]; + keys.forEach(publicRotationKey); + publicRotationKey(entrywayKey); + if (!keys.includes(entrywayKey)) keys.push(entrywayKey); + if (keys.length < 2 || keys.length > 5 || new Set(keys).size !== keys.length) + return invalid(); + return keys; +} + +/** Source facts an authority-only handoff must not alter. Comparison is exact + * and order-sensitive: a reordered rotation list is a different approved list. */ +export interface IncomingSourceFacts { + readonly services: plc.UnsignedOperation["services"]; + readonly verificationMethods: plc.UnsignedOperation["verificationMethods"]; + readonly alsoKnownAs: plc.UnsignedOperation["alsoKnownAs"]; +} + +/** Validate a source-signed authority-only handoff in its original encoding. + * The signature must prove the expected source predecessor, and the only change + * to the approved ordered rotation list may be adding the Entryway rotation key, + * within the protocol limit. Overfull lists, removals, reordering, unexpected + * keys, changed source facts and tombstones are rejected rather than truncated. */ +export async function validateIncomingHandoff(input: { + readonly operation: unknown; + readonly expectedPredecessor: unknown; + readonly approvedRotationKeys: readonly string[]; + readonly source: IncomingSourceFacts; +}): Promise { + const approved = [...input.approvedRotationKeys]; + if ( + approved.length < 2 || + approved.length > 5 || + new Set(approved).size !== approved.length + ) + return invalid(); + let candidate: plc.CompatibleOp; + let predecessor: plc.Operation; + let predecessorCid: string; + try { + approved.forEach(publicRotationKey); + const original = plc.def.compatibleOp.parse( + structuredClone(input.expectedPredecessor), + ); + predecessorCid = String(await cidForCbor(original)); + predecessor = plc.normalizeOp(original); + // The handoff is always the current signed operation form, never legacy v1. + candidate = plc.def.operation.parse(structuredClone(input.operation)); + if (candidate.prev !== predecessorCid) return invalid(); + await plc.assureValidSig([...predecessor.rotationKeys], candidate); + } catch (error) { + if (error instanceof PlcError) throw error; + return invalid(); + } + const facts = plc.normalizeOp(candidate); + if (facts.rotationKeys.length !== approved.length) return invalid(); + for (let index = 0; index < approved.length; index += 1) + if (facts.rotationKeys[index] !== approved[index]) return invalid(); + if ( + !sameSignedOperation(facts.alsoKnownAs, input.source.alsoKnownAs) || + !sameSignedOperation( + facts.verificationMethods, + input.source.verificationMethods, + ) || + !sameSignedOperation(facts.services, input.source.services) || + !sameSignedOperation(candidate, input.operation) + ) + return invalid(); + return candidate; +} + +/** A retried handoff resumes the saved bytes or conflicts; it never re-signs. */ +export function sameSignedOperation(left: unknown, right: unknown): boolean { + const canonical = (value: unknown): unknown => { + if (Array.isArray(value)) return value.map(canonical); + if (record(value)) + return Object.fromEntries( + Object.entries(value) + .sort(([first], [second]) => (first < second ? -1 : 1)) + .map(([key, item]) => [key, canonical(item)]), + ); + return value; + }; + return JSON.stringify(canonical(left)) === JSON.stringify(canonical(right)); +} + export async function publicUpdateCandidate( current: unknown, replacement: unknown, diff --git a/tests/contracts/account-schema.test.mjs b/tests/contracts/account-schema.test.mjs index 3eb68760..0d899a9b 100644 --- a/tests/contracts/account-schema.test.mjs +++ b/tests/contracts/account-schema.test.mjs @@ -406,7 +406,7 @@ test("authorized migration can share an email with an unbound DID and roll back "synthetic binding failure", ); await assert.rejects( - storage.finalizeImportedAccount({ + storage.bindProvisionedArrival({ workflowId: incoming.workflowId, did: incoming.did, userId: ownerId, @@ -425,7 +425,7 @@ test("authorized migration can share an email with an unbound DID and roll back }); await removeFailureTrigger(db, "reject_import_binding", "account_bindings"); - const imported = await storage.finalizeImportedAccount({ + const imported = await storage.bindProvisionedArrival({ workflowId: incoming.workflowId, did: incoming.did, userId: ownerId, @@ -693,7 +693,7 @@ test("synthetic imported DID binds only a recent verified owner then activates a ); await assert.rejects( async () => - await storage.finalizeImportedAccount({ + await storage.bindProvisionedArrival({ workflowId: reservation.workflowId, did: alice.did, userId: "wrong", @@ -706,7 +706,7 @@ test("synthetic imported DID binds only a recent verified owner then activates a ); await assert.rejects( async () => - await storage.finalizeImportedAccount({ + await storage.bindProvisionedArrival({ workflowId: reservation.workflowId, did: alice.did, userId: "owner", @@ -717,7 +717,7 @@ test("synthetic imported DID binds only a recent verified owner then activates a }), (error) => error.code === "IdentityConflict", ); - const placed = await storage.finalizeImportedAccount({ + const placed = await storage.bindProvisionedArrival({ workflowId: reservation.workflowId, did: alice.did, userId: "owner", @@ -741,7 +741,7 @@ test("synthetic imported DID binds only a recent verified owner then activates a [hosted.did, alice.did], ); assert.equal(await storage.hasPendingExternalMigration(alice.did), true); - const active = await storage.activateImportedAccount({ + const active = await storage.activateBoundArrival({ workflowId: reservation.workflowId, did: alice.did, userId: "owner", @@ -750,7 +750,7 @@ test("synthetic imported DID binds only a recent verified owner then activates a assert.equal(await storage.hasPendingExternalMigration(alice.did), false); assert.equal( ( - await storage.activateImportedAccount({ + await storage.activateBoundArrival({ workflowId: reservation.workflowId, did: alice.did, userId: "owner", diff --git a/tests/contracts/account-security.test.mjs b/tests/contracts/account-security.test.mjs index d8b7554f..e48f3177 100644 --- a/tests/contracts/account-security.test.mjs +++ b/tests/contracts/account-security.test.mjs @@ -1,3 +1,6 @@ +import { Secp256k1Keypair } from "@atproto/crypto"; +import { cidForCbor } from "@atproto/common"; +import * as plc from "@did-plc/lib"; import { query, failureTrigger, @@ -6,6 +9,7 @@ import { } from "../support/database-fixture.mjs"; import { createSecurityPrimitives } from "../../dist/src/accounts/security-primitives.mjs"; import { createAccountAccess } from "../../dist/src/accounts/account-access.mjs"; +import { createArrivalStorage } from "../../dist/src/database/drizzle/migration-arrival.js"; import { createAccountAuthority } from "../../dist/src/database/drizzle/account-authority.mjs"; import assert from "node:assert/strict"; import { randomBytes } from "node:crypto"; @@ -1808,6 +1812,87 @@ test("stale saved deletion authorization cannot manufacture another deletion adm assert.equal((await f.accounts.get(f.alice.did)).status, "deleted"); }); +test("active arrivals reject email availability, pending, backup and final authority changes atomically", async (t) => { + const f = await fixture(t); + const email = "arrival@example.com"; + const userId = await f.accounts.storage.ensureVerifiedEmailUser(email); + // Preparation only reads account authority; all writes below use the real helper. + const preparing = createArrivalStorage(f.db, f.config.pds, { + readAccount: (did) => f.accounts.storage.getByDid(did), + readBinding: (did) => f.accounts.storage.getVerifiedBinding(did), + }); + const sourceKey = await Secp256k1Keypair.create(); + const hotKey = await Secp256k1Keypair.create(); + const sourcePredecessor = await plc.signOperation( + plc.formatAtprotoOp({ + signingKey: sourceKey.did(), + handle: "incoming.entryway.atmosbox.test", + pds: "https://source.example.test", + rotationKeys: [sourceKey.did()], + prev: null, + }), + sourceKey, + ); + await preparing.createArrival({ + operationId: "authority-arrival", + did: "did:plc:incomingauthority", + userId, + email, + handle: "incoming.entryway.atmosbox.test", + pdsId: "pds1", + endpoint: f.config.pds[0].url, + sourcePlcHead: String(await cidForCbor(sourcePredecessor)), + sourcePredecessor, + source: { + services: sourcePredecessor.services, + verificationMethods: sourcePredecessor.verificationMethods, + alsoKnownAs: sourcePredecessor.alsoKnownAs, + }, + approvedRotationKeys: [sourceKey.did(), hotKey.did()], + codeHash: "a".repeat(64), + codeExpiresAt: Date.now() + 60_000, + }); + assert.ok(await preparing.readArrival("authority-arrival", userId)); + const authority = createAccountAuthority({ db: f.db, accounts: f.accounts }); + const snapshot = async () => ({ + accounts: await f.db.read("accounts"), + claims: await f.db.read("email_claims"), + bindings: await f.db.read("account_bindings"), + users: await f.db.read("user"), + sessions: await f.db.read("session"), + state: await f.db.read("key_value_state"), + arrivals: await f.db.read("arrivals"), + }); + for (const write of [ + () => authority.assertEmailAvailable(" ARRIVAL@EXAMPLE.COM ", f.alice.did), + () => + authority.reservePendingEmail({ + did: f.alice.did, + email, + recovery: false, + expiresAt: Date.now() + 60_000, + }), + () => authority.addBackupEmail(f.alice.did, email), + ...[false, true].map( + (verified) => () => + authority.commitEmailChange({ + did: f.alice.did, + email, + recovery: false, + verified, + previousEmail: f.alice.email, + }), + ), + ]) { + const before = await snapshot(); + await assert.rejects( + write, + (error) => (error.error ?? error.code) === "EmailNotAvailable", + ); + assert.deepEqual(await snapshot(), before); + } +}); + // "Confirm it's you": a browser session signed in more than ten minutes ago proves // its mailbox again by email code instead of signing in again. const staleActor = (actor) => ({ diff --git a/tests/contracts/external-workflow.test.mjs b/tests/contracts/external-workflow.test.mjs index c00c7cf1..205af124 100644 --- a/tests/contracts/external-workflow.test.mjs +++ b/tests/contracts/external-workflow.test.mjs @@ -61,10 +61,10 @@ async function fixture() { assert.equal(input.handle, "moved.entryway.test"); calls.push("reserve"); }, - async finalizeImportedAccount() { + async bindProvisionedArrival() { calls.push("bind"); }, - async activateImportedAccount() { + async activateBoundArrival() { assert.equal(state.active, true); calls.push("local-active"); }, diff --git a/tests/contracts/incoming-arrival-storage.test.mjs b/tests/contracts/incoming-arrival-storage.test.mjs new file mode 100644 index 00000000..ae4de2a4 --- /dev/null +++ b/tests/contracts/incoming-arrival-storage.test.mjs @@ -0,0 +1,3303 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + failureTrigger, + hasFailure, + openTestDatabase, + query, + removeFailureTrigger, + verifiedUser, + browserSession, +} from "../support/database-fixture.mjs"; +import { createAccountStorage } from "../../dist/src/database/drizzle/account-storage.js"; +import { createArrivalStorage } from "../../dist/src/database/drizzle/migration-arrival.js"; +import { createOperationOwnershipStore } from "../../dist/src/database/drizzle/operation-ownership.js"; +import { Secp256k1Keypair } from "@atproto/crypto"; +import * as plc from "@did-plc/lib"; +import { cidForCbor } from "@atproto/common"; + +const hosts = [ + { id: "pds1", url: "https://pds1.example.test" }, + { id: "pds2", url: "https://pds2.example.test" }, +]; +const endpoint = hosts[0].url; +const did = "did:plc:arrivalstorage00000000000"; +const otherDid = "did:plc:arrivalother000000000000"; +const day = 86_400_000; + +const hash = (char) => char.repeat(64); +const persistedVersion = async (db, operationId) => + ( + await query(db, "SELECT version FROM arrivals WHERE operation_id = ?", [ + operationId, + ]) + )[0].version; +const head = (char) => "bafyreih".concat(char.repeat(52)); +const publicKey = (char) => "did:key:zQ3sh".concat(char.repeat(44)); +const sourceKey = await Secp256k1Keypair.create(); +const hotKey = await Secp256k1Keypair.create(); +const reservedKey = await Secp256k1Keypair.create(); +const rotationKeys = [sourceKey.did(), hotKey.did()]; +const sourcePredecessor = await plc.signOperation( + plc.formatAtprotoOp({ + signingKey: sourceKey.did(), + handle: "dest.entryway.test", + pds: endpoint, + rotationKeys: [sourceKey.did()], + prev: null, + }), + sourceKey, +); +const source = { + verificationMethods: sourcePredecessor.verificationMethods, + services: sourcePredecessor.services, + alsoKnownAs: sourcePredecessor.alsoKnownAs, +}; +const sourcePlcHead = String(await cidForCbor(sourcePredecessor)); +const preparationAuthority = { + sourcePredecessor, + source, + sourcePlcHead, + approvedRotationKeys: rotationKeys, +}; +const signed = async (tag = "a", overrides = {}) => { + const { sig: _sourceSignature, ...sourceUnsigned } = sourcePredecessor; + const handoff = await plc.signOperation( + { ...sourceUnsigned, rotationKeys, prev: sourcePlcHead }, + sourceKey, + ); + const { sig: _handoffSignature, ...handoffUnsigned } = handoff; + const operation = + tag === "b" + ? await plc.signOperation( + { + ...handoffUnsigned, + prev: String(await cidForCbor(handoff)), + verificationMethods: { atproto: reservedKey.did() }, + ...overrides, + }, + hotKey, + ) + : await plc.signOperation( + { ...handoffUnsigned, ...overrides }, + sourceKey, + ); + const normalized = plc.def.operation.parse(operation); + return { operation: normalized, cid: String(await cidForCbor(normalized)) }; +}; + +async function fixture() { + const db = await openTestDatabase(":memory:"); + const accounts = createAccountStorage(db, hosts); + const arrivals = createArrivalStorage(db, hosts, { + readAccount: (value) => accounts.getByDid(value), + readBinding: (value) => accounts.getVerifiedBinding(value), + reserveEmailClaim: (email, value, purpose, userId) => + accounts.reserveEmail(email, value, purpose, userId), + reserveHandleClaim: (handle, value) => + accounts.reserveHandle(handle, value), + recordSavedUserBinding: (value, userId) => + db.insert( + "account_bindings", + { did: value, user_id: userId }, + { ignoreConflict: true }, + ), + insertPlacedAccount: (input) => + accounts.insertAccount( + { + did: input.did, + email: input.email, + emailVerified: true, + handle: input.handle, + pdsId: input.pdsId, + pdsUrl: input.pdsUrl, + status: "provisioning", + createdAt: new Date().toISOString(), + }, + input.userId, + ), + }); + const ownership = createOperationOwnershipStore(db); + const claim = await ownership.acquire({ + resource: `arrival:${did}`, + kind: "public-arrival", + requestDigest: hash("c"), + workerId: "worker-1", + leaseMs: 120_000, + }); + const prepare = (overrides = {}) => + arrivals.createArrival({ + operationId: "op-1", + did, + userId: "user-a", + email: "dest@example.test", + handle: "dest.entryway.test", + pdsId: "pds1", + endpoint, + ...preparationAuthority, + codeHash: hash("a"), + codeExpiresAt: Date.now() + day, + ...overrides, + }); + const allocate = async ( + version, + operationId = "op-1", + operationDid = did, + key = reservedKey.did(), + ) => { + const intent = await arrivals.recordAllocationIntent(claim, version, { + operationId, + did: operationDid, + pdsId: "pds1", + endpoint, + }); + assert.deepEqual(intent, { kind: "applied", version: version + 1 }); + const result = await arrivals.recordReservationResult( + claim, + intent.version, + { + operationId, + did: operationDid, + pdsId: "pds1", + endpoint, + signingKey: key, + }, + ); + assert.deepEqual(result, { kind: "applied", version: version + 2 }); + return result.version; + }; + const bind = (version, overrides = {}) => + arrivals.bindProvisionedArrival({ + owner: claim, + expectedVersion: version, + operationId: "op-1", + did, + userId: "user-a", + email: "dest@example.test", + handle: "dest.entryway.test", + pdsId: "pds1", + placement: { provisioned: true, deactivationObserved: true }, + ...overrides, + }); + await verifiedUser(db, "user-a", "dest@example.test"); + return { db, accounts, arrivals, claim, prepare, allocate, bind }; +} + +test("arrival preparation stores only a code hash and admits one active arrival per DID", async () => { + const { db, arrivals, prepare } = await fixture(); + try { + const prepared = await prepare(); + assert.equal(prepared.version, 1); + assert.equal(prepared.generation, 1); + assert.equal(prepared.signingKey, null); + assert.equal(prepared.codeDelivered, true); + assert.deepEqual(await query(db, "SELECT code_hash FROM arrival_code"), [ + { code_hash: hash("a") }, + ]); + assert.equal( + await arrivals.consumeArrivalCode({ + codeHash: hash("b"), + did, + method: "com.atproto.server.createAccount", + }), + null, + ); + + await assert.rejects(prepare({ operationId: "op-2" }), { + code: "EmailNotAvailable", + }); + await verifiedUser(db, "user-b", "second@example.test"); + await assert.rejects( + prepare({ + operationId: "op-4", + did: otherDid, + userId: "user-a", + email: "dest@example.test", + handle: "second.example.test", + pdsId: "pds2", + endpoint: hosts[1].url, + }), + { code: "EmailNotAvailable" }, + ); + await assert.rejects( + prepare({ + operationId: "op-5", + did: otherDid, + userId: "user-b", + email: "second@example.test", + handle: "dest.entryway.test", + pdsId: "pds2", + endpoint: hosts[1].url, + }), + { code: "HandleNotAvailable" }, + ); + assert.equal( + (await query(db, "SELECT operation_id FROM arrivals")).length, + 1, + ); + const independent = await prepare({ + operationId: "op-6", + did: otherDid, + userId: "user-b", + email: "second@example.test", + handle: "second.example.test", + pdsId: "pds2", + endpoint: hosts[1].url, + }); + assert.equal(independent.did, otherDid); + assert.equal(independent.userId, "user-b"); + } finally { + await db.close(); + } +}); + +test("arrival preparation requires the saved verified user, a configured host and a 24 hour lifetime", async () => { + const { db, prepare } = await fixture(); + try { + await verifiedUser(db, "user-b", "unverified@example.test"); + for (const unverified of [ + { userId: "user-b", email: "someone-else@example.test" }, + { userId: "user-missing" }, + ]) + await assert.rejects(prepare(unverified), { code: "AccountMismatch" }); + await assert.rejects(prepare({ pdsId: "pds2" }), { + code: "InvalidAccount", + }); + await assert.rejects(prepare({ endpoint: hosts[1].url }), { + code: "InvalidAccount", + }); + for (const codeExpiresAt of [ + Date.now() + day + 60_000, + Date.now() + 8 * day, + Date.now(), + Date.now() - day, + ]) + await assert.rejects(prepare({ codeExpiresAt }), { + code: "InvalidAccount", + }); + assert.equal( + (await query(db, "SELECT operation_id FROM arrivals")).length, + 0, + ); + const shorter = await prepare({ codeExpiresAt: Date.now() + 3_600_000 }); + assert.equal(shorter.codeExpiresAt > Date.now(), true); + } finally { + await db.close(); + } +}); + +test("arrival code expiry is bounded to 24 hours by the database, not only by the adapter", async () => { + const { db } = await fixture(); + try { + const now = Date.now(); + await query( + db, + "INSERT INTO arrivals (operation_id, did, did_root, active, user_id, email, handle, pds_id, endpoint, source_plc_head, source_predecessor, source_facts, approved_rotation_keys, version, generation, created_at, updated_at) VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, '{}', '{}', '[]', 1, 1, ?, ?)", + [ + "op-direct", + did, + did, + "user-a", + "direct@example.test", + "direct.entryway.test", + "pds1", + endpoint, + head("a"), + now, + now, + ], + "run", + ); + for (const expires_at of [now + day + 1, now + 8 * day]) { + await assert.rejects( + query( + db, + "INSERT INTO arrival_code (operation_id, code_hash, generation, issued_at, expires_at) VALUES (?, ?, 1, ?, ?)", + ["op-direct", hash("f"), now, expires_at], + "run", + ), + hasFailure("arrival_code_ceiling"), + ); + } + await assert.rejects( + query( + db, + "INSERT INTO arrival_code (operation_id, code_hash, generation, issued_at, expires_at) VALUES (?, ?, 1, ?, ?)", + ["op-direct", hash("f"), now, now - 1], + "run", + ), + hasFailure("arrival_code_lifetime"), + ); + await query( + db, + "INSERT INTO arrival_code (operation_id, code_hash, generation, issued_at, expires_at) VALUES (?, ?, 1, ?, ?)", + ["op-direct", hash("f"), now, now + day], + "run", + ); + assert.deepEqual( + await query( + db, + "SELECT issued_at, expires_at FROM arrival_code WHERE operation_id = ?", + ["op-direct"], + ), + [{ issued_at: now, expires_at: now + day }], + ); + } finally { + await db.close(); + } +}); + +for (const action of ["rotateArrivalCode", "cancelArrival"]) + test(`${action} hides unknown and nonowner arrivals without mutation`, async () => { + for (const state of ["pending", "intent", "reserved", "cancelled"]) { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + let version = prepared.version; + if (state === "intent") + version = ( + await arrivals.recordAllocationIntent(claim, version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + }) + ).version; + if (state === "reserved") version = await allocate(version); + if (state === "cancelled") + version = ( + await arrivals.cancelArrival({ + owner: claim, + operationId: "op-1", + expectedVersion: version, + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }) + ).version; + const snapshot = async () => ({ + arrivals: await query(db, "SELECT * FROM arrivals"), + codes: await query(db, "SELECT * FROM arrival_code"), + reservations: await query(db, "SELECT * FROM arrival_reservations"), + ownership: await query(db, "SELECT * FROM authority_operations"), + }); + const before = await snapshot(); + for (const expectedVersion of [version, version - 1, -1, 1.5, NaN]) { + const errors = []; + for (const operationId of ["op-missing", "op-1"]) { + await assert.rejects( + arrivals[action]({ + owner: claim, + operationId, + expectedVersion, + ownerUserId: "user-b", + codeHash: hash("b"), + codeExpiresAt: Date.now() + day, + noRemoteObligation: true, + plcStateUnchanged: true, + }), + (error) => { + const shape = { + code: error.code, + status: error.status, + message: error.message, + }; + assert.deepEqual(shape, { + code: "AccountNotFound", + status: 404, + message: "Arrival not found", + }); + errors.push(shape); + return true; + }, + ); + assert.deepEqual(await snapshot(), before); + } + assert.deepEqual(errors[0], errors[1]); + } + } finally { + await db.close(); + } + } + }); + +test("arrival code rotation invalidates the previous generation and cannot redirect placement", async () => { + const { db, arrivals, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const rotated = await arrivals.rotateArrivalCode({ + operationId: "op-1", + expectedVersion: prepared.version, + ownerUserId: "user-a", + codeHash: hash("b"), + codeExpiresAt: Date.now() + day, + }); + assert.equal(rotated.generation, 2); + for (const [codeHash, expected] of [ + [hash("a"), null], + [hash("b"), "op-1"], + ]) + assert.equal( + ( + await arrivals.consumeArrivalCode({ + codeHash, + did, + method: "com.atproto.server.createAccount", + }) + )?.operationId ?? null, + expected, + ); + await verifiedUser(db, "user-b", "intruder@example.test"); + await assert.rejects( + arrivals.rotateArrivalCode({ + operationId: "op-1", + expectedVersion: prepared.version, + ownerUserId: "user-a", + codeHash: hash("c"), + codeExpiresAt: Date.now() + day, + }), + { code: "OperationConflict" }, + ); + await assert.rejects( + arrivals.rotateArrivalCode({ + operationId: "op-1", + expectedVersion: rotated.version, + ownerUserId: "user-b", + codeHash: hash("c"), + codeExpiresAt: Date.now() + day, + }), + { code: "AccountNotFound", status: 404, message: "Arrival not found" }, + ); + + assert.equal(await arrivals.readArrival("op-1", "user-b"), null); + assert.equal((await prepare()).operationId, "op-1"); + + const rotatedAgain = await arrivals.rotateArrivalCode({ + operationId: "op-1", + expectedVersion: rotated.version, + ownerUserId: "user-a", + codeHash: hash("c"), + codeExpiresAt: Date.now() + day, + }); + assert.equal(rotatedAgain.generation, 3); + assert.equal( + await arrivals.consumeArrivalCode({ + codeHash: hash("b"), + did, + method: "com.atproto.server.createAccount", + }), + null, + ); + await allocate(rotatedAgain.version); + const consumed = await arrivals.consumeArrivalCode({ + codeHash: hash("c"), + did, + method: "com.atproto.server.createAccount", + }); + assert.equal(consumed.signingKey, reservedKey.did()); + assert.deepEqual(consumed, await arrivals.readArrival("op-1", "user-a")); + assert.equal((await arrivals.readArrival("op-1", "user-a")).generation, 3); + assert.equal( + (await arrivals.readArrival("op-1", "user-a")).signingKey, + reservedKey.did(), + ); + } finally { + await db.close(); + } +}); + +test("allocation intent is durable before dispatch and the tuple is immutable", async () => { + const { db, arrivals, claim, prepare } = await fixture(); + try { + const prepared = await prepare(); + const intent = await arrivals.recordAllocationIntent( + claim, + prepared.version, + { operationId: "op-1", did, pdsId: "pds1", endpoint }, + ); + assert.deepEqual(intent, { kind: "applied", version: 2 }); + assert.deepEqual( + await query( + db, + "SELECT signing_key, uncertain_reason FROM arrival_reservations", + ), + [{ signing_key: null, uncertain_reason: null }], + ); + await assert.rejects( + arrivals.recordReservationResult(claim, intent.version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: "did:key:zPrivateMaterial", + }), + { code: "InvalidAccount" }, + ); + for (const redirect of [ + { pdsId: "pds2", endpoint: hosts[1].url }, + { pdsId: "pds1", endpoint: hosts[1].url }, + { did: otherDid }, + ]) + await assert.rejects( + arrivals.recordAllocationIntent(claim, intent.version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + ...redirect, + }), + { code: "OperationConflict" }, + ); + assert.deepEqual(await arrivals.readArrivalAccess(did), { + operationId: "op-1", + version: 2, + did, + userId: "user-a", + pdsId: "pds1", + provisioned: false, + deactivationObserved: false, + bound: false, + complete: false, + unresolvedAttempt: false, + }); + } finally { + await db.close(); + } +}); + +test("a validated reservation result is conditional and a changed key never overwrites it", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + assert.deepEqual( + await arrivals.recordReservationResult(claim, version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: reservedKey.did(), + }), + { kind: "applied", version: version + 1 }, + ); + assert.deepEqual( + await arrivals.recordReservationResult(claim, version + 1, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: publicKey("n"), + }), + { kind: "reconciliation-required", reason: "saved-key-differs" }, + ); + await assert.rejects( + arrivals.recordReservationResult( + { ...claim, fence: claim.fence - 1 }, + version + 1, + { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: reservedKey.did(), + }, + ), + { code: "OperationLeaseLost" }, + ); + await assert.rejects( + arrivals.recordReservationResult(claim, version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: publicKey("n"), + }), + { code: "OperationConflict" }, + ); + assert.equal( + (await arrivals.readArrival("op-1", "user-a")).signingKey, + reservedKey.did(), + ); + } finally { + await db.close(); + } +}); + +test("an uncertain allocation retains recovery and permits no automatic retry", async () => { + const { db, accounts, arrivals, claim, prepare, bind } = await fixture(); + try { + const prepared = await prepare(); + const intent = await arrivals.recordAllocationIntent( + claim, + prepared.version, + { operationId: "op-1", did, pdsId: "pds1", endpoint }, + ); + const uncertain = await arrivals.retainUncertainAttempt( + claim, + intent.version, + { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + reason: "lost-response", + }, + ); + assert.deepEqual(uncertain, { + kind: "reconciliation-required", + reason: "uncertain-attempt", + }); + assert.deepEqual( + await query( + db, + "SELECT reason, fence FROM arrival_attempts WHERE operation_id = ?", + ["op-1"], + ), + [{ reason: "lost-response", fence: claim.fence }], + ); + assert.equal( + (await arrivals.readArrivalAccess(did)).unresolvedAttempt, + true, + ); + const currentVersion = (await arrivals.readArrival("op-1", "user-a")) + .version; + await assert.rejects( + arrivals.recordReservationResult(claim, currentVersion, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: publicKey("n"), + }), + { code: "OperationRecoveryRequired" }, + ); + await assert.rejects( + bind((await arrivals.readArrival("op-1", "user-a")).version), + { code: "OperationRecoveryRequired" }, + ); + await assert.rejects( + arrivals.cancelArrival({ + owner: claim, + operationId: "op-1", + expectedVersion: (await arrivals.readArrival("op-1", "user-a")).version, + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }), + { code: "OperationRecoveryRequired" }, + ); + assert.equal(await accounts.getByDid(did), null); + } finally { + await db.close(); + } +}); + +test("allocation intent rolls back with any later failure in the same transaction", async () => { + const { db, arrivals, claim, prepare } = await fixture(); + try { + const prepared = await prepare(); + await failureTrigger(db, "fail_family", "arrival_families", "injected"); + await assert.rejects( + db.transact(async () => { + await arrivals.recordAllocationIntent(claim, prepared.version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + }); + await db.insert("arrival_families", { + family_id: "family-rollback", + operation_id: "op-1", + pds_id: "pds1", + created_at: Date.now(), + revoked_at: null, + }); + }), + hasFailure("injected"), + ); + await removeFailureTrigger(db, "fail_family", "arrival_families"); + assert.deepEqual( + await query(db, "SELECT operation_id FROM arrival_reservations"), + [], + ); + assert.equal((await arrivals.readArrival("op-1", "user-a")).version, 1); + const retried = await arrivals.recordAllocationIntent( + claim, + prepared.version, + { operationId: "op-1", did, pdsId: "pds1", endpoint }, + ); + assert.deepEqual(retried, { kind: "applied", version: 2 }); + assert.equal(await persistedVersion(db, "op-1"), retried.version); + } finally { + await db.close(); + } +}); + +test("a lost result persistence leaves the intent retained and requires reconciliation", async () => { + const { db, arrivals, claim, prepare } = await fixture(); + try { + const prepared = await prepare(); + const intent = await arrivals.recordAllocationIntent( + claim, + prepared.version, + { operationId: "op-1", did, pdsId: "pds1", endpoint }, + ); + const dispatched = publicKey("q"); + await query( + db, + db.backend === "sqlite" + ? "CREATE TRIGGER fail_result BEFORE UPDATE ON arrival_reservations BEGIN SELECT RAISE(ABORT, 'injected'); END" + : "CREATE FUNCTION fail_result() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected'; END $$", + [], + "run", + ); + if (db.backend === "postgresql") + await query( + db, + "CREATE TRIGGER fail_result BEFORE UPDATE ON arrival_reservations FOR EACH ROW EXECUTE FUNCTION fail_result()", + [], + "run", + ); + await assert.rejects( + arrivals.recordReservationResult(claim, intent.version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: dispatched, + }), + hasFailure("injected"), + ); + await query( + db, + db.backend === "sqlite" + ? "DROP TRIGGER fail_result" + : "DROP TRIGGER fail_result ON arrival_reservations", + [], + "run", + ); + if (db.backend === "postgresql") + await query(db, "DROP FUNCTION fail_result()", [], "run"); + const retained = await query( + db, + "SELECT signing_key, uncertain_reason FROM arrival_reservations WHERE operation_id = ?", + ["op-1"], + ); + assert.deepEqual(retained, [{ signing_key: null, uncertain_reason: null }]); + assert.equal( + (await arrivals.readArrival("op-1", "user-a")).version, + intent.version, + ); + const uncertain = await arrivals.retainUncertainAttempt( + claim, + intent.version, + { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + reason: "result-persistence-lost", + }, + ); + assert.deepEqual(uncertain, { + kind: "reconciliation-required", + reason: "uncertain-attempt", + }); + assert.equal( + (await arrivals.readArrivalAccess(did)).unresolvedAttempt, + true, + ); + await assert.rejects( + arrivals.recordReservationResult( + claim, + (await arrivals.readArrival("op-1", "user-a")).version, + { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: dispatched, + }, + ), + { code: "OperationRecoveryRequired" }, + ); + assert.equal( + (await query(db, "SELECT signing_key FROM arrival_reservations"))[0] + .signing_key, + null, + ); + } finally { + await db.close(); + } +}); + +test("two concurrent reservation results resolve to one saved key and one version", async () => { + const { db, arrivals, claim, prepare } = await fixture(); + try { + const prepared = await prepare(); + const intent = await arrivals.recordAllocationIntent( + claim, + prepared.version, + { operationId: "op-1", did, pdsId: "pds1", endpoint }, + ); + const results = await Promise.allSettled([ + arrivals.recordReservationResult(claim, intent.version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: reservedKey.did(), + }), + arrivals.recordReservationResult(claim, intent.version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: publicKey("n"), + }), + ]); + const outcomes = results.map((result) => + result.status === "fulfilled" + ? result.value + : { kind: "rejected", code: result.reason.code }, + ); + const applied = outcomes.filter(({ kind }) => kind === "applied"); + const lost = outcomes.filter(({ kind }) => kind !== "applied"); + assert.equal(applied.length, 1); + assert.equal(lost.length, 1); + assert.equal( + lost[0].kind === "reconciliation-required" + ? lost[0].reason === "saved-key-differs" + : lost[0].code === "OperationConflict", + true, + ); + assert.equal(await persistedVersion(db, "op-1"), applied[0].version); + assert.equal( + ( + await query( + db, + "SELECT signing_key FROM arrival_reservations WHERE operation_id = ?", + ["op-1"], + ) + )[0].signing_key, + (await arrivals.readArrival("op-1", "user-a")).signingKey, + ); + } finally { + await db.close(); + } +}); + +test("immutable method admission checks proof once, permits handoff then creation and fences retries", async () => { + const { db, arrivals, claim, prepare } = await fixture(); + try { + const prepared = await prepare(); + const facts = { + operationId: "op-1", + did, + method: "com.atproto.identity.submitPlcOperation", + requestDigest: hash("d"), + credentialIssuer: did, + credentialJti: "handoff-token", + }; + const proof = { codeHash: hash("a"), codeGeneration: 1 }; + await assert.rejects( + arrivals.recordArrivalReplay(claim, prepared.version, facts, { + ...proof, + codeHash: hash("b"), + }), + { code: "AccountMismatch" }, + ); + assert.equal(await persistedVersion(db, "op-1"), 1); + assert.deepEqual( + await arrivals.recordArrivalReplay(claim, 1, facts, proof), + { operationId: "op-1", generation: 1 }, + ); + assert.deepEqual( + await arrivals.recordArrivalReplay(claim, 1, facts, { + codeHash: "expired", + codeGeneration: 0, + }), + { operationId: "op-1", generation: 1 }, + ); + assert.equal(await persistedVersion(db, "op-1"), 2); + await assert.rejects( + arrivals.recordArrivalReplay( + claim, + 2, + { ...facts, requestDigest: hash("e") }, + proof, + ), + { code: "OperationConflict" }, + ); + await assert.rejects( + arrivals.recordArrivalReplay( + claim, + 2, + { ...facts, method: "com.atproto.server.createAccount" }, + proof, + ), + { code: "OperationConflict" }, + ); + await arrivals.recordArrivalReplay( + claim, + 2, + { + ...facts, + method: "com.atproto.server.createAccount", + credentialJti: "create-token", + }, + proof, + ); + await assert.rejects( + arrivals.recordArrivalReplay( + { ...claim, fence: claim.fence + 1 }, + 1, + facts, + proof, + ), + { code: "OperationLeaseLost" }, + ); + assert.equal((await db.read("arrival_replay")).length, 2); + } finally { + await db.close(); + } +}); + +test("binding commits saved user, account, claims and placement only with observed evidence", async () => { + const { db, accounts, arrivals, prepare, allocate, bind } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + for (const placement of [ + { provisioned: false, deactivationObserved: true }, + { provisioned: true, deactivationObserved: false }, + { provisioned: false, deactivationObserved: false }, + ]) + await assert.rejects(bind(version, { placement }), { + code: "OperationConflict", + }); + assert.equal(await accounts.getByDid(did), null); + assert.equal(await accounts.hasPendingExternalMigration(did), true); + + const bound = await bind(version); + assert.equal(bound.kind, "applied"); + assert.equal((await accounts.getByDid(did))?.status, "provisioning"); + assert.equal((await accounts.getVerifiedBinding(did))?.userId, "user-a"); + assert.deepEqual(await accounts.listEmailClaims("dest@example.test"), [ + { did, purpose: "primary" }, + ]); + assert.equal(await accounts.getHandleClaim("dest.entryway.test"), did); + assert.equal((await arrivals.readArrivalAccess(did)).bound, true); + assert.equal((await arrivals.readArrivalAccess(did)).complete, false); + + const beforeRetry = await claimSnapshot(db); + for (const expectedVersion of [version, bound.version]) { + assert.deepEqual(await bind(expectedVersion), { + kind: "already-settled", + version: bound.version, + }); + assert.deepEqual(await claimSnapshot(db), beforeRetry); + } + await verifiedUser(db, "user-b", "intruder@example.test"); + await assert.rejects(bind(bound.version, { userId: "user-b" }), { + code: "OperationConflict", + }); + assert.equal((await query(db, "SELECT did FROM accounts")).length, 1); + } finally { + await db.close(); + } +}); + +test("pending binding retries reject changed tuples without writes", async () => { + const { db, prepare, allocate, bind } = await fixture(); + try { + const version = await allocate((await prepare()).version); + const bound = await bind(version); + const before = await claimSnapshot(db); + for (const expectedVersion of [version, bound.version]) + for (const changed of [ + { did: otherDid }, + { userId: "other-user" }, + { email: "changed@example.test" }, + { handle: "changed.entryway.test" }, + { pdsId: "pds2" }, + { placement: { provisioned: true, deactivationObserved: false } }, + ]) { + await assert.rejects(bind(expectedVersion, changed), { + code: "OperationConflict", + }); + assert.deepEqual(await claimSnapshot(db), before); + } + } finally { + await db.close(); + } +}); + +for (const drift of [ + "account-email", + "account-handle", + "account-pds", + "account-status", + "account-payload", + "binding", + "email-claim", + "handle-claim", + "placement", + "reservation", +]) + test(`pending binding retry rejects persisted ${drift} drift without writes`, async () => { + const { db, prepare, allocate, bind } = await fixture(); + try { + const version = await allocate((await prepare()).version); + const bound = await bind(version); + if (drift.startsWith("account-")) { + const column = { + "account-email": "email", + "account-handle": "handle", + "account-pds": "pds_id", + "account-status": "status", + "account-payload": "data", + }[drift]; + const value = { + "account-email": "changed@example.test", + "account-handle": "changed.entryway.test", + "account-pds": "pds2", + "account-status": "active", + "account-payload": "{}", + }[drift]; + await query( + db, + `UPDATE accounts SET ${column} = ? WHERE did = ?`, + [value, did], + "run", + ); + } + if (drift === "binding") + await query(db, "DELETE FROM account_bindings", [], "run"); + if (drift === "email-claim") + await query(db, "DELETE FROM email_claims", [], "run"); + if (drift === "handle-claim") + await query(db, "DELETE FROM handle_claims", [], "run"); + if (drift === "placement") + await query( + db, + "UPDATE arrivals SET bound_at = NULL, deactivated_at = NULL", + [], + "run", + ); + if (drift === "reservation") + await query( + db, + "UPDATE arrival_reservations SET signing_key = NULL", + [], + "run", + ); + const before = await claimSnapshot(db); + for (const expectedVersion of [version, bound.version]) { + await assert.rejects(bind(expectedVersion), { + code: "OperationConflict", + }); + assert.deepEqual(await claimSnapshot(db), before); + } + } finally { + await db.close(); + } + }); + +test("a competing account cannot take the destination email before arrival binding", async () => { + const { db, accounts, arrivals, prepare, allocate, bind } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + await verifiedUser(db, "user-c", "sibling@example.test"); + await assert.rejects( + accounts.insertAccount( + { + did: otherDid, + email: "dest@example.test", + emailVerified: true, + handle: "sibling.entryway.test", + pdsId: "pds1", + pdsUrl: endpoint, + status: "active", + createdAt: new Date().toISOString(), + }, + "user-c", + ), + { code: "EmailNotAvailable" }, + ); + assert.equal(await accounts.getByDid(otherDid), null); + await bind(version); + assert.equal((await arrivals.readArrivalAccess(did)).bound, true); + } finally { + await db.close(); + } +}); + +test("activation completion is separate and requires exact version and observed evidence", async () => { + const { db, accounts, arrivals, claim, prepare, allocate, bind } = + await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const bound = await bind(version); + assert.equal(bound.kind, "applied"); + const complete = (overrides = {}) => + arrivals.completeArrivalActivation({ + owner: claim, + operationId: "op-1", + expectedVersion: bound.version, + did, + userId: "user-a", + activation: { + backendActiveObserved: true, + method: "com.atproto.server.activateAccount", + observedAt: Date.now(), + }, + ...overrides, + }); + for (const activation of [ + null, + { + backendActiveObserved: false, + method: "com.atproto.server.activateAccount", + observedAt: 1, + }, + { backendActiveObserved: true, method: "not-a-method", observedAt: 1 }, + ]) + await assert.rejects(complete({ activation }), { + code: "OperationRecoveryRequired", + }); + await assert.rejects(complete({ expectedVersion: bound.version - 1 }), { + code: "OperationConflict", + }); + assert.deepEqual(await complete(), { + kind: "applied", + version: bound.version + 1, + }); + assert.equal((await arrivals.readArrivalAccess(did)).complete, true); + const completedSnapshot = await claimSnapshot(db); + for (const expectedVersion of [version, bound.version + 1]) { + await assert.rejects(bind(expectedVersion), { + code: "OperationConflict", + }); + assert.deepEqual(await claimSnapshot(db), completedSnapshot); + } + assert.equal((await accounts.getByDid(did))?.status, "provisioning"); + await assert.rejects(complete({ expectedVersion: bound.version + 1 }), { + code: "OperationConflict", + }); + } finally { + await db.close(); + } +}); + +test("activation completion is rejected when the operation owner changed", async () => { + const { db, arrivals, claim, prepare, allocate, bind } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const bound = await bind(version); + await query( + db, + "UPDATE authority_operations SET lease_expires_at = ? WHERE id = ?", + [Date.now() - 1_000, claim.operationId], + "run", + ); + await assert.rejects( + arrivals.completeArrivalActivation({ + owner: claim, + operationId: "op-1", + expectedVersion: bound.version, + did, + userId: "user-a", + activation: { + backendActiveObserved: true, + method: "com.atproto.server.activateAccount", + observedAt: Date.now(), + }, + }), + { code: "OperationLeaseLost" }, + ); + assert.deepEqual( + await query( + db, + "SELECT active, completed_at, activation_method, version FROM arrivals WHERE operation_id = ?", + ["op-1"], + ), + [ + { + active: 1, + completed_at: null, + activation_method: null, + version: bound.version, + }, + ], + ); + assert.equal((await arrivals.readArrivalAccess(did)).complete, false); + } finally { + await db.close(); + } +}); + +test("credential family association and revocation are rejected when the operation owner changed", async () => { + const { db, arrivals, claim, prepare, allocate, bind } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const bound = await bind(version); + const recorded = await arrivals.recordCredentialFamily({ + owner: claim, + operationId: "op-1", + expectedVersion: bound.version, + familyId: "family-1", + did, + pdsId: "pds1", + }); + assert.deepEqual(recorded, { + kind: "applied", + version: bound.version + 1, + }); + await query( + db, + "UPDATE authority_operations SET lease_expires_at = ? WHERE id = ?", + [Date.now() - 1_000, claim.operationId], + "run", + ); + await assert.rejects( + arrivals.recordCredentialFamily({ + owner: claim, + operationId: "op-1", + expectedVersion: recorded.version, + familyId: "family-2", + did, + pdsId: "pds1", + }), + { code: "OperationLeaseLost" }, + ); + await assert.rejects( + arrivals.revokeArrivalCredentialFamilies({ + owner: claim, + operationId: "op-1", + expectedVersion: recorded.version, + }), + { code: "OperationLeaseLost" }, + ); + assert.deepEqual( + await query( + db, + "SELECT family_id, revoked_at FROM arrival_families ORDER BY family_id", + ), + [{ family_id: "family-1", revoked_at: null }], + ); + assert.equal(await persistedVersion(db, "op-1"), recorded.version); + } finally { + await db.close(); + } +}); + +test("cancellation releases local reservations only before a remote obligation exists", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + for (const evidence of [ + { noRemoteObligation: true, plcStateUnchanged: false }, + { noRemoteObligation: false, plcStateUnchanged: true }, + ]) + await assert.rejects( + arrivals.cancelArrival({ + owner: claim, + operationId: "op-1", + expectedVersion: prepared.version, + ownerUserId: "user-a", + ...evidence, + }), + { code: "OperationRecoveryRequired" }, + ); + await assert.rejects( + arrivals.cancelArrival({ + owner: claim, + operationId: "op-1", + expectedVersion: prepared.version - 1, + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }), + { code: "OperationConflict", status: 409 }, + ); + await assert.rejects( + arrivals.cancelArrival({ + owner: { ...claim, fence: claim.fence - 1 }, + operationId: "op-1", + expectedVersion: prepared.version, + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }), + { code: "OperationLeaseLost" }, + ); + const cancelled = await arrivals.cancelArrival({ + owner: claim, + operationId: "op-1", + expectedVersion: prepared.version, + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }); + assert.deepEqual(cancelled, { + kind: "applied", + version: prepared.version + 1, + }); + const [released] = await query( + db, + "SELECT active, did_root, cancelled_at, version FROM arrivals WHERE operation_id = ?", + ["op-1"], + ); + assert.deepEqual( + { active: released.active, did_root: released.did_root }, + { active: 0, did_root: null }, + ); + assert.equal(released.cancelled_at > 0, true); + assert.equal(released.version, cancelled.version); + assert.deepEqual( + await query(db, "SELECT operation_id FROM arrival_reservations"), + [], + ); + assert.deepEqual( + await arrivals.cancelArrival({ + owner: claim, + operationId: "op-1", + expectedVersion: cancelled.version, + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }), + { kind: "already-settled", version: cancelled.version }, + ); + assert.equal(await arrivals.readArrival("op-1", "user-a"), null); + + await verifiedUser(db, "user-b", "second@example.test"); + const next = await prepare({ + operationId: "op-2", + userId: "user-b", + email: "second@example.test", + handle: "second.example.test", + codeHash: hash("b"), + }); + assert.equal(next.operationId, "op-2"); + const version = await allocate(next.version, "op-2"); + await assert.rejects( + arrivals.cancelArrival({ + owner: claim, + operationId: "op-2", + expectedVersion: version, + ownerUserId: "user-b", + noRemoteObligation: true, + plcStateUnchanged: true, + }), + { code: "OperationRecoveryRequired" }, + ); + assert.equal( + (await arrivals.readArrival("op-2", "user-b")).signingKey, + reservedKey.did(), + ); + assert.equal( + ( + await query( + db, + "SELECT operation_id FROM arrivals ORDER BY operation_id", + ) + ).length, + 2, + ); + } finally { + await db.close(); + } +}); + +test("a saved allocation intent alone blocks cancellation while dispatch is in flight", async () => { + const { db, arrivals, claim, prepare } = await fixture(); + try { + const prepared = await prepare(); + const intent = await arrivals.recordAllocationIntent( + claim, + prepared.version, + { operationId: "op-1", did, pdsId: "pds1", endpoint }, + ); + assert.deepEqual(intent, { + kind: "applied", + version: prepared.version + 1, + }); + assert.deepEqual( + await query( + db, + "SELECT signing_key, uncertain_reason FROM arrival_reservations WHERE operation_id = ?", + ["op-1"], + ), + [{ signing_key: null, uncertain_reason: null }], + ); + await assert.rejects( + arrivals.cancelArrival({ + owner: claim, + operationId: "op-1", + expectedVersion: intent.version, + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }), + { code: "OperationRecoveryRequired" }, + ); + assert.deepEqual( + await query( + db, + "SELECT active, did_root, cancelled_at, version FROM arrivals WHERE operation_id = ?", + ["op-1"], + ), + [ + { + active: 1, + did_root: did, + cancelled_at: null, + version: intent.version, + }, + ], + ); + assert.deepEqual( + await query( + db, + "SELECT signing_key FROM arrival_reservations WHERE operation_id = ?", + ["op-1"], + ), + [{ signing_key: null }], + ); + } finally { + await db.close(); + } +}); + +test( + "two independent PostgreSQL connections contend on one arrival version", + { skip: process.env.CONTRACT_DATABASE_BACKEND !== "postgresql" }, + async () => { + const { openDatabase } = + await import("../../dist/src/database/connection.js"); + const { testDatabaseConfiguration } = + await import("../support/database-fixture.mjs"); + const { createOperationOwnershipStore } = + await import("../../dist/src/database/drizzle/operation-ownership.js"); + const configuration = await testDatabaseConfiguration(); + const first = await openDatabase(configuration); + const second = await openDatabase(configuration); + try { + assert.notEqual(first, second); + const accounts = createAccountStorage(first, hosts); + const authority = { + readAccount: (value) => accounts.getByDid(value), + readBinding: (value) => accounts.getVerifiedBinding(value), + reserveEmailClaim: (email, value, purpose, userId) => + accounts.reserveEmail(email, value, purpose, userId), + reserveHandleClaim: (handle, value) => + accounts.reserveHandle(handle, value), + recordSavedUserBinding: (value, userId) => + first.insert( + "account_bindings", + { did: value, user_id: userId }, + { ignoreConflict: true }, + ), + insertPlacedAccount: (input) => + accounts.insertAccount( + { + did: input.did, + email: input.email, + emailVerified: true, + handle: input.handle, + pdsId: input.pdsId, + pdsUrl: input.pdsUrl, + status: "provisioning", + createdAt: new Date().toISOString(), + }, + input.userId, + ), + }; + const initial = createArrivalStorage(first, hosts, authority); + const contender = createArrivalStorage(second, hosts, authority); + await verifiedUser(first, "user-a", "dest@example.test"); + const prepared = await initial.createArrival({ + operationId: "op-1", + did, + userId: "user-a", + email: "dest@example.test", + handle: "dest.entryway.test", + pdsId: "pds1", + endpoint, + ...preparationAuthority, + codeHash: hash("a"), + codeExpiresAt: Date.now() + day, + }); + const ownership = createOperationOwnershipStore(first); + const claim = await ownership.acquire({ + resource: `arrival:${did}`, + kind: "public-arrival", + requestDigest: hash("c"), + workerId: "worker-1", + leaseMs: 120_000, + }); + const intent = await initial.recordAllocationIntent( + claim, + prepared.version, + { operationId: "op-1", did, pdsId: "pds1", endpoint }, + ); + const [firstAttempt, secondAttempt] = await Promise.allSettled([ + initial.recordReservationResult(claim, intent.version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: reservedKey.did(), + }), + contender.recordReservationResult(claim, intent.version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + signingKey: reservedKey.did(), + }), + ]); + const outcomes = [firstAttempt, secondAttempt].map((result) => + result.status === "fulfilled" + ? result.value + : { kind: "rejected", code: result.reason.code }, + ); + assert.equal(outcomes.filter(({ kind }) => kind === "applied").length, 1); + assert.equal(outcomes.filter(({ kind }) => kind !== "applied").length, 1); + const losing = outcomes.find(({ kind }) => kind !== "applied"); + assert.equal( + losing.kind === "reconciliation-required" + ? losing.reason === "saved-key-differs" + : losing.code === "OperationConflict", + true, + ); + const applied = outcomes.find(({ kind }) => kind === "applied"); + assert.equal(applied.version, intent.version + 1); + const persisted = await query( + first, + "SELECT version FROM arrivals WHERE operation_id = ?", + ["op-1"], + ); + assert.equal(persisted[0].version, applied.version); + const reservationRow = await query( + first, + "SELECT signing_key FROM arrival_reservations WHERE operation_id = ?", + ["op-1"], + ); + assert.equal(reservationRow[0].signing_key, reservedKey.did()); + } finally { + await first.close(); + await second.close(); + } + }, +); + +test( + "a dispatch holding the operation fence cannot be released by a concurrent cancel", + { skip: process.env.CONTRACT_DATABASE_BACKEND !== "postgresql" }, + async () => { + const { openDatabase } = + await import("../../dist/src/database/connection.js"); + const { testDatabaseConfiguration } = + await import("../support/database-fixture.mjs"); + const configuration = await testDatabaseConfiguration(); + const dispatcher = await openDatabase(configuration); + const canceler = await openDatabase(configuration); + const gate = { open: false, resume: () => {} }; + try { + assert.notEqual(dispatcher, canceler); + const accounts = createAccountStorage(dispatcher, hosts); + const authority = { + readAccount: (value) => accounts.getByDid(value), + readBinding: (value) => accounts.getVerifiedBinding(value), + reserveEmailClaim: (email, value, purpose, userId) => + accounts.reserveEmail(email, value, purpose, userId), + reserveHandleClaim: (handle, value) => + accounts.reserveHandle(handle, value), + recordSavedUserBinding: (value, userId) => + dispatcher.insert( + "account_bindings", + { did: value, user_id: userId }, + { ignoreConflict: true }, + ), + insertPlacedAccount: (input) => + accounts.insertAccount( + { + did: input.did, + email: input.email, + emailVerified: true, + handle: input.handle, + pdsId: input.pdsId, + pdsUrl: input.pdsUrl, + status: "provisioning", + createdAt: new Date().toISOString(), + }, + input.userId, + ), + }; + const dispatching = createArrivalStorage(dispatcher, hosts, authority); + const canceling = createArrivalStorage(canceler, hosts, authority); + await verifiedUser(dispatcher, "user-a", "dest@example.test"); + const prepared = await dispatching.createArrival({ + operationId: "op-1", + did, + userId: "user-a", + email: "dest@example.test", + handle: "dest.entryway.test", + pdsId: "pds1", + endpoint, + ...preparationAuthority, + codeHash: hash("a"), + codeExpiresAt: Date.now() + day, + }); + const ownership = createOperationOwnershipStore(dispatcher); + const claim = await ownership.acquire({ + resource: `arrival:${did}`, + kind: "public-arrival", + requestDigest: hash("c"), + workerId: "worker-1", + leaseMs: 120_000, + }); + const intent = await dispatching.recordAllocationIntent( + claim, + prepared.version, + { operationId: "op-1", did, pdsId: "pds1", endpoint }, + ); + assert.deepEqual(intent, { + kind: "applied", + version: prepared.version + 1, + }); + + const held = Promise.withResolvers(); + const reached = Promise.withResolvers(); + gate.resume = held.resolve; + const dispatchFlight = dispatcher.transact(() => + dispatcher.withOperationFence(claim, async () => { + await ownership.renew(claim, 120_000); + reached.resolve(); + await held.promise; + }), + ); + await reached.promise; + const cancelFlight = canceling.cancelArrival({ + owner: claim, + operationId: "op-1", + expectedVersion: intent.version, + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }); + let cancelSettled = false; + void cancelFlight.then( + () => { + cancelSettled = true; + }, + () => { + cancelSettled = true; + }, + ); + const settled = Promise.allSettled([dispatchFlight, cancelFlight]); + await new Promise((resolve) => setTimeout(resolve, 400)); + assert.equal( + cancelSettled, + false, + "Cancellation must wait for the held operation fence", + ); + gate.open = true; + gate.resume(); + const [dispatchOutcome, cancelOutcome] = await settled; + assert.equal(dispatchOutcome.status, "fulfilled"); + assert.equal(cancelOutcome.status, "rejected"); + assert.equal(cancelOutcome.reason.code, "OperationRecoveryRequired"); + assert.deepEqual( + await query( + dispatcher, + "SELECT active, did_root, cancelled_at, version FROM arrivals WHERE operation_id = ?", + ["op-1"], + ), + [ + { + active: 1, + did_root: did, + cancelled_at: null, + version: intent.version, + }, + ], + ); + assert.deepEqual( + await query( + dispatcher, + "SELECT signing_key FROM arrival_reservations WHERE operation_id = ?", + ["op-1"], + ), + [{ signing_key: null }], + ); + } finally { + if (!gate.open) gate.resume(); + await dispatcher.close(); + await canceler.close(); + } + }, +); + +test("access projection prefers the active arrival and breaks identical milliseconds by operation id", async () => { + const { db, arrivals, claim, prepare, allocate, bind } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const bound = await bind(version); + await arrivals.completeArrivalActivation({ + owner: claim, + operationId: "op-1", + expectedVersion: bound.version, + did, + userId: "user-a", + activation: { + backendActiveObserved: true, + method: "com.atproto.server.activateAccount", + observedAt: Date.now(), + }, + }); + const completed = await query( + db, + "SELECT created_at, updated_at, version FROM arrivals WHERE operation_id = ?", + ["op-1"], + ); + assert.equal((await arrivals.readArrivalAccess(did)).operationId, "op-1"); + const sameMillisecond = completed[0].created_at; + for (const operationId of ["op-0", "op-2"]) { + await query( + db, + "INSERT INTO arrivals (operation_id, did, did_root, active, user_id, email, handle, pds_id, endpoint, source_plc_head, source_predecessor, source_facts, approved_rotation_keys, version, generation, created_at, updated_at, cancelled_at) VALUES (?, ?, NULL, 0, ?, ?, ?, 'pds1', ?, ?, '{}', '{}', '[]', 1, 1, ?, ?, ?)", + [ + operationId, + did, + "user-a", + `${operationId}@example.test`, + `${operationId}.entryway.test`, + endpoint, + head("a"), + sameMillisecond, + sameMillisecond, + sameMillisecond, + ], + "run", + ); + } + const active = await arrivals.readArrivalAccess(did); + assert.equal(active.operationId, "op-1"); + assert.equal(active.complete, true); + await query( + db, + "UPDATE arrivals SET did_root = NULL WHERE operation_id = ?", + ["op-1"], + "run", + ); + await query( + db, + "UPDATE arrivals SET updated_at = ? WHERE operation_id = ?", + [sameMillisecond + 5_000, "op-0"], + "run", + ); + assert.equal((await arrivals.readArrivalAccess(did)).operationId, "op-0"); + await query( + db, + "UPDATE arrivals SET updated_at = ? WHERE operation_id = ?", + [sameMillisecond + 9_000, "op-2"], + "run", + ); + assert.equal((await arrivals.readArrivalAccess(did)).operationId, "op-2"); + } finally { + await db.close(); + } +}); + +test("credential families associate only after binding and never replace signing", async () => { + const { db, arrivals, claim, prepare, allocate, bind } = await fixture(); + try { + const prepared = await prepare(); + await assert.rejects( + arrivals.recordCredentialFamily({ + owner: claim, + operationId: "op-1", + expectedVersion: prepared.version, + familyId: "family-1", + did, + pdsId: "pds1", + }), + { code: "OperationConflict" }, + ); + const version = await allocate(prepared.version); + const bound = await bind(version); + const recorded = await arrivals.recordCredentialFamily({ + owner: claim, + operationId: "op-1", + expectedVersion: bound.version, + familyId: "family-1", + did, + pdsId: "pds1", + }); + assert.deepEqual(recorded, { + kind: "applied", + version: bound.version + 1, + }); + assert.equal(await persistedVersion(db, "op-1"), recorded.version); + assert.deepEqual( + await query(db, "SELECT family_id, pds_id FROM arrival_families"), + [{ family_id: "family-1", pds_id: "pds1" }], + ); + await assert.rejects( + arrivals.recordCredentialFamily({ + owner: claim, + operationId: "op-1", + expectedVersion: bound.version, + familyId: "family-2", + did, + pdsId: "pds2", + }), + { code: "OperationConflict" }, + ); + assert.deepEqual( + await arrivals.recordCredentialFamily({ + owner: claim, + operationId: "op-1", + expectedVersion: recorded.version, + familyId: "family-2", + did, + pdsId: "pds1", + }), + { kind: "applied", version: recorded.version + 1 }, + ); + const revoked = await arrivals.revokeArrivalCredentialFamilies({ + owner: claim, + operationId: "op-1", + expectedVersion: recorded.version + 1, + }); + assert.deepEqual(revoked, { + kind: "applied", + version: recorded.version + 2, + }); + assert.equal(await persistedVersion(db, "op-1"), revoked.version); + const rows = await query( + db, + "SELECT revoked_at FROM arrival_families WHERE family_id = ?", + ["family-1"], + ); + assert.notEqual(rows[0].revoked_at, null); + } finally { + await db.close(); + } +}); + +test("the arrival row has a source endpoint slot for the approved handoff facts", async () => { + const { db, prepare } = await fixture(); + try { + await prepare(); + assert.deepEqual( + await query( + db, + "SELECT endpoint, source_endpoint FROM arrivals WHERE operation_id = ?", + ["op-1"], + ), + [{ endpoint, source_endpoint: endpoint }], + ); + } finally { + await db.close(); + } +}); + +test("a signed handoff is journaled with a new version and an exact repeat does not advance", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const handoff = await signed(); + const recorded = await arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + ...handoff, + }); + assert.deepEqual(recorded, { kind: "applied", version: version + 1 }); + assert.equal(await persistedVersion(db, "op-1"), version + 1); + assert.deepEqual( + await query( + db, + "SELECT kind, did, cid, operation, kind_operation_cid FROM arrival_signed_operations WHERE operation_id = ?", + ["op-1"], + ), + [ + { + kind: "handoff", + did, + cid: handoff.cid, + operation: JSON.stringify(handoff.operation), + kind_operation_cid: `handoff:${handoff.cid}`, + }, + ], + ); + assert.deepEqual( + await arrivals.recordSignedOperation(claim, version + 1, { + kind: "handoff", + operationId: "op-1", + did, + ...handoff, + }), + { kind: "already-settled", version: version + 1 }, + ); + assert.equal(await persistedVersion(db, "op-1"), version + 1); + assert.equal( + (await query(db, "SELECT cid FROM arrival_signed_operations")).length, + 1, + ); + } finally { + await db.close(); + } +}); + +test("a changed handoff CID or operation is a conflict and never overwrites the saved bytes", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const handoff = await signed(); + await arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + ...handoff, + }); + const other = await signed("a", { + alsoKnownAs: ["at://changed.entryway.test"], + }); + assert.notEqual(other.cid, handoff.cid); + for (const changed of [ + { ...handoff, cid: other.cid }, + { ...other, cid: handoff.cid }, + ]) + await assert.rejects( + arrivals.recordSignedOperation(claim, version + 1, { + kind: "handoff", + operationId: "op-1", + did, + ...changed, + }), + { code: "OperationConflict" }, + ); + assert.deepEqual( + await query( + db, + "SELECT cid, operation FROM arrival_signed_operations WHERE operation_id = ? AND kind = ?", + ["op-1", "handoff"], + ), + [{ cid: handoff.cid, operation: JSON.stringify(handoff.operation) }], + ); + assert.equal(await persistedVersion(db, "op-1"), version + 1); + } finally { + await db.close(); + } +}); + +test("a signed handoff journals its signed bytes and a CID over those bytes", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const handoff = await signed(); + const recorded = await arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + ...handoff, + }); + assert.deepEqual(recorded, { kind: "applied", version: version + 1 }); + const saved = await query( + db, + "SELECT cid, operation FROM arrival_signed_operations WHERE operation_id = ?", + ["op-1"], + ); + assert.equal(saved[0].cid, handoff.cid); + const journaled = JSON.parse(saved[0].operation); + assert.equal(journaled.sig, handoff.operation.sig); + // The stored CID covers the signed bytes, so it can equal a directory head. + assert.equal(saved[0].cid, String(await cidForCbor(journaled))); + } finally { + await db.close(); + } +}); + +test("a journaled operation without a signature is refused", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const { sig: _signature, ...facts } = (await signed()).operation; + await assert.rejects( + arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + operation: facts, + cid: String(await cidForCbor(facts)), + }), + { code: "InvalidAccount" }, + ); + assert.equal( + (await query(db, "SELECT cid FROM arrival_signed_operations")).length, + 0, + ); + assert.equal(await persistedVersion(db, "op-1"), version); + } finally { + await db.close(); + } +}); + +test("a signed operation whose CID covers only its unsigned facts is a conflict", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const { sig: _signature, ...facts } = (await signed()).operation; + await assert.rejects( + arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + operation: (await signed()).operation, + cid: String(await cidForCbor(facts)), + }), + { code: "OperationConflict" }, + ); + assert.equal( + (await query(db, "SELECT cid FROM arrival_signed_operations")).length, + 0, + ); + assert.equal(await persistedVersion(db, "op-1"), version); + } finally { + await db.close(); + } +}); + +test("a stale owner records no signed operation and leaves the arrival version unchanged", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + await query( + db, + "UPDATE authority_operations SET lease_expires_at = ? WHERE id = ?", + [Date.now() - 1_000, claim.operationId], + "run", + ); + await assert.rejects( + arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + ...(await signed()), + }), + { code: "OperationLeaseLost" }, + ); + assert.equal( + (await query(db, "SELECT cid FROM arrival_signed_operations")).length, + 0, + ); + assert.equal(await persistedVersion(db, "op-1"), version); + } finally { + await db.close(); + } +}); + +test("a destination move is refused before a handoff and accepted after it", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const move = await signed("b"); + await assert.rejects( + arrivals.recordSignedOperation(claim, version, { + kind: "destination-move", + operationId: "op-1", + did, + repositoryKey: reservedKey.did(), + ...move, + }), + { code: "OperationConflict" }, + ); + assert.equal( + (await query(db, "SELECT cid FROM arrival_signed_operations")).length, + 0, + ); + assert.equal(await persistedVersion(db, "op-1"), version); + + const handoff = await signed(); + const handedOff = await arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + ...handoff, + }); + assert.deepEqual(handedOff, { kind: "applied", version: version + 1 }); + const recorded = await arrivals.recordSignedOperation( + claim, + handedOff.version, + { + kind: "destination-move", + operationId: "op-1", + did, + repositoryKey: reservedKey.did(), + ...move, + }, + ); + assert.deepEqual(recorded, { kind: "applied", version: version + 2 }); + assert.deepEqual( + await query( + db, + "SELECT kind, cid FROM arrival_signed_operations WHERE operation_id = ? ORDER BY kind", + ["op-1"], + ), + [ + { kind: "destination-move", cid: move.cid }, + { kind: "handoff", cid: handoff.cid }, + ], + ); + } finally { + await db.close(); + } +}); + +test("signed operations must match their CID and carry no private material", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const handoff = await signed(); + await assert.rejects( + arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + operation: { + ...handoff.operation, + verificationMethods: { atproto: "did:key:zPrivateMaterial" }, + }, + cid: handoff.cid, + }), + { code: "InvalidAccount" }, + ); + const unsigned = { + ...handoff.operation, + verificationMethods: { atproto: "did:key:zQ3shnotavalidkey" }, + }; + await assert.rejects( + arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + operation: unsigned, + cid: String(await cidForCbor(unsigned)), + }), + { code: "InvalidAccount" }, + ); + assert.equal( + (await query(db, "SELECT cid FROM arrival_signed_operations")).length, + 0, + ); + assert.equal(await persistedVersion(db, "op-1"), version); + } finally { + await db.close(); + } +}); + +test("signed journal rejects privateKey on otherwise valid signed authority without writes", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const version = await allocate((await prepare()).version); + const handoff = await signed(); + await plc.assureValidSig([sourceKey.did()], handoff.operation); + const before = await claimSnapshot(db); + await assert.rejects( + arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + ...handoff, + operation: { + ...handoff.operation, + privateKey: "rejected-fixture-value", + }, + }), + { + code: "InvalidAccount", + message: "Signed public facts never carry private material", + }, + ); + assert.deepEqual(await claimSnapshot(db), before); + assert.equal(await persistedVersion(db, "op-1"), version); + assert.equal((await db.read("arrival_signed_operations")).length, 0); + assert.deepEqual( + await arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + ...handoff, + }), + { kind: "applied", version: version + 1 }, + ); + } finally { + await db.close(); + } +}); + +test("signed operation rows are immutable at the database boundary on both dialects", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const handoff = await signed(); + await arrivals.recordSignedOperation(claim, version, { + kind: "handoff", + operationId: "op-1", + did, + ...handoff, + }); + await assert.rejects( + query( + db, + "INSERT INTO arrival_signed_operations (operation_id, kind, did, cid, operation, kind_operation_cid, recorded_at) VALUES (?, 'handoff', ?, ?, ?, ?, ?)", + [ + "op-1", + did, + handoff.cid, + JSON.stringify(handoff.operation), + `handoff:${handoff.cid}`, + Date.now(), + ], + "run", + ), + hasFailure("arrival_signed_operations"), + ); + await assert.rejects( + query( + db, + "INSERT INTO arrival_signed_operations (operation_id, kind, did, cid, operation, kind_operation_cid, recorded_at) VALUES (?, 'move', ?, ?, ?, ?, ?)", + [ + "op-1", + did, + handoff.cid, + JSON.stringify(handoff.operation), + `move:${handoff.cid}`, + Date.now(), + ], + "run", + ), + hasFailure("arrival_signed_kind"), + ); + await assert.rejects( + query( + db, + "INSERT INTO arrival_signed_operations (operation_id, kind, did, cid, operation, kind_operation_cid, recorded_at) VALUES (?, 'handoff', ?, ?, ?, ?, ?)", + [ + "op-missing", + did, + handoff.cid, + JSON.stringify(handoff.operation), + `handoff:${handoff.cid}`, + Date.now(), + ], + "run", + ), + hasFailure("arrival_signed_operations"), + ); + } finally { + await db.close(); + } +}); + +const ordinaryAccount = { + did: otherDid, + email: "ordinary@example.test", + handle: "ordinary.entryway.test", + pdsId: "pds1", + pdsUrl: endpoint, + status: "active", +}; + +const claimSnapshot = async (db) => { + const result = {}; + for (const name of [ + "accounts", + "email_claims", + "handle_claims", + "account_bindings", + "arrivals", + "arrival_code", + "migration_reservations", + "arrival_signed_operations", + "arrival_reservations", + ]) + result[name] = await query(db, `SELECT * FROM ${name}`); + return result; +}; + +for (const kind of ["primary", "pending", "backup", "handle"]) + test(`active arrival DID blocks an alternate ${kind} claim without mutation`, async () => { + const { db, accounts, prepare, allocate, bind } = await fixture(); + try { + const prepared = await prepare(); + await bind(await allocate(prepared.version)); + for (const ownerUserId of [undefined, "user-a", "unrelated-owner"]) { + const before = await claimSnapshot(db); + await assert.rejects( + kind === "handle" + ? accounts.reserveHandle("alternate.entryway.test", did) + : accounts.reserveEmail( + "alternate@example.test", + did, + kind, + ownerUserId, + ), + { + code: kind === "handle" ? "HandleNotAvailable" : "IdentityConflict", + }, + ); + assert.deepEqual(await claimSnapshot(db), before); + } + } finally { + await db.close(); + } + }); + +for (const state of [ + "prepared", + "expired", + "allocated", + "uncertain", + "bound", + "cancelled", +]) + test(`ordinary writers respect ${state} arrival claims regardless of DID or owner`, async () => { + const { db, accounts, arrivals, claim, prepare, allocate, bind } = + await fixture(); + try { + await accounts.insertAccount(ordinaryAccount); + await browserSession( + db, + "owner-session", + "user-a", + Date.now(), + Date.now() + day, + ); + const prepared = await prepare(); + if (state === "expired") + await query( + db, + "UPDATE arrival_code SET issued_at = ?, expires_at = ?", + [Date.now() - day, Date.now() - 1], + "run", + ); + if (["allocated", "uncertain", "bound"].includes(state)) { + const version = await allocate(prepared.version); + if (state === "bound") await bind(version); + if (state === "uncertain") + await arrivals.retainUncertainAttempt(claim, version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + reason: "lost-response", + }); + } + if (state === "cancelled") + await arrivals.cancelArrival({ + owner: claim, + operationId: "op-1", + expectedVersion: prepared.version, + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }); + for (const writerDid of [did, otherDid]) { + for (const ownerUserId of [undefined, "user-a", "unrelated-owner"]) { + for (const purpose of ["primary", "pending", "backup"]) { + const before = await claimSnapshot(db); + if (state !== "cancelled") { + await assert.rejects( + accounts.reserveEmail( + " DEST@EXAMPLE.TEST ", + writerDid, + purpose, + ownerUserId, + ), + { + code: + writerDid === did + ? "IdentityConflict" + : "EmailNotAvailable", + }, + ); + assert.deepEqual(await claimSnapshot(db), before); + } + } + } + if (state !== "cancelled") { + const before = await claimSnapshot(db); + await assert.rejects( + accounts.reserveHandle(" DEST.ENTRYWAY.TEST ", writerDid), + { code: "HandleNotAvailable" }, + ); + assert.deepEqual(await claimSnapshot(db), before); + } + } + const writes = [ + () => + accounts.saveAccount({ + ...ordinaryAccount, + email: "dest@example.test", + }), + () => + accounts.saveAccount({ + ...ordinaryAccount, + handle: "dest.entryway.test", + }), + () => + accounts.insertAccount( + { + ...ordinaryAccount, + did: "did:plc:newaccount", + email: "dest@example.test", + handle: "new.entryway.test", + }, + "user-a", + ), + () => + accounts.reserveExternalMigration({ + workflowId: "competing", + did: "did:plc:migration", + handle: "migration.entryway.test", + userId: "user-a", + sessionId: "owner-session", + targetPdsId: "pds1", + targetPdsUrl: endpoint, + }), + ]; + if (state !== "cancelled") { + for (const write of writes) { + const before = await claimSnapshot(db); + await assert.rejects(write, (error) => + ["EmailNotAvailable", "HandleNotAvailable"].includes(error.code), + ); + assert.deepEqual(await claimSnapshot(db), before); + } + } else { + await accounts.reserveEmail( + "dest@example.test", + otherDid, + "pending", + "user-a", + ); + await accounts.reserveHandle("dest.entryway.test", otherDid); + } + } finally { + await db.close(); + } + }); + +for (const kind of [ + "primary", + "pending", + "backup", + "handle", + "account-email", + "account-handle", + "migration-email", + "migration-handle", + "migration-did", +]) + test(`arrival admission rejects an earlier ${kind} writer without mutation`, async () => { + const { db, accounts, prepare } = await fixture(); + try { + await accounts.insertAccount(ordinaryAccount); + if (["primary", "pending", "backup"].includes(kind)) + await accounts.reserveEmail("dest@example.test", otherDid, kind); + if (kind === "handle") + await accounts.reserveHandle("dest.entryway.test", otherDid); + if (kind === "account-email") { + await accounts.saveAccount({ + ...ordinaryAccount, + email: "dest@example.test", + }); + await accounts.reserveEmail("dest@example.test", otherDid, "primary"); + } + if (kind === "account-handle") + await accounts.saveAccount({ + ...ordinaryAccount, + handle: "dest.entryway.test", + }); + if (kind.startsWith("migration-")) { + const owner = kind === "migration-email" ? "user-a" : "migration-owner"; + if (owner !== "user-a") + await verifiedUser(db, owner, "migration@example.test"); + await browserSession( + db, + "migration-session", + owner, + Date.now(), + Date.now() + day, + ); + await accounts.reserveExternalMigration({ + workflowId: "earlier", + did: kind === "migration-did" ? did : "did:plc:earliermigration", + handle: + kind === "migration-handle" + ? "dest.entryway.test" + : "migration.entryway.test", + userId: owner, + sessionId: "migration-session", + targetPdsId: "pds1", + targetPdsUrl: endpoint, + }); + } + const before = await claimSnapshot(db); + await assert.rejects(prepare(), (error) => + [ + "EmailNotAvailable", + "HandleNotAvailable", + "IdentityConflict", + ].includes(error.code), + ); + assert.deepEqual(await claimSnapshot(db), before); + } finally { + await db.close(); + } + }); + +test("exact pending arrival binding restores all claims if the binding write fails", async () => { + const { db, accounts, prepare, allocate, bind } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const before = await claimSnapshot(db); + await failureTrigger( + db, + "reject_own_binding", + "account_bindings", + "binding failure", + ); + await assert.rejects(bind(version), hasFailure("binding failure")); + assert.deepEqual(await claimSnapshot(db), before); + await removeFailureTrigger(db, "reject_own_binding", "account_bindings"); + await bind(version); + assert.equal((await accounts.getVerifiedBinding(did)).userId, "user-a"); + } finally { + await db.close(); + } +}); + +test("a signed handoff without an allocation blocks cancellation despite caller booleans", async () => { + const { db, arrivals, claim, prepare } = await fixture(); + try { + const prepared = await prepare(); + const recorded = await arrivals.recordSignedOperation( + claim, + prepared.version, + { operationId: "op-1", did, kind: "handoff", ...(await signed()) }, + ); + assert.deepEqual(await query(db, "SELECT * FROM arrival_reservations"), []); + const before = await claimSnapshot(db); + await assert.rejects( + arrivals.cancelArrival({ + owner: claim, + operationId: "op-1", + expectedVersion: recorded.version, + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }), + { code: "OperationRecoveryRequired" }, + ); + assert.deepEqual(await claimSnapshot(db), before); + } finally { + await db.close(); + } +}); + +for (const kind of ["email", "handle", "migration-did"]) + for (const arrivalFirst of [true, false]) + test(`concurrent ${kind} writers preserve the first transaction (arrival first: ${arrivalFirst})`, async () => { + const { db, accounts, prepare } = await fixture(); + try { + await accounts.insertAccount(ordinaryAccount); + await verifiedUser(db, "migration-owner", "migration@example.test"); + await browserSession( + db, + "migration-session", + "migration-owner", + Date.now(), + Date.now() + day, + ); + const ordinary = () => + kind === "email" + ? accounts.reserveEmail("dest@example.test", otherDid, "backup") + : kind === "handle" + ? accounts.reserveHandle("dest.entryway.test", otherDid) + : accounts.reserveExternalMigration({ + workflowId: "racing", + did, + handle: "migration.entryway.test", + userId: "migration-owner", + sessionId: "migration-session", + targetPdsId: "pds1", + targetPdsUrl: endpoint, + }); + // Hold the shared transaction lock before starting the contender so both + // writer orders are deterministic rather than scheduler-dependent. + const entered = Promise.withResolvers(); + const release = Promise.withResolvers(); + const first = db.transact(async () => { + entered.resolve(); + await release.promise; + await (arrivalFirst ? prepare() : ordinary()); + }); + await entered.promise; + const second = arrivalFirst ? ordinary() : prepare(); + const outcomes = Promise.allSettled([first, second]); + release.resolve(); + const [winner, loser] = await outcomes; + assert.equal(winner.status, "fulfilled"); + assert.equal(loser.status, "rejected"); + assert.equal( + loser.reason.code, + kind === "email" + ? "EmailNotAvailable" + : kind === "handle" + ? "HandleNotAvailable" + : "IdentityConflict", + ); + assert.equal((await db.read("arrivals")).length, arrivalFirst ? 1 : 0); + } finally { + await db.close(); + } + }); + +for (const [label, change] of [ + [ + "actual repository key", + (operation) => ({ + ...operation, + verificationMethods: { atproto: sourceKey.did() }, + }), + ], + [ + "signed handoff predecessor", + (operation) => ({ ...operation, prev: sourcePlcHead }), + ], + [ + "destination endpoint", + (operation) => ({ + ...operation, + services: { + atproto_pds: { + type: "AtprotoPersonalDataServer", + endpoint: "https://other.example.test", + }, + }, + }), + ], + [ + "destination alias", + (operation) => ({ ...operation, alsoKnownAs: ["at://other.example.test"] }), + ], + [ + "ordered custody", + (operation) => ({ + ...operation, + rotationKeys: [...rotationKeys].reverse(), + }), + ], +]) { + test(`signed destination move rejects changed ${label} despite correct DTO and valid signature`, async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + await arrivals.recordSignedOperation(claim, version, { + operationId: "op-1", + did, + kind: "handoff", + ...(await signed()), + }); + const { sig: _signature, ...unsigned } = (await signed("b")).operation; + const operation = await plc.signOperation(change(unsigned), hotKey); + await assert.rejects( + arrivals.recordSignedOperation(claim, version + 1, { + operationId: "op-1", + did, + kind: "destination-move", + repositoryKey: reservedKey.did(), + operation, + cid: String(await cidForCbor(operation)), + }), + { code: "OperationConflict" }, + ); + assert.equal((await db.read("arrival_signed_operations")).length, 1); + assert.equal(await persistedVersion(db, "op-1"), version + 1); + } finally { + await db.close(); + } + }); +} + +test("legacy create predecessor persists exact signed encoding and original CID", async () => { + const { db, prepare } = await fixture(); + try { + const recovery = await Secp256k1Keypair.create(); + const legacy = await plc.deprecatedSignCreate( + { + type: "create", + signingKey: sourceKey.did(), + recoveryKey: recovery.did(), + handle: "dest.entryway.test", + service: endpoint, + prev: null, + }, + recovery, + ); + const normalized = plc.normalizeOp(legacy); + const originalCid = String(await cidForCbor(legacy)); + assert.notEqual(originalCid, String(await cidForCbor(normalized))); + const saved = await prepare({ + sourcePredecessor: legacy, + sourcePlcHead: originalCid, + source: { + services: normalized.services, + verificationMethods: normalized.verificationMethods, + alsoKnownAs: normalized.alsoKnownAs, + }, + approvedRotationKeys: [...normalized.rotationKeys, hotKey.did()], + }); + assert.deepEqual(saved.sourcePredecessor, legacy); + assert.equal(saved.sourcePlcHead, originalCid); + assert.equal( + (await query(db, "SELECT source_predecessor FROM arrivals"))[0] + .source_predecessor, + JSON.stringify(legacy), + ); + } finally { + await db.close(); + } +}); + +test("preparation rejects absent, fabricated and private-bearing authority without persisting it", async () => { + const { db, prepare } = await fixture(); + try { + for (const overrides of [ + { sourcePredecessor: undefined }, + { sourcePlcHead: head("a") }, + { source: { ...source, alsoKnownAs: ["at://changed.example.test"] } }, + { sourcePredecessor: { ...sourcePredecessor, privateKey: "not-a-key" } }, + ]) { + await assert.rejects(prepare(overrides), { code: "InvalidAccount" }); + assert.equal((await db.read("arrivals")).length, 0); + } + } finally { + await db.close(); + } +}); + +test("owner aggregate retains exact authority, signed journal, observation and external owner association", async () => { + const { db, arrivals, claim, prepare, allocate } = await fixture(); + try { + const prepared = await prepare(); + const version = await allocate(prepared.version); + const handoff = await signed(); + await arrivals.recordSignedOperation(claim, version, { + operationId: "op-1", + did, + kind: "handoff", + ...handoff, + }); + await arrivals.recordCanonicalHandoff(claim, version + 1, { + operationId: "op-1", + did, + cid: handoff.cid, + }); + await arrivals.retainUncertainAttempt(claim, version + 2, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + reason: "publication-unobserved", + }); + assert.equal( + await arrivals.readArrivalAggregate("op-1", "other-user"), + null, + ); + const aggregate = await arrivals.readArrivalAggregate("op-1", "user-a"); + assert.deepEqual(aggregate.arrival.sourcePredecessor, sourcePredecessor); + assert.deepEqual(aggregate.arrival.approvedRotationKeys, rotationKeys); + assert.deepEqual( + aggregate.signedOperations[0].operation, + handoff.operation, + ); + assert.equal(aggregate.progress.canonicalHandoffCid, handoff.cid); + assert.deepEqual(aggregate.attempts, [ + { + ownershipOperationId: claim.operationId, + attemptId: claim.attemptId, + fence: claim.fence, + reason: "publication-unobserved", + }, + ]); + const before = await persistedVersion(db, "op-1"); + await arrivals.recordCanonicalHandoff(claim, 1, { + operationId: "op-1", + did, + cid: handoff.cid, + }); + await assert.rejects( + arrivals.recordCanonicalHandoff({ ...claim, fence: claim.fence + 1 }, 1, { + operationId: "op-1", + did, + cid: handoff.cid, + }), + { code: "OperationLeaseLost" }, + ); + assert.equal(await persistedVersion(db, "op-1"), before); + } finally { + await db.close(); + } +}); + +test("signed journal and its version roll back under a later outer failure", async () => { + const { db, arrivals, claim, prepare } = await fixture(); + try { + await prepare(); + await assert.rejects( + db.transact(async () => { + await arrivals.recordSignedOperation(claim, 1, { + operationId: "op-1", + did, + kind: "handoff", + ...(await signed()), + }); + throw Error("InjectedJournalFailure"); + }), + /InjectedJournalFailure/, + ); + assert.equal((await db.read("arrival_signed_operations")).length, 0); + assert.equal(await persistedVersion(db, "op-1"), 1); + } finally { + await db.close(); + } +}); + +test("credential identity cannot authorize an unrelated operation and new admissions require current generation", async () => { + const { db, arrivals, claim, prepare } = await fixture(); + try { + await prepare(); + const facts = { + operationId: "op-1", + did, + method: "com.atproto.identity.submitPlcOperation", + requestDigest: hash("d"), + credentialIssuer: did, + credentialJti: "unique-source-jti", + }; + await arrivals.recordArrivalReplay(claim, 1, facts, { + codeHash: hash("a"), + codeGeneration: 1, + }); + await arrivals.rotateArrivalCode({ + operationId: "op-1", + ownerUserId: "user-a", + expectedVersion: 2, + codeHash: hash("b"), + codeExpiresAt: Date.now() + day, + }); + await assert.rejects( + arrivals.recordArrivalReplay( + claim, + 3, + { + ...facts, + method: "com.atproto.server.createAccount", + credentialJti: "new-jti", + }, + { codeHash: hash("a"), codeGeneration: 1 }, + ), + { code: "AccountMismatch" }, + ); + await verifiedUser(db, "user-b", "second@example.test"); + await prepare({ + operationId: "op-2", + did: otherDid, + userId: "user-b", + email: "second@example.test", + handle: "second.entryway.test", + codeHash: hash("c"), + }); + await assert.rejects( + arrivals.recordArrivalReplay( + claim, + 1, + { ...facts, operationId: "op-2", did: otherDid }, + { codeHash: hash("c"), codeGeneration: 1 }, + ), + { code: "OperationConflict" }, + ); + assert.equal((await db.read("arrival_replay")).length, 1); + assert.equal(await persistedVersion(db, "op-2"), 1); + } finally { + await db.close(); + } +}); + +// Exercise each storage mutation directly: execution ownership alone must not +// authorize another arrival, including paths that return a settled result. +for (const action of [ + "recordAllocationIntent", + "recordReservationResult", + "recordSignedOperation", + "recordCanonicalHandoff", + "retainUncertainAttempt", + "recordArrivalReplay", + "bindProvisionedArrival", + "completeArrivalActivation", + "cancelArrival", + "recordCredentialFamily", + "revokeArrivalCredentialFamilies", + "repeatPendingBinding", + "repeatSignedOperation", + "repeatCanonicalHandoff", + "repeatArrivalReplay", + "repeatCancellation", +]) { + for (const ownershipState of [ + "unrelated", + "forged-resource", + "additional-binding", + "stale", + "expired", + ]) { + test(`persisted arrival ownership: ${action} with ${ownershipState}`, async () => { + const f = await fixture(); + const { db, arrivals, claim } = f; + const ownership = createOperationOwnershipStore(db); + try { + await f.prepare(); + const tuple = { operationId: "op-1", did, pdsId: "pds1", endpoint }; + const handoff = { ...tuple, kind: "handoff", ...(await signed()) }; + const facts = { + operationId: "op-1", + did, + method: "com.atproto.identity.submitPlcOperation", + requestDigest: hash("d"), + credentialIssuer: did, + credentialJti: "ownership-regression-jti", + }; + const proof = { codeHash: hash("a"), codeGeneration: 1 }; + const cancellation = { + operationId: "op-1", + ownerUserId: "user-a", + noRemoteObligation: true, + plcStateUnchanged: true, + }; + let version = 1; + if ( + ["recordReservationResult", "retainUncertainAttempt"].includes(action) + ) + version = ( + await arrivals.recordAllocationIntent(claim, version, tuple) + ).version; + if ( + [ + "bindProvisionedArrival", + "repeatPendingBinding", + "completeArrivalActivation", + "recordCredentialFamily", + "revokeArrivalCredentialFamilies", + ].includes(action) + ) + version = await f.allocate(version); + if ( + [ + "repeatPendingBinding", + "completeArrivalActivation", + "recordCredentialFamily", + "revokeArrivalCredentialFamilies", + ].includes(action) + ) + version = (await f.bind(version)).version; + if (action === "revokeArrivalCredentialFamilies") + version = ( + await arrivals.recordCredentialFamily({ + owner: claim, + ...tuple, + expectedVersion: version, + familyId: "family-existing", + }) + ).version; + if ( + [ + "recordCanonicalHandoff", + "repeatSignedOperation", + "repeatCanonicalHandoff", + ].includes(action) + ) + version = ( + await arrivals.recordSignedOperation(claim, version, handoff) + ).version; + if (action === "repeatCanonicalHandoff") + version = ( + await arrivals.recordCanonicalHandoff(claim, version, handoff) + ).version; + if (action === "repeatArrivalReplay") { + await arrivals.recordArrivalReplay(claim, version, facts, proof); + version += 1; + } + if (action === "repeatCancellation") + version = ( + await arrivals.cancelArrival({ + owner: claim, + ...cancellation, + expectedVersion: version, + }) + ).version; + + let owner = claim; + if ( + ["unrelated", "forged-resource", "additional-binding"].includes( + ownershipState, + ) + ) { + if (ownershipState === "additional-binding") + await ownership.release(claim); + owner = await ownership.acquire({ + resource: `arrival:${otherDid}`, + kind: "public-arrival", + requestDigest: hash("e"), + workerId: "unrelated-worker", + leaseMs: 120_000, + }); + if (ownershipState === "forged-resource") + owner = { ...owner, resource: `arrival:${did}` }; + if (ownershipState === "additional-binding") { + await ownership.bindResource(owner, `arrival:${did}`); + assert.notEqual(owner.resource, `arrival:${did}`); + assert.notEqual(owner.operationId, tuple.operationId); + } + } + if (ownershipState === "stale") + owner = { ...claim, fence: claim.fence + 1 }; + if (ownershipState === "expired") + await query( + db, + "UPDATE authority_operations SET lease_expires_at = ? WHERE id = ?", + [Date.now() - 1_000, claim.operationId], + "run", + ); + const invoke = () => { + switch (action) { + case "recordAllocationIntent": + return arrivals.recordAllocationIntent(owner, version, tuple); + case "recordReservationResult": + return arrivals.recordReservationResult(owner, version, { + ...tuple, + signingKey: reservedKey.did(), + }); + case "recordSignedOperation": + case "repeatSignedOperation": + return arrivals.recordSignedOperation(owner, 1, handoff); + case "recordCanonicalHandoff": + return arrivals.recordCanonicalHandoff(owner, version, handoff); + case "repeatCanonicalHandoff": + return arrivals.recordCanonicalHandoff(owner, 1, handoff); + case "retainUncertainAttempt": + return arrivals.retainUncertainAttempt(owner, version, { + ...tuple, + reason: "lost-response", + }); + case "recordArrivalReplay": + case "repeatArrivalReplay": + return arrivals.recordArrivalReplay(owner, 1, facts, proof); + case "bindProvisionedArrival": + return f.bind(version, { owner }); + case "repeatPendingBinding": + return f.bind(version - 1, { owner }); + case "completeArrivalActivation": + return arrivals.completeArrivalActivation({ + owner, + ...tuple, + expectedVersion: version, + userId: "user-a", + activation: { + backendActiveObserved: true, + method: "com.atproto.server.activateAccount", + observedAt: Date.now(), + }, + }); + case "cancelArrival": + case "repeatCancellation": + return arrivals.cancelArrival({ + owner, + ...cancellation, + expectedVersion: version, + }); + case "recordCredentialFamily": + return arrivals.recordCredentialFamily({ + owner, + ...tuple, + expectedVersion: version, + familyId: "family-new", + }); + case "revokeArrivalCredentialFamilies": + return arrivals.revokeArrivalCredentialFamilies({ + owner, + operationId: tuple.operationId, + expectedVersion: version, + }); + default: + throw Error("UncoveredArrivalMutation"); + } + }; + const snapshot = async () => ({ + ...(await claimSnapshot(db)), + attempts: await db.read("arrival_attempts"), + families: await db.read("arrival_families"), + replay: await db.read("arrival_replay"), + operations: await db.read("authority_operations"), + admissions: await db.read("operation_admissions"), + }); + const before = await snapshot(); + if (ownershipState === "additional-binding") { + await invoke(); + assert.equal( + await persistedVersion(db, "op-1"), + version + (action.startsWith("repeat") ? 0 : 1), + ); + } else { + await assert.rejects(invoke(), { + code: ["stale", "expired"].includes(ownershipState) + ? "OperationLeaseLost" + : "OperationConflict", + }); + assert.deepEqual(await snapshot(), before); + } + } finally { + await db.close(); + } + }); + } +} + +test("generic arrival attempts settle only exact acknowledged receipts without allocation uncertainty", async () => { + const f = await fixture(); + const store = createOperationOwnershipStore(f.db); + try { + let version = await f.allocate((await f.prepare()).version); + const receipt = await store.beginExternal(f.claim, { + step: "incoming-creation", + target: endpoint, + method: "com.atproto.server.createAccount", + intentDigest: hash("e"), + }); + const input = { + operationId: "op-1", + did, + externalAttemptId: receipt.id, + step: "incoming-creation", + }; + version = ( + await f.arrivals.associateArrivalAttempt(f.claim, version, input) + ).version; + assert.equal( + (await f.arrivals.readArrivalAggregate("op-1", "user-a")).reservation + .uncertainReason, + null, + ); + await assert.rejects( + f.arrivals.settleArrivalAttempt(f.claim, version, input), + { code: "OperationRecoveryRequired" }, + ); + await assert.rejects(f.bind(version), { + code: "OperationRecoveryRequired", + }); + await assert.rejects( + f.arrivals.settleArrivalAttempt(f.claim, version, { + ...input, + externalAttemptId: "wrong", + }), + { code: "OperationConflict" }, + ); + await store.acknowledgeExternal(f.claim, receipt, null); + await assert.rejects( + f.arrivals.settleArrivalAttempt( + { ...f.claim, fence: f.claim.fence + 1 }, + version, + input, + ), + ); + version = (await f.arrivals.settleArrivalAttempt(f.claim, version, input)) + .version; + assert.equal( + (await f.arrivals.settleArrivalAttempt(f.claim, version, input)).kind, + "already-settled", + ); + const bound = await f.bind(version); + assert.equal((await f.bind(bound.version)).kind, "already-settled"); + } finally { + await f.db.close(); + } +}); + +test("completed generic receipt association never clears allocation uncertainty", async () => { + const f = await fixture(); + const store = createOperationOwnershipStore(f.db); + try { + let version = await f.allocate((await f.prepare()).version); + const receipt = await store.beginExternal(f.claim, { + step: "incoming-pause", + target: endpoint, + method: "com.atproto.admin.updateSubjectStatus", + intentDigest: hash("f"), + }); + await store.acknowledgeExternal(f.claim, receipt, null); + const input = { + operationId: "op-1", + did, + externalAttemptId: receipt.id, + step: "incoming-pause", + }; + // Completed receipts can be associated after dispatch, including recovery. + version = ( + await f.arrivals.associateArrivalAttempt(f.claim, version, input) + ).version; + await f.arrivals.retainUncertainAttempt(f.claim, version, { + operationId: "op-1", + did, + pdsId: "pds1", + endpoint, + reason: "allocation-result-lost", + }); + version = (await f.arrivals.readArrival("op-1", "user-a")).version; + version = (await f.arrivals.settleArrivalAttempt(f.claim, version, input)) + .version; + assert.equal( + (await f.arrivals.readArrivalAggregate("op-1", "user-a")).reservation + .uncertainReason, + "allocation-result-lost", + ); + await assert.rejects(f.bind(version), { + code: "OperationRecoveryRequired", + }); + } finally { + await f.db.close(); + } +}); diff --git a/tests/contracts/plc-policy.test.mjs b/tests/contracts/plc-policy.test.mjs index 73ab8f8f..5b081bd2 100644 --- a/tests/contracts/plc-policy.test.mjs +++ b/tests/contracts/plc-policy.test.mjs @@ -4,6 +4,7 @@ import { Secp256k1Keypair, P256Keypair } from "@atproto/crypto"; import * as plc from "@did-plc/lib"; import { genesisRotationKeys, + incomingRotationKeys, publicUpdateCandidate, } from "../../dist/src/plc/policy.js"; @@ -34,6 +35,27 @@ test("genesis keeps recovery priority and rejects repeated or private references { code: "InvalidPlcOperation" }, ); }); +test("incoming authority preserves priority, rejects invalid/full lists and never truncates", async () => { + const { hot, offline } = await fixture(); + const source = await Secp256k1Keypair.create(); + assert.deepEqual( + incomingRotationKeys([offline.did(), source.did()], hot.did()), + [offline.did(), source.did(), hot.did()], + ); + assert.deepEqual( + incomingRotationKeys([hot.did(), offline.did()], hot.did()), + [hot.did(), offline.did()], + ); + const full = [offline.did(), source.did()]; + for (let index = 0; index < 3; index++) + full.push((await Secp256k1Keypair.create()).did()); + for (const keys of [full, ["private"], [source.did(), source.did()]]) { + assert.throws(() => incomingRotationKeys(keys, hot.did()), { + code: "InvalidPlcOperation", + }); + } +}); + test("updates preserve omission and pinned duplicate behavior, enforce bounds and policy", async () => { const { hot, op } = await fixture(); assert.deepEqual( diff --git a/tests/support/run-database-contracts.mjs b/tests/support/run-database-contracts.mjs index 863667cf..fd9bdb15 100644 --- a/tests/support/run-database-contracts.mjs +++ b/tests/support/run-database-contracts.mjs @@ -35,6 +35,7 @@ const files = [ "external-workflow", "migration-boundary", "migration-custody", + "incoming-arrival-storage", ].map((name) => `tests/contracts/${name}.test.mjs`); files.push( "src/features/email-login/routes.test.mjs",