diff --git a/README.md b/README.md index c3bddbe..8dab929 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,27 @@ One honest admission, stated rather than buried: an account recoverable by emailed code is exactly as secure as the mailbox behind it. Every consumer service works this way; almost none say it. We say it. +## Passkey lifecycle settings + +Identity keeps passkey enrollment and removal bounded in storage. The default +settings allow 10 active or in-flight credentials and 20 retained credential +records per principal. Completed registration proofs become eligible for +collection after 24 hours; proofs and capacity reservations for registrations +that did not complete are collected after the same grace period once no +credential record references them. Revoked credential records remain for 30 +days before collection. Hosts may set the active limit from 1 to 64 and the +retained limit from the active limit through 128. Proof and revoked-record +retention accept positive millisecond values up to 30 and 365 days, +respectively. Configure them with `passkeyMaxActiveCredentials`, +`passkeyMaxRetainedCredentials`, `passkeyRegistrationProofRetentionMs`, and +`passkeyTombstoneRetentionMs`. + +Run `sweepPasskeys()` to collect eligible registration proofs, expired +revoked records, and abandoned reservations. Persist and pass its cursor until +`hasMore` is false, as with `sweepChallenges()`. A `limit_exceeded` +`IdentityError` is returned when a principal has reached a configured +credential limit. + ## Development ```sh diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 8a796c0..38042cc 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -22,7 +22,7 @@ The protected assets are: Mailbox control is the account-recovery security floor. The component cannot make a compromised mailbox safe; hosts must communicate that limit and should -encourage passkey enrollment. `@pegma/mail@0.1.0` provides durable +encourage passkey enrollment. `@pegma/mail@0.1.1` provides durable at-least-once delivery state while the provider remains host-owned. ## Threat Model, Trust Boundaries, and Assumptions @@ -81,11 +81,24 @@ Security invariants: scoped to configured RP IDs and origins, and support multiple credentials per principal. Every credential-index trust boundary recomputes `principalHash` from `principalId` before verification, mutation, repair, or - claims issuance. A reserved generation can create its passkey mirror only - from an exact, content-addressed immutable registration proof stored before - the reservation; an active generation must cross-check the independently - stored passkey mirror's owner, credential identity, generation, public key, - transports, label, creation time, and counter. + claims issuance. A per-principal storage record reserves capacity before an + immutable registration proof is stored, and the credential index can enter + `reserved` only with that exact content-addressed proof. An active generation + must cross-check the independently stored passkey mirror's owner, credential + identity, generation, public key, transports, label, creation time, and + counter. +- Per-principal passkey capacity is serialized through that storage record. + Active and in-flight credentials count toward a configurable limit (10 by + default), while active and revoked credential records count toward a second + configurable limit (20 by default). Both bounds are re-evaluated inside the + optimistic update that reserves capacity, so concurrent registrations cannot + exceed them. +- Registration proofs carry a configurable collection deadline (24 hours by + default). Maintenance retains a proof while its exact reserved generation + still needs repair; after the deadline it may collect proofs for completed + generations or registrations that did not obtain a credential reservation. + Reserved capacity is released only after neither credential record references + that generation. - Authenticator attestation is deliberately not verified. Registration uses `attestationType: "none"`, so no authenticator-model or AAGUID policy is expressed and software passkeys are accepted. This is the correct default @@ -106,6 +119,15 @@ Security invariants: which repair finalizes the index. A crash on either side of the mirror write is replayable without weakening owner, generation, or counter-regression checks. +- Passkey removal returns success only after the exact credential generation is + `revoked` in both the credential index and principal mirror. If an assertion + has placed the index in `counter-pending`, removal completes that repair and + retries the revocation in a bounded loop; retry exhaustion is a conflict, not + a successful result. +- Revoked credential-index and mirror records share a configurable retention + fence (30 days by default). Maintenance uses version-conditional deletion and + removes the per-principal retained slot only after the generation is no + longer present. Active and in-flight generations are not compacted. - Raw token-shaped values, one-time codes, and challenge verification material never enter storage, logs, or error messages. - Eight-digit codes are deterministically derived with unbiased rejection @@ -161,7 +183,8 @@ Cross-collection crashes are expected, so intermediate states are durable and repairable rather than treated as exceptional. WebAuthn option generation can be abused for storage exhaustion. Challenge -TTLs, maximum attempts, bounded identifiers and labels, authoritative +TTLs, maximum attempts, bounded identifiers and labels, per-principal active +and retained-credential limits, proof and tombstone retention, authoritative adapter-bounded scan pages, and host endpoint rate limiting constrain the budget. Sweep decodes each physical row independently, so a malformed row is retained for investigation without preventing the continuation from reaching @@ -184,8 +207,11 @@ Challenge handles and authenticator responses can be replayed or raced. The handle is random and only its domain-separated hash is stored. A verification attempt atomically claims a pending record; success consumes it, while failure increments a bounded attempt count. Concurrent submissions cannot both claim -the same challenge. Expired and terminal records are retained until a -version-conditional sweep, so a stale listing cannot delete replacement +the same challenge. Once registration has durably activated its credential, +that durable result remains successful if the final challenge-state write is +temporarily unavailable: the existing `verifying` claim remains single-flight +and is collected after expiry. Expired and terminal records are retained until +a version-conditional sweep, so a stale listing cannot delete replacement state. Storage poisoning can target codecs, sweep key reconstruction, or state diff --git a/packages/identity/README.md b/packages/identity/README.md index cac3acd..531884b 100644 --- a/packages/identity/README.md +++ b/packages/identity/README.md @@ -71,6 +71,11 @@ const identity = createIdentity({ emailCodeProtector: createHmacEmailCodeProtector(emailCodeSecret), emailCodeRequestLimiter, emailCodeVerificationLimiter, + // Defaults shown explicitly; choose lower host-specific bounds if needed. + passkeyMaxActiveCredentials: 10, + passkeyMaxRetainedCredentials: 20, + passkeyRegistrationProofRetentionMs: 24 * 60 * 60_000, + passkeyTombstoneRetentionMs: 30 * 24 * 60 * 60_000, }); ``` @@ -155,8 +160,9 @@ await worker.runReconciliationPage({ limit: 100 }); Authenticate and deduplicate provider callbacks before passing them to `applyAuthenticatedMailCallback`. Schedule `sweepEmailOperations`, -`sweepMail`, both Mail worker cursor cycles, `sweepChallenges`, and the two -durable limiter sweeps independently. Persist every non-null opaque cursor. +`sweepMail`, both Mail worker cursor cycles, `sweepChallenges`, +`sweepPasskeys`, and the two durable limiter sweeps independently. Persist +every non-null opaque cursor. Dead-letter and terminal-unknown mail stays operator-visible until explicitly acknowledged. Provider, renderer, and reconciliation calls must enforce finite timeouts shorter than the Mail lease. @@ -233,6 +239,21 @@ The host must authenticate passkey list/add/remove endpoints for the named principal. Removing the last passkey is allowed because the durable email-code recovery floor is available. +Active and in-flight registrations share the configured per-principal active +credential limit. Active and revoked records share the retained-credential +limit. Enrollment returns `IdentityError` with code `limit_exceeded` when the +relevant limit has been reached. Limits and retention settings must be +positive integers within their documented type-level option bounds; the +retained limit must be at least the active limit. + +Run `sweepPasskeys(limit, cursor)` periodically using the same cursor loop +shown below for challenges. It collects completed or unreferenced registration +proofs after their grace period, removes revoked credential records after +their retention fence, and releases expired registration reservations only +when no credential record still references their generation. Passkey removal +returns `true` only after the credential index and principal mirror both store +the revoked generation. + Run `sweepChallenges(limit, cursor)` periodically. Each call scans and inspects at most `limit` physical challenge rows, retains malformed rows for investigation, and deletes expired or terminal rows by their adapter-issued diff --git a/packages/identity/src/errors.ts b/packages/identity/src/errors.ts index 6b634c2..d52330e 100644 --- a/packages/identity/src/errors.ts +++ b/packages/identity/src/errors.ts @@ -3,6 +3,7 @@ export type IdentityErrorCode = | "conflict" | "not_found" | "invalid_state" + | "limit_exceeded" | "rate_limited" | "verification_failed" | "storage_corrupt"; diff --git a/packages/identity/src/index.ts b/packages/identity/src/index.ts index 9584d0c..2c82f73 100644 --- a/packages/identity/src/index.ts +++ b/packages/identity/src/index.ts @@ -23,6 +23,7 @@ import { type FinishAuthenticationInput, type FinishRegistrationInput, type Passkey, + type PasskeySweepResult, type RegistrationStart, } from "./passkeys.js"; import { @@ -68,6 +69,14 @@ export interface IdentityOptions { readonly emailCodeTtlMs?: number; readonly emailCodeMaxAttempts?: number; readonly emailOperationRetentionMs?: number; + /** Maximum active or in-flight passkeys per principal. Default 10; range 1..64. */ + readonly passkeyMaxActiveCredentials?: number; + /** Maximum active and revoked records per principal. Default 20; range 1..128 and not below the active limit. */ + readonly passkeyMaxRetainedCredentials?: number; + /** Proof collection grace in milliseconds. Default 24 hours; maximum 30 days. */ + readonly passkeyRegistrationProofRetentionMs?: number; + /** Revoked-record retention in milliseconds. Default 30 days; maximum 365 days. */ + readonly passkeyTombstoneRetentionMs?: number; } export interface Identity { @@ -97,6 +106,7 @@ export interface Identity { limit?: number, cursor?: string, ): Promise; + sweepPasskeys(limit?: number, cursor?: string): Promise; beginAccountCreation( email: string, rateLimitKey: string, @@ -171,6 +181,10 @@ const IDENTITY_OPTION_KEYS = new Set([ "emailCodeTtlMs", "emailCodeMaxAttempts", "emailOperationRetentionMs", + "passkeyMaxActiveCredentials", + "passkeyMaxRetainedCredentials", + "passkeyRegistrationProofRetentionMs", + "passkeyTombstoneRetentionMs", ]); function snapshotOptions(value: unknown): Record { @@ -326,6 +340,36 @@ export function createIdentity(options: IdentityOptions): Identity { 90 * 24 * 60 * 60_000, "Email operation retention", ); + const passkeyMaxActiveCredentials = positiveBoundedInteger( + safe.passkeyMaxActiveCredentials as number | undefined, + 10, + 64, + "Active passkey limit", + ); + const passkeyMaxRetainedCredentials = positiveBoundedInteger( + safe.passkeyMaxRetainedCredentials as number | undefined, + 20, + 128, + "Retained passkey limit", + ); + if (passkeyMaxRetainedCredentials < passkeyMaxActiveCredentials) { + throw new IdentityError( + "invalid_input", + "Retained passkey limit is invalid.", + ); + } + const passkeyRegistrationProofRetentionMs = positiveBoundedInteger( + safe.passkeyRegistrationProofRetentionMs as number | undefined, + 24 * 60 * 60_000, + 30 * 24 * 60 * 60_000, + "Passkey registration proof retention", + ); + const passkeyTombstoneRetentionMs = positiveBoundedInteger( + safe.passkeyTombstoneRetentionMs as number | undefined, + 30 * 24 * 60 * 60_000, + 365 * 24 * 60 * 60_000, + "Passkey tombstone retention", + ); if ( !hasDataMethods(safe.emailCodeProtector, [ "deriveCode", @@ -365,6 +409,10 @@ export function createIdentity(options: IdentityOptions): Identity { challengeService: challenges, users, newId, + maxActiveCredentials: passkeyMaxActiveCredentials, + maxRetainedCredentials: passkeyMaxRetainedCredentials, + registrationProofRetentionMs: passkeyRegistrationProofRetentionMs, + tombstoneRetentionMs: passkeyTombstoneRetentionMs, }); const emailCodes = createEmailCodeService({ store: safe.store as Store, @@ -399,6 +447,7 @@ export function createIdentity(options: IdentityOptions): Identity { removePasskey: passkeys.removePasskey, repairPasskey: passkeys.repairPasskey, sweepChallenges: challenges.sweep, + sweepPasskeys: passkeys.sweep, beginAccountCreation: emailCodes.beginAccountCreation, finishAccountCreation: emailCodes.finishAccountCreation, beginEmailSignIn: emailCodes.beginEmailSignIn, @@ -425,6 +474,7 @@ export type { FinishRegistrationInput, IdentityErrorCode, Passkey, + PasskeySweepResult, ProvisionVerifiedUserInput, RegistrationStart, User, diff --git a/packages/identity/src/passkeys.test.ts b/packages/identity/src/passkeys.test.ts index 5347bf4..b7c1ec1 100644 --- a/packages/identity/src/passkeys.test.ts +++ b/packages/identity/src/passkeys.test.ts @@ -48,6 +48,7 @@ vi.mock("@simplewebauthn/server", () => ({ }; }, async verifyRegistrationResponse(options: { + response: { id: string }; expectedChallenge: string | ((candidate: string) => boolean | Promise); }) { @@ -64,7 +65,7 @@ vi.mock("@simplewebauthn/server", () => ({ registrationInfo: { userVerified: true, credential: { - id: ceremony.credentialId, + id: options.response.id, publicKey: new Uint8Array([1, 2, 3, 4]), counter: ceremony.registrationCounter, transports: ["internal"], @@ -114,8 +115,9 @@ import { validCounterTransition } from "./passkeys.js"; import { challengesCollection, credentialIndexesCollection, + passkeyPrincipalsCollection, passkeysCollection, - type CredentialIndexRecord, + registrationProofsCollection, } from "./records.js"; import { TABLE_PORT } from "../../../test/azurite.js"; @@ -221,10 +223,10 @@ function observeStore(inner: Store) { }; } -function registrationResponse() { +function registrationResponse(credentialId = ceremony.credentialId) { return { - id: ceremony.credentialId, - rawId: ceremony.credentialId, + id: credentialId, + rawId: credentialId, type: "public-key" as const, clientExtensionResults: {}, response: { @@ -256,6 +258,10 @@ function service( readonly clock?: Clock; readonly newId?: () => string; readonly authenticationLimiter?: RateLimiter; + readonly passkeyMaxActiveCredentials?: number; + readonly passkeyMaxRetainedCredentials?: number; + readonly passkeyRegistrationProofRetentionMs?: number; + readonly passkeyTombstoneRetentionMs?: number; } = {}, ) { return createIdentity({ @@ -273,6 +279,27 @@ function service( emailCodeVerificationLimiter: durableAllow, newId: options.newId ?? (() => randomUUID()), ...(options.clock === undefined ? {} : { clock: options.clock }), + ...(options.passkeyMaxActiveCredentials === undefined + ? {} + : { + passkeyMaxActiveCredentials: options.passkeyMaxActiveCredentials, + }), + ...(options.passkeyMaxRetainedCredentials === undefined + ? {} + : { + passkeyMaxRetainedCredentials: options.passkeyMaxRetainedCredentials, + }), + ...(options.passkeyRegistrationProofRetentionMs === undefined + ? {} + : { + passkeyRegistrationProofRetentionMs: + options.passkeyRegistrationProofRetentionMs, + }), + ...(options.passkeyTombstoneRetentionMs === undefined + ? {} + : { + passkeyTombstoneRetentionMs: options.passkeyTombstoneRetentionMs, + }), }); } @@ -285,6 +312,34 @@ async function provision(identity: ReturnType) { return principalId; } +async function sweepPasskeysCompletely( + identity: ReturnType, + limit = 100, +) { + let cursor: string | undefined; + let deletedProofs = 0; + let deletedTombstones = 0; + let releasedReservations = 0; + let rejected = 0; + for (let pass = 0; pass < 20; pass += 1) { + const result = await identity.sweepPasskeys(limit, cursor); + deletedProofs += result.deletedProofs; + deletedTombstones += result.deletedTombstones; + releasedReservations += result.releasedReservations; + rejected += result.rejected; + if (!result.hasMore) { + return { + deletedProofs, + deletedTombstones, + releasedReservations, + rejected, + }; + } + cursor = result.cursor ?? undefined; + } + throw new Error("passkey maintenance did not complete"); +} + beforeEach(() => { ceremony.registrationChallenge = "registration_challenge"; ceremony.authenticationChallenge = "authentication_challenge"; @@ -365,6 +420,97 @@ describe("passkey ceremonies", () => { expect(Object.isFrozen(claims)).toBe(true); }); + it.each([ + ["memory store", createMemoryStore], + ["Azurite", createAzuriteStore], + ] as const)( + "returns a durable registration when final challenge cleanup is interrupted over %s", + async (_name, makeStore) => { + const inner = makeStore(); + let now = "2026-01-01T00:00:00.000Z"; + let interruptConsumption = true; + const wrapped: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const collection = inner.collection(definition); + if (definition.name !== challengesCollection.name) { + return collection; + } + return { + ...collection, + async update(key, decide, updateOptions) { + const interruptingDecide: typeof decide = async (current) => { + const decision = await decide(current); + if ( + interruptConsumption && + decision.action === "write" && + (decision.value as { state?: unknown }).state === "consumed" + ) { + interruptConsumption = false; + throw new Error("simulated challenge cleanup interruption"); + } + return decision; + }; + return updateOptions === undefined + ? collection.update(key, interruptingDecide) + : collection.update(key, interruptingDecide, updateOptions); + }, + }; + }, + }; + const identity = service(wrapped, { clock: { now: () => now } }); + const principalId = await provision(identity); + const registration = await identity.beginPasskeyRegistration( + principalId, + "request-registration", + ); + + await expect( + identity.finishPasskeyRegistration({ + principalId, + challengeHandle: registration.challengeHandle, + label: "Security key", + response: registrationResponse(), + }), + ).resolves.toMatchObject({ + credentialId: ceremony.credentialId, + label: "Security key", + }); + expect(interruptConsumption).toBe(false); + + const challengeDigest = await challengeHandleHash( + registration.challengeHandle, + ); + const challengeKey = { + partition: "challenges", + id: challengeDigest, + }; + const retained = await inner + .collection(challengesCollection) + .get(challengeKey); + expect(retained).toMatchObject({ state: "verifying" }); + await expect( + identity.finishPasskeyRegistration({ + principalId, + challengeHandle: registration.challengeHandle, + label: "Repeated key", + response: registrationResponse(), + }), + ).rejects.toMatchObject({ code: "verification_failed" }); + await expect(identity.listPasskeys(principalId)).resolves.toHaveLength(1); + + if (retained === null) { + throw new Error("expected a retained challenge"); + } + now = new Date(Date.parse(retained.expiresAt) + 1).toISOString(); + await expect(identity.sweepChallenges(100)).resolves.toMatchObject({ + deleted: 1, + }); + await expect( + inner.collection(challengesCollection).get(challengeKey), + ).resolves.toBeNull(); + }, + ); + it.each([ ["memory store", createMemoryStore], ["Azurite", createAzuriteStore], @@ -1072,54 +1218,12 @@ describe("passkey ceremonies", () => { "lets only one concurrent re-registration own a revoked credential over %s", async (_name, makeStore) => { const inner = makeStore(); - let armed = false; - let arrivals = 0; - let release!: () => void; - const gate = new Promise((resolve) => { - release = resolve; - }); - const racing: Store = { - collection(definition: CollectionDefinition): CollectionStore { - const collection = inner.collection(definition); - if (definition.name !== "pegma_identity_credential_indexes") { - return collection; - } - return { - ...collection, - async update(key, decide, updateOptions) { - const wrapped = async (current: T | null) => { - const decision = await decide(current); - const index = current as CredentialIndexRecord | null; - const proposed = - decision.action === "write" - ? (decision.value as CredentialIndexRecord) - : null; - if ( - armed && - index?.state === "revoked" && - proposed?.state === "reserved" - ) { - arrivals += 1; - if (arrivals === 2) { - release(); - } - await gate; - } - return decision; - }; - return updateOptions === undefined - ? collection.update(key, wrapped) - : collection.update(key, wrapped, updateOptions); - }, - }; - }, - }; let firstId = 0; let secondId = 0; - const first = service(racing, { + const first = service(inner, { newId: () => `first_${(firstId += 1)}`, }); - const second = service(racing, { + const second = service(inner, { newId: () => `second_${(secondId += 1)}`, }); const principalId = await provision(first); @@ -1139,7 +1243,6 @@ describe("passkey ceremonies", () => { first.beginPasskeyRegistration(principalId, "first-race"), second.beginPasskeyRegistration(principalId, "second-race"), ]); - armed = true; const settled = await Promise.allSettled([ first.finishPasskeyRegistration({ principalId, @@ -1189,6 +1292,689 @@ describe("passkey ceremonies", () => { ); }); +describe("passkey lifecycle bounds", () => { + it("rejects passkey limits and retention settings outside their bounds", () => { + const cases = [ + { passkeyMaxActiveCredentials: 0 }, + { passkeyMaxActiveCredentials: 1.5 }, + { passkeyMaxActiveCredentials: Number.POSITIVE_INFINITY }, + { passkeyMaxActiveCredentials: 65 }, + { passkeyMaxRetainedCredentials: 0 }, + { passkeyMaxRetainedCredentials: 129 }, + { + passkeyMaxActiveCredentials: 2, + passkeyMaxRetainedCredentials: 1, + }, + { passkeyRegistrationProofRetentionMs: 0 }, + { passkeyRegistrationProofRetentionMs: 30 * 24 * 60 * 60_000 + 1 }, + { passkeyTombstoneRetentionMs: 0 }, + { passkeyTombstoneRetentionMs: 365 * 24 * 60 * 60_000 + 1 }, + ]; + for (const options of cases) { + expect(() => service(createMemoryStore(), options)).toThrow( + IdentityError, + ); + } + }); + + it.each([ + ["memory store", createMemoryStore], + ["Azurite", createAzuriteStore], + ] as const)( + "retains malformed maintenance rows and continues each scan over %s", + async (_name, makeStore) => { + const inner = makeStore(); + let now = "2026-08-31T12:00:00.000Z"; + const identity = service(inner, { + clock: { now: () => now }, + passkeyRegistrationProofRetentionMs: 1_000, + passkeyTombstoneRetentionMs: 1_000, + }); + const principalId = await provision(identity); + const registration = await identity.beginPasskeyRegistration( + principalId, + "maintenance-registration", + ); + await identity.finishPasskeyRegistration({ + principalId, + challengeHandle: registration.challengeHandle, + label: "Maintenance key", + response: registrationResponse("maintenance_credential"), + }); + await identity.removePasskey(principalId, "maintenance_credential"); + + const malformedId = "0".repeat(64); + for (const [name, partition] of [ + [ + registrationProofsCollection.name, + `registration-${malformedId.slice(0, 16)}`, + ], + [ + credentialIndexesCollection.name, + `credential-${malformedId.slice(0, 16)}`, + ], + [passkeysCollection.name, `passkeys-${malformedId.slice(0, 32)}`], + [ + passkeyPrincipalsCollection.name, + `passkeys-${malformedId.slice(0, 32)}`, + ], + ] as const) { + const raw = defineCollection({ + name, + key: (record) => ({ + partition: String(record.partition), + id: String(record.id), + }), + codec: { + encode: (record) => record, + decode: (record) => record, + }, + }); + await inner.collection(raw).put({ + partition, + id: malformedId, + malformed: true, + }); + } + + now = "2026-08-31T12:00:02.000Z"; + await expect(sweepPasskeysCompletely(identity, 1)).resolves.toEqual({ + deletedProofs: 1, + deletedTombstones: 1, + releasedReservations: 0, + rejected: 4, + }); + }, + ); + + it.each([ + ["memory store", createMemoryStore], + ["Azurite", createAzuriteStore], + ] as const)( + "reconciles a stale reservation with the committed credential generation over %s", + async (_name, makeStore) => { + const inner = makeStore(); + const identity = service(inner, { + passkeyMaxActiveCredentials: 2, + passkeyMaxRetainedCredentials: 2, + }); + const principalId = await provision(identity); + const registration = await identity.beginPasskeyRegistration( + principalId, + "initial-registration", + ); + await identity.finishPasskeyRegistration({ + principalId, + challengeHandle: registration.challengeHandle, + label: "Initial key", + response: registrationResponse("reconciled_credential"), + }); + const principalDigest = await principalHash(principalId); + const credentialDigest = await credentialHash("reconciled_credential"); + const principalKey = { + partition: `passkeys-${principalDigest.slice(0, 32)}`, + id: principalDigest, + }; + const principalRecords = inner.collection(passkeyPrincipalsCollection); + const state = await principalRecords.get(principalKey); + const mirror = await inner.collection(passkeysCollection).get({ + partition: principalKey.partition, + id: credentialDigest, + }); + if (state === null || mirror === null) { + throw new Error("expected passkey state"); + } + await principalRecords.put({ + ...state, + slots: [ + { + ...state.slots[0]!, + registrationId: "stale_generation", + state: "reserved", + expiresAt: "2027-09-30T12:00:00.000Z", + }, + ], + }); + + await expect( + identity.beginPasskeyRegistration(principalId, "after-reconcile"), + ).resolves.toMatchObject({ challengeHandle: expect.any(String) }); + await expect(principalRecords.get(principalKey)).resolves.toMatchObject({ + slots: [ + { + registrationId: mirror.registrationId, + state: "active", + expiresAt: null, + }, + ], + }); + }, + ); + + it.each([ + ["memory store", createMemoryStore], + ["Azurite", createAzuriteStore], + ] as const)( + "removes an active credential whose stored records predate retention fields over %s", + async (_name, makeStore) => { + const inner = makeStore(); + const identity = service(inner); + const principalId = await provision(identity); + const registration = await identity.beginPasskeyRegistration( + principalId, + "legacy-record", + ); + await identity.finishPasskeyRegistration({ + principalId, + challengeHandle: registration.challengeHandle, + label: "Legacy key", + response: registrationResponse("legacy_credential"), + }); + const credentialDigest = await credentialHash("legacy_credential"); + const principalDigest = await principalHash(principalId); + for (const [definition, key] of [ + [ + credentialIndexesCollection, + { + partition: `credential-${credentialDigest.slice(0, 16)}`, + id: credentialDigest, + }, + ], + [ + passkeysCollection, + { + partition: `passkeys-${principalDigest.slice(0, 32)}`, + id: credentialDigest, + }, + ], + ] as const) { + const raw = defineCollection({ + name: definition.name, + key: (record) => ({ + partition: String(record.partition), + id: String(record.id), + }), + codec: { + encode: (record) => record, + decode: (record) => record, + }, + }); + const collection = inner.collection(raw); + const stored = await collection.get(key); + if (stored === null) { + throw new Error("expected stored credential record"); + } + const { retireAt: _retireAt, ...legacy } = stored; + await collection.put(legacy); + } + + await expect( + identity.removePasskey(principalId, "legacy_credential"), + ).resolves.toBe(true); + }, + ); + + it.each([ + ["memory store with a mirror", createMemoryStore, true], + ["memory store without a mirror", createMemoryStore, false], + ["Azurite with a mirror", createAzuriteStore, true], + ["Azurite without a mirror", createAzuriteStore, false], + ] as const)( + "repairs a revoked credential whose stored records predate retention fields over %s", + async (_name, makeStore, keepMirror) => { + const inner = makeStore(); + const identity = service(inner); + const principalId = await provision(identity); + const registration = await identity.beginPasskeyRegistration( + principalId, + "legacy-revoked-record", + ); + await identity.finishPasskeyRegistration({ + principalId, + challengeHandle: registration.challengeHandle, + label: "Retired key", + response: registrationResponse("legacy_revoked_credential"), + }); + await identity.removePasskey(principalId, "legacy_revoked_credential"); + + const credentialDigest = await credentialHash( + "legacy_revoked_credential", + ); + const principalDigest = await principalHash(principalId); + const indexKey = { + partition: `credential-${credentialDigest.slice(0, 16)}`, + id: credentialDigest, + }; + const mirrorKey = { + partition: `passkeys-${principalDigest.slice(0, 32)}`, + id: credentialDigest, + }; + const principalKey = { + partition: mirrorKey.partition, + id: principalDigest, + }; + const raw = (name: string) => + inner.collection( + defineCollection({ + name, + key: (record) => ({ + partition: String(record.partition), + id: String(record.id), + }), + codec: { + encode: (record) => record, + decode: (record) => record, + }, + }), + ); + for (const [name, key] of [ + [credentialIndexesCollection.name, indexKey], + [passkeysCollection.name, mirrorKey], + ] as const) { + const collection = raw(name); + const stored = await collection.get(key); + if (stored === null) { + throw new Error("expected stored revoked credential record"); + } + const { retireAt: _retireAt, ...legacy } = stored; + await collection.put(legacy); + } + await inner.collection(passkeyPrincipalsCollection).delete(principalKey); + if (!keepMirror) { + await inner.collection(passkeysCollection).delete(mirrorKey); + } + + const restarted = service(inner); + await expect( + restarted.repairPasskey("legacy_revoked_credential"), + ).resolves.toBeNull(); + await expect( + restarted.removePasskey(principalId, "legacy_revoked_credential"), + ).resolves.toBe(false); + await expect( + inner.collection(passkeyPrincipalsCollection).get(principalKey), + ).resolves.toMatchObject({ + slots: [ + { + credentialHash: credentialDigest, + state: "revoked", + expiresAt: expect.any(String), + }, + ], + }); + await expect( + restarted.beginPasskeyRegistration(principalId, "after-legacy-repair"), + ).resolves.toMatchObject({ challengeHandle: expect.any(String) }); + }, + ); + + it.each([ + ["memory store", createMemoryStore], + ["Azurite", createAzuriteStore], + ] as const)( + "enforces the active credential limit before and after verification over %s", + async (_name, makeStore) => { + const inner = makeStore(); + const identity = service(inner, { + passkeyMaxActiveCredentials: 1, + passkeyMaxRetainedCredentials: 2, + }); + const principalId = await provision(identity); + const [first, waiting] = await Promise.all([ + identity.beginPasskeyRegistration(principalId, "first"), + identity.beginPasskeyRegistration(principalId, "waiting"), + ]); + await identity.finishPasskeyRegistration({ + principalId, + challengeHandle: first.challengeHandle, + label: "First key", + response: registrationResponse("quota_first"), + }); + + await expect( + identity.finishPasskeyRegistration({ + principalId, + challengeHandle: waiting.challengeHandle, + label: "Waiting key", + response: registrationResponse("quota_waiting"), + }), + ).rejects.toMatchObject({ code: "limit_exceeded" }); + await expect( + identity.beginPasskeyRegistration(principalId, "after-limit"), + ).rejects.toMatchObject({ code: "limit_exceeded" }); + await expect(identity.listPasskeys(principalId)).resolves.toHaveLength(1); + + const digest = await principalHash(principalId); + await expect( + inner + .collection(passkeyPrincipalsCollection) + .get({ partition: `passkeys-${digest.slice(0, 32)}`, id: digest }), + ).resolves.toMatchObject({ + slots: [{ state: "active" }], + }); + }, + ); + + it.each([ + ["memory store", createMemoryStore], + ["Azurite", createAzuriteStore], + ] as const)( + "serializes concurrent registrations at the active credential limit over %s", + async (_name, makeStore) => { + const identity = service(makeStore(), { + passkeyMaxActiveCredentials: 1, + passkeyMaxRetainedCredentials: 2, + }); + const principalId = await provision(identity); + const [first, second] = await Promise.all([ + identity.beginPasskeyRegistration(principalId, "first-race"), + identity.beginPasskeyRegistration(principalId, "second-race"), + ]); + + const settled = await Promise.allSettled([ + identity.finishPasskeyRegistration({ + principalId, + challengeHandle: first.challengeHandle, + label: "First key", + response: registrationResponse("quota_race_first"), + }), + identity.finishPasskeyRegistration({ + principalId, + challengeHandle: second.challengeHandle, + label: "Second key", + response: registrationResponse("quota_race_second"), + }), + ]); + + expect( + settled.filter(({ status }) => status === "fulfilled"), + ).toHaveLength(1); + const rejected = settled.find( + (result): result is PromiseRejectedResult => + result.status === "rejected", + ); + expect(rejected?.reason).toMatchObject({ code: "limit_exceeded" }); + await expect(identity.listPasskeys(principalId)).resolves.toHaveLength(1); + }, + ); + + it.each([ + ["memory store", createMemoryStore], + ["Azurite", createAzuriteStore], + ] as const)( + "collects completed and unreferenced registration state after its grace period over %s", + async (_name, makeStore) => { + const inner = makeStore(); + let now = "2026-09-01T12:00:00.000Z"; + const options = { + clock: { now: () => now }, + passkeyMaxActiveCredentials: 1, + passkeyMaxRetainedCredentials: 1, + passkeyRegistrationProofRetentionMs: 1_000, + }; + const first = service(inner, options); + const second = service(inner, options); + const firstPrincipal = await provision(first); + const secondPrincipal = "principal-passkeys-second" as PrincipalId; + await second.provisionVerifiedUser({ + principalId: secondPrincipal, + email: "second@example.test", + }); + const [firstStart, secondStart] = await Promise.all([ + first.beginPasskeyRegistration(firstPrincipal, "first"), + second.beginPasskeyRegistration(secondPrincipal, "second"), + ]); + + const settled = await Promise.allSettled([ + first.finishPasskeyRegistration({ + principalId: firstPrincipal, + challengeHandle: firstStart.challengeHandle, + label: "First key", + response: registrationResponse("shared_credential"), + }), + second.finishPasskeyRegistration({ + principalId: secondPrincipal, + challengeHandle: secondStart.challengeHandle, + label: "Second key", + response: registrationResponse("shared_credential"), + }), + ]); + expect( + settled.filter(({ status }) => status === "fulfilled"), + ).toHaveLength(1); + expect( + settled.filter(({ status }) => status === "rejected"), + ).toHaveLength(1); + const before = await inner + .collection(registrationProofsCollection) + .scan({ limit: 10 }); + expect(before.records).toHaveLength(2); + + now = "2026-09-01T12:00:02.000Z"; + const swept = await sweepPasskeysCompletely(first, 1); + expect(swept.deletedProofs).toBe(2); + expect(swept.releasedReservations).toBe(1); + const after = await inner + .collection(registrationProofsCollection) + .scan({ limit: 10 }); + expect(after.records).toHaveLength(0); + + const losingPrincipal = + settled[0]?.status === "rejected" ? firstPrincipal : secondPrincipal; + await expect( + first.beginPasskeyRegistration(losingPrincipal, "after-maintenance"), + ).resolves.toMatchObject({ challengeHandle: expect.any(String) }); + }, + ); + + it.each([ + ["memory store", createMemoryStore], + ["Azurite", createAzuriteStore], + ] as const)( + "compacts expired revoked records while retaining an active credential over %s", + async (_name, makeStore) => { + const inner = makeStore(); + let now = "2026-09-02T12:00:00.000Z"; + const identity = service(inner, { + clock: { now: () => now }, + passkeyMaxActiveCredentials: 2, + passkeyMaxRetainedCredentials: 2, + passkeyRegistrationProofRetentionMs: 1_000, + passkeyTombstoneRetentionMs: 1_000, + }); + const principalId = await provision(identity); + const first = await identity.beginPasskeyRegistration( + principalId, + "first", + ); + await identity.finishPasskeyRegistration({ + principalId, + challengeHandle: first.challengeHandle, + label: "First key", + response: registrationResponse("retired_credential"), + }); + const second = await identity.beginPasskeyRegistration( + principalId, + "second", + ); + await identity.finishPasskeyRegistration({ + principalId, + challengeHandle: second.challengeHandle, + label: "Second key", + response: registrationResponse("active_credential"), + }); + await expect( + identity.removePasskey(principalId, "retired_credential"), + ).resolves.toBe(true); + await expect(sweepPasskeysCompletely(identity)).resolves.toMatchObject({ + deletedTombstones: 0, + }); + + now = "2026-09-02T12:00:02.000Z"; + await expect(sweepPasskeysCompletely(identity, 1)).resolves.toMatchObject( + { deletedTombstones: 1 }, + ); + const retiredDigest = await credentialHash("retired_credential"); + const principalDigest = await principalHash(principalId); + await expect( + inner.collection(credentialIndexesCollection).get({ + partition: `credential-${retiredDigest.slice(0, 16)}`, + id: retiredDigest, + }), + ).resolves.toBeNull(); + await expect( + inner.collection(passkeysCollection).get({ + partition: `passkeys-${principalDigest.slice(0, 32)}`, + id: retiredDigest, + }), + ).resolves.toBeNull(); + await expect(identity.listPasskeys(principalId)).resolves.toMatchObject([ + { credentialId: "active_credential" }, + ]); + + ceremony.credentialId = "active_credential"; + const authentication = await identity.beginPasskeyAuthentication( + "active-after-maintenance", + ); + await expect( + identity.finishPasskeyAuthentication({ + challengeHandle: authentication.challengeHandle, + response: authenticationResponse(), + }), + ).resolves.toMatchObject({ subject: principalId }); + }, + ); + + it.each([ + ["memory store", createMemoryStore], + ["Azurite", createAzuriteStore], + ] as const)( + "commits removal after a concurrent counter transition over %s", + async (_name, makeStore) => { + const inner = makeStore(); + let armed = false; + let removalObserved!: () => void; + let pendingWritten!: () => void; + let resumeAuthentication!: () => void; + const removalReachedUpdate = new Promise((resolve) => { + removalObserved = resolve; + }); + const counterPending = new Promise((resolve) => { + pendingWritten = resolve; + }); + const authenticationMayResume = new Promise((resolve) => { + resumeAuthentication = resolve; + }); + let heldRemoval = false; + let heldAuthentication = false; + const racing: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const collection = inner.collection(definition); + if (definition.name !== "pegma_identity_credential_indexes") { + return collection; + } + return { + ...collection, + async update(key, decide, updateOptions) { + const wrapped = async (current: T | null) => { + const decision = await decide(current); + const currentState = (current as { state?: string } | null) + ?.state; + const proposedState = + decision.action === "write" + ? (decision.value as { state?: string }).state + : undefined; + if ( + armed && + !heldRemoval && + currentState === "active" && + proposedState === "revoked" + ) { + heldRemoval = true; + removalObserved(); + await counterPending; + } + return decision; + }; + const result = + updateOptions === undefined + ? await collection.update(key, wrapped) + : await collection.update(key, wrapped, updateOptions); + if ( + armed && + !heldAuthentication && + result.written && + (result.value as { state?: string } | null)?.state === + "counter-pending" + ) { + heldAuthentication = true; + pendingWritten(); + await authenticationMayResume; + } + return result; + }, + }; + }, + }; + const identity = service(racing); + const principalId = await provision(identity); + ceremony.registrationCounter = 1; + const registration = await identity.beginPasskeyRegistration( + principalId, + "registration", + ); + await identity.finishPasskeyRegistration({ + principalId, + challengeHandle: registration.challengeHandle, + label: "Security key", + response: registrationResponse(), + }); + ceremony.authenticationCounter = 2; + const authentication = await identity.beginPasskeyAuthentication( + "concurrent-authentication", + ); + + armed = true; + const removing = identity.removePasskey( + principalId, + ceremony.credentialId, + ); + await removalReachedUpdate; + const authenticating = identity.finishPasskeyAuthentication({ + challengeHandle: authentication.challengeHandle, + response: authenticationResponse(), + }); + await counterPending; + await expect(removing).resolves.toBe(true); + + const digest = await credentialHash(ceremony.credentialId); + const principalDigest = await principalHash(principalId); + await expect( + inner.collection(credentialIndexesCollection).get({ + partition: `credential-${digest.slice(0, 16)}`, + id: digest, + }), + ).resolves.toMatchObject({ state: "revoked" }); + await expect( + inner.collection(passkeysCollection).get({ + partition: `passkeys-${principalDigest.slice(0, 32)}`, + id: digest, + }), + ).resolves.toMatchObject({ state: "revoked" }); + + resumeAuthentication(); + await expect(authenticating).rejects.toBeInstanceOf(IdentityError); + const after = await identity.beginPasskeyAuthentication("after-removal"); + await expect( + identity.finishPasskeyAuthentication({ + challengeHandle: after.challengeHandle, + response: authenticationResponse(), + }), + ).rejects.toMatchObject({ code: "verification_failed" }); + }, + ); +}); + describe.each([ { name: "memory store", diff --git a/packages/identity/src/passkeys.ts b/packages/identity/src/passkeys.ts index 177b377..b190be8 100644 --- a/packages/identity/src/passkeys.ts +++ b/packages/identity/src/passkeys.ts @@ -1,6 +1,11 @@ import type { RateLimiter } from "@pegma/rate-limit"; import type { Clock, PrincipalId } from "@pegma/spine"; -import type { Store } from "@pegma/storage-core"; +import { + defineCollection, + type CollectionDefinition, + type Store, + type StoredRecord, +} from "@pegma/storage-core"; import { generateAuthenticationOptions, generateRegistrationOptions, @@ -23,11 +28,14 @@ import { import { IdentityError } from "./errors.js"; import { credentialIndexesCollection, + passkeyPrincipalsCollection, passkeysCollection, registrationProofsCollection, TRANSPORTS, type CredentialIndexRecord, + type PasskeyPrincipalRecord, type PasskeyRecord, + type PasskeySlot, type RegistrationProofRecord, } from "./records.js"; import type { User, UserService, VerifiedIdentityClaims } from "./users.js"; @@ -53,6 +61,10 @@ interface PasskeyServiceOptions { readonly challengeService: ChallengeService; readonly users: UserService; readonly newId: () => string; + readonly maxActiveCredentials: number; + readonly maxRetainedCredentials: number; + readonly registrationProofRetentionMs: number; + readonly tombstoneRetentionMs: number; } export interface RegistrationStart { @@ -101,6 +113,228 @@ export interface PasskeyService { credentialId: string, ): Promise; repairPasskey(credentialId: string): Promise; + sweep(limit?: number, cursor?: string): Promise; +} + +export interface PasskeySweepResult { + readonly inspected: number; + readonly deletedProofs: number; + readonly deletedTombstones: number; + readonly releasedReservations: number; + readonly rejected: number; + readonly cursor: string | null; + readonly hasMore: boolean; +} + +interface SafePasskeyScanRecord { + readonly key: { readonly partition: string; readonly id: string }; + readonly value: unknown; + readonly version: string; +} + +interface SafePasskeyScanPage { + readonly records: readonly unknown[]; + readonly nextCursor: string | null; +} + +function passkeyScanCollection(name: string) { + return defineCollection({ + name, + key: (record) => ({ + partition: String(record.partition), + id: String(record.id), + }), + codec: { + encode: (record) => record, + decode: (record) => record, + }, + }); +} + +const registrationProofScanCollection = passkeyScanCollection( + registrationProofsCollection.name, +); +const credentialIndexScanCollection = passkeyScanCollection( + credentialIndexesCollection.name, +); +const passkeyMirrorScanCollection = passkeyScanCollection( + passkeysCollection.name, +); +const passkeyPrincipalScanCollection = passkeyScanCollection( + passkeyPrincipalsCollection.name, +); + +function passkeyScanOwnData(value: object, name: string): unknown { + const descriptor = Object.getOwnPropertyDescriptor(value, name); + if ( + descriptor === undefined || + !descriptor.enumerable || + !("value" in descriptor) + ) { + throw new IdentityError( + "invalid_state", + "Passkey scan returned malformed data.", + ); + } + return descriptor.value; +} + +function passkeyScanRecord(value: unknown): SafePasskeyScanRecord { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new IdentityError( + "invalid_state", + "Passkey scan returned malformed data.", + ); + } + const prototype = Object.getPrototypeOf(value); + const keys = Reflect.ownKeys(Object.getOwnPropertyDescriptors(value)); + if ( + (prototype !== Object.prototype && prototype !== null) || + keys.length !== 3 || + keys.some( + (key) => + typeof key === "symbol" || + (key !== "key" && key !== "value" && key !== "version"), + ) + ) { + throw new IdentityError( + "invalid_state", + "Passkey scan returned malformed data.", + ); + } + const key = passkeyScanOwnData(value, "key"); + const record = passkeyScanOwnData(value, "value"); + const version = passkeyScanOwnData(value, "version"); + if ( + typeof key !== "object" || + key === null || + Array.isArray(key) || + (Object.getPrototypeOf(key) !== Object.prototype && + Object.getPrototypeOf(key) !== null) || + Reflect.ownKeys(Object.getOwnPropertyDescriptors(key)).length !== 2 || + typeof version !== "string" || + version.length === 0 || + version.length > 16_384 + ) { + throw new IdentityError( + "invalid_state", + "Passkey scan returned malformed data.", + ); + } + const partition = passkeyScanOwnData(key, "partition"); + const id = passkeyScanOwnData(key, "id"); + if ( + typeof partition !== "string" || + partition.length === 0 || + partition.length > 1_024 || + typeof id !== "string" || + id.length === 0 || + id.length > 1_024 + ) { + throw new IdentityError( + "invalid_state", + "Passkey scan returned malformed data.", + ); + } + return Object.freeze({ + key: Object.freeze({ partition, id }), + value: record, + version, + }); +} + +function passkeyScanPage(value: unknown, limit: number): SafePasskeyScanPage { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new IdentityError( + "invalid_state", + "Passkey scan returned malformed data.", + ); + } + const prototype = Object.getPrototypeOf(value); + const keys = Reflect.ownKeys(Object.getOwnPropertyDescriptors(value)); + if ( + (prototype !== Object.prototype && prototype !== null) || + keys.length !== 2 || + keys.some( + (key) => + typeof key === "symbol" || (key !== "records" && key !== "nextCursor"), + ) + ) { + throw new IdentityError( + "invalid_state", + "Passkey scan returned malformed data.", + ); + } + const records = passkeyScanOwnData(value, "records"); + const nextCursor = passkeyScanOwnData(value, "nextCursor"); + if ( + !Array.isArray(records) || + records.length > limit || + (nextCursor !== null && + (typeof nextCursor !== "string" || + nextCursor.length === 0 || + nextCursor.length > 16_384)) + ) { + throw new IdentityError( + "invalid_state", + "Passkey scan returned malformed data.", + ); + } + const descriptors = Object.getOwnPropertyDescriptors(records); + const safeRecords: unknown[] = []; + for (let index = 0; index < records.length; index += 1) { + const descriptor = descriptors[String(index)]; + if ( + descriptor === undefined || + !descriptor.enumerable || + !("value" in descriptor) + ) { + throw new IdentityError( + "invalid_state", + "Passkey scan returned malformed data.", + ); + } + safeRecords.push(descriptor.value); + } + if ( + Reflect.ownKeys(descriptors).filter((key) => key !== "length").length !== + records.length + ) { + throw new IdentityError( + "invalid_state", + "Passkey scan returned malformed data.", + ); + } + return Object.freeze({ + records: Object.freeze(safeRecords), + nextCursor, + }); +} + +function decodePasskeyScanRecord( + raw: unknown, + definition: CollectionDefinition, +): { readonly row: SafePasskeyScanRecord; readonly value: T } { + const row = passkeyScanRecord(raw); + if ( + typeof row.value !== "object" || + row.value === null || + Array.isArray(row.value) + ) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey maintenance record is malformed.", + ); + } + const value = definition.codec.decode(row.value as StoredRecord); + const key = definition.key(value); + if (row.key.partition !== key.partition || row.key.id !== key.id) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey maintenance record is malformed.", + ); + } + return Object.freeze({ row, value }); } function passkeyPartition(hash: string): string { @@ -114,6 +348,13 @@ function passkeyKey(principalDigest: string, credentialDigest: string) { }; } +function passkeyPrincipalKey(principalDigest: string) { + return { + partition: passkeyPartition(principalDigest), + id: principalDigest, + }; +} + function credentialKey(hash: string) { return { partition: `credential-${hash.slice(0, 16)}`, id: hash }; } @@ -144,7 +385,7 @@ function activeUser(user: User | null): asserts user is User { } async function assertCredentialOwner( - index: CredentialIndexRecord, + index: Pick, ): Promise { const principalId = readDataProperty(index, "principalId"); const storedDigest = readDataProperty(index, "principalHash"); @@ -211,9 +452,18 @@ function finalizedCounterTransition( type RegistrationMaterial = Omit< CredentialIndexRecord, - "partition" | "id" | "registrationProofHash" | "state" | "nextCounter" + | "partition" + | "id" + | "registrationProofHash" + | "state" + | "nextCounter" + | "retireAt" >; +function after(milliseconds: number, durationMs: number): string { + return new Date(milliseconds + durationMs).toISOString(); +} + function registrationProofMaterial(material: RegistrationMaterial): string { return JSON.stringify([ material.credentialHash, @@ -340,6 +590,413 @@ export function createPasskeyService( const registrationProofs = options.store.collection( registrationProofsCollection, ); + const principals = options.store.collection(passkeyPrincipalsCollection); + const registrationProofScan = options.store.collection( + registrationProofScanCollection, + ); + const credentialIndexScan = options.store.collection( + credentialIndexScanCollection, + ); + const passkeyMirrorScan = options.store.collection( + passkeyMirrorScanCollection, + ); + const passkeyPrincipalScan = options.store.collection( + passkeyPrincipalScanCollection, + ); + + async function assertPrincipalStateOwner( + state: PasskeyPrincipalRecord, + ): Promise { + if ((await principalHash(state.principalId)) !== state.principalHash) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey principal state is malformed.", + ); + } + } + + function slotFromPasskey(passkey: PasskeyRecord): PasskeySlot { + return { + credentialHash: passkey.credentialHash, + registrationId: passkey.registrationId, + state: passkey.state, + expiresAt: + passkey.state === "revoked" + ? (passkey.retireAt ?? + after(Date.parse(passkey.updatedAt), options.tombstoneRetentionMs)) + : null, + updatedAt: passkey.updatedAt, + }; + } + + function sameSlots( + left: readonly PasskeySlot[], + right: readonly PasskeySlot[], + ): boolean { + return ( + left.length === right.length && + left.every((slot, position) => { + const candidate = right[position]; + return ( + candidate !== undefined && + slot.credentialHash === candidate.credentialHash && + slot.registrationId === candidate.registrationId && + slot.state === candidate.state && + slot.expiresAt === candidate.expiresAt && + slot.updatedAt === candidate.updatedAt + ); + }) + ); + } + + async function mergedPrincipalSlots( + principalId: string, + principalDigest: string, + existing: readonly PasskeySlot[], + ): Promise { + const slots = [...existing]; + const mirrors = await passkeys.list(passkeyPartition(principalDigest)); + for (const mirror of mirrors) { + if ( + mirror.principalId !== principalId || + mirror.principalHash !== principalDigest + ) { + throw new IdentityError( + "storage_corrupt", + "Stored credential binding is malformed.", + ); + } + const next = slotFromPasskey(mirror); + const position = slots.findIndex( + (slot) => slot.credentialHash === mirror.credentialHash, + ); + if (position < 0) { + slots.push(next); + continue; + } + const current = slots[position]; + if (current?.registrationId === mirror.registrationId) { + slots[position] = next; + continue; + } + if (current?.state === "active") { + throw new IdentityError( + "storage_corrupt", + "Stored passkey principal state is malformed.", + ); + } + if (current?.state === "reserved") { + const index = await credentials.get( + credentialKey(mirror.credentialHash), + ); + if (index !== null) { + await assertCredentialOwner(index); + } + if ( + index !== null && + index.principalId === principalId && + index.principalHash === principalDigest && + index.registrationId === mirror.registrationId && + index.state !== "reserved" + ) { + slots[position] = next; + continue; + } + if ( + index !== null && + index.principalId === principalId && + index.principalHash === principalDigest && + index.registrationId === current.registrationId && + index.state === "reserved" + ) { + continue; + } + throw new IdentityError( + "storage_corrupt", + "Stored passkey principal state is malformed.", + ); + } else { + slots[position] = next; + } + } + return Object.freeze( + slots.sort((left, right) => + left.credentialHash.localeCompare(right.credentialHash), + ), + ); + } + + async function ensurePrincipalState( + principalId: string, + principalDigest: string, + updatedAt: string, + ): Promise { + const key = passkeyPrincipalKey(principalDigest); + const result = await principals.update( + key, + async (current) => { + if (current !== null) { + await assertPrincipalStateOwner(current); + if ( + current.principalId !== principalId || + current.principalHash !== principalDigest + ) { + return { action: "keep" }; + } + } + const slots = await mergedPrincipalSlots( + principalId, + principalDigest, + current?.slots ?? [], + ); + if (current !== null && sameSlots(current.slots, slots)) { + return { action: "keep" }; + } + return { + action: "write", + value: { + ...key, + principalId, + principalHash: principalDigest, + slots, + updatedAt, + }, + }; + }, + { maxAttempts: 10 }, + ); + if ( + result.value === null || + result.value.principalId !== principalId || + result.value.principalHash !== principalDigest + ) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey principal state is malformed.", + ); + } + return result.value; + } + + async function reservePrincipalSlot( + material: RegistrationMaterial, + expiresAt: string, + ): Promise { + const key = passkeyPrincipalKey(material.principalHash); + const result = await principals.update( + key, + async (current) => { + if (current !== null) { + await assertPrincipalStateOwner(current); + if ( + current.principalId !== material.principalId || + current.principalHash !== material.principalHash + ) { + return { action: "keep" }; + } + } + const slots = [ + ...(await mergedPrincipalSlots( + material.principalId, + material.principalHash, + current?.slots ?? [], + )), + ]; + const position = slots.findIndex( + (slot) => slot.credentialHash === material.credentialHash, + ); + const candidate = position < 0 ? undefined : slots[position]; + const active = slots.filter((slot) => slot.state !== "revoked").length; + const mayReserve = + (candidate === undefined || candidate.state === "revoked") && + active < options.maxActiveCredentials && + (candidate !== undefined || + slots.length < options.maxRetainedCredentials); + if (mayReserve) { + const reserved: PasskeySlot = { + credentialHash: material.credentialHash, + registrationId: material.registrationId, + state: "reserved", + expiresAt, + updatedAt: material.updatedAt, + }; + if (position < 0) { + slots.push(reserved); + } else { + slots[position] = reserved; + } + } + const normalized = Object.freeze( + slots.sort((left, right) => + left.credentialHash.localeCompare(right.credentialHash), + ), + ); + if ( + current !== null && + sameSlots(current.slots, normalized) && + !mayReserve + ) { + return { action: "keep" }; + } + return { + action: "write", + value: { + ...key, + principalId: material.principalId, + principalHash: material.principalHash, + slots: normalized, + updatedAt: material.updatedAt, + }, + }; + }, + { maxAttempts: 10 }, + ); + const slot = result.value?.slots.find( + (candidate) => + candidate.credentialHash === material.credentialHash && + candidate.registrationId === material.registrationId && + candidate.state === "reserved", + ); + if (slot !== undefined) { + return; + } + const state = result.value; + if ( + state !== null && + (state.slots.filter((candidate) => candidate.state !== "revoked") + .length >= options.maxActiveCredentials || + state.slots.length >= options.maxRetainedCredentials) + ) { + throw new IdentityError("limit_exceeded", "Passkey limit reached."); + } + throw new IdentityError( + "conflict", + "Another credential registration won the race.", + ); + } + + async function setPrincipalSlot( + index: CredentialIndexRecord, + state: "active" | "revoked", + expiresAt: string | null, + ): Promise { + const normalizedExpiresAt = + state === "revoked" + ? (expiresAt ?? + after(Date.parse(index.updatedAt), options.tombstoneRetentionMs)) + : null; + const key = passkeyPrincipalKey(index.principalHash); + const result = await principals.update( + key, + async (current) => { + if (current !== null) { + await assertPrincipalStateOwner(current); + } + if ( + current === null || + current.principalId !== index.principalId || + current.principalHash !== index.principalHash + ) { + return { action: "keep" }; + } + const position = current.slots.findIndex( + (slot) => + slot.credentialHash === index.credentialHash && + slot.registrationId === index.registrationId, + ); + if (position < 0) { + if (state !== "revoked") { + return { action: "keep" }; + } + return { + action: "write", + value: { + ...current, + slots: [ + ...current.slots, + { + credentialHash: index.credentialHash, + registrationId: index.registrationId, + state, + expiresAt: normalizedExpiresAt, + updatedAt: index.updatedAt, + }, + ].sort((left, right) => + left.credentialHash.localeCompare(right.credentialHash), + ), + updatedAt: index.updatedAt, + }, + }; + } + const slots = [...current.slots]; + slots[position] = { + ...slots[position]!, + state, + expiresAt: normalizedExpiresAt, + updatedAt: index.updatedAt, + }; + return { + action: "write", + value: { ...current, slots, updatedAt: index.updatedAt }, + }; + }, + { maxAttempts: 10 }, + ); + const slot = result.value?.slots.find( + (candidate) => + candidate.credentialHash === index.credentialHash && + candidate.registrationId === index.registrationId, + ); + if (slot?.state !== state || slot.expiresAt !== normalizedExpiresAt) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey principal state is malformed.", + ); + } + } + + async function releasePrincipalSlot( + principalId: string, + principalDigest: string, + credentialDigest: string, + registrationId: string, + updatedAt: string, + ): Promise { + const result = await principals.update( + passkeyPrincipalKey(principalDigest), + async (current) => { + if (current !== null) { + await assertPrincipalStateOwner(current); + } + if ( + current === null || + current.principalId !== principalId || + current.principalHash !== principalDigest || + !current.slots.some( + (slot) => + slot.credentialHash === credentialDigest && + slot.registrationId === registrationId, + ) + ) { + return { action: "keep" }; + } + return { + action: "write", + value: { + ...current, + slots: current.slots.filter( + (slot) => + slot.credentialHash !== credentialDigest || + slot.registrationId !== registrationId, + ), + updatedAt, + }, + }; + }, + { maxAttempts: 10 }, + ); + return result.written; + } async function assertRegistrationProof( index: CredentialIndexRecord, @@ -366,6 +1023,7 @@ export function createPasskeyService( async function persistRegistrationProof( material: RegistrationMaterial, + expiresAt: string, ): Promise { const proofHash = await registrationProofHash( registrationProofMaterial(material), @@ -374,6 +1032,7 @@ export function createPasskeyService( ...registrationProofKey(proofHash), ...material, registrationProofHash: proofHash, + expiresAt, }; const inserted = await registrationProofs.insertIfAbsent(proposed); if ( @@ -384,6 +1043,7 @@ export function createPasskeyService( nextCounter: material.counter, registrationProofHash: proofHash, state: "reserved", + retireAt: null, }) ) { throw new IdentityError( @@ -457,6 +1117,7 @@ export function createPasskeyService( transports: index.transports, label: index.label, state: "active", + retireAt: null, createdAt: current?.registrationId === index.registrationId ? current.createdAt @@ -526,31 +1187,44 @@ export function createPasskeyService( ): Promise { await assertCredentialOwner(index); if (index.state === "revoked") { - const existing = await passkeys.get( + const mirrored = await passkeys.update( passkeyKey(index.principalHash, index.credentialHash), - ); - if (existing !== null && existing.state !== "revoked") { - await passkeys.update( - passkeyKey(index.principalHash, index.credentialHash), - (current) => - current === null || - current.principalId !== index.principalId || - current.principalHash !== index.principalHash || - current.credentialId !== index.credentialId || - current.registrationId !== index.registrationId || - current.state === "revoked" - ? { action: "keep" } - : { - action: "write", - value: { - ...current, - state: "revoked", - updatedAt: index.updatedAt, - }, + (current) => + current === null || + current.principalId !== index.principalId || + current.principalHash !== index.principalHash || + current.credentialId !== index.credentialId || + current.registrationId !== index.registrationId || + current.state === "revoked" + ? { action: "keep" } + : { + action: "write", + value: { + ...current, + state: "revoked", + retireAt: index.retireAt, + updatedAt: index.updatedAt, }, - { maxAttempts: 10 }, + }, + { maxAttempts: 10 }, + ); + if ( + mirrored.value !== null && + (mirrored.value.state !== "revoked" || + !sameCredentialBinding(mirrored.value, index) || + mirrored.value.retireAt !== index.retireAt) + ) { + throw new IdentityError( + "conflict", + "Credential changed while it was being repaired.", ); } + await ensurePrincipalState( + index.principalId, + index.principalHash, + index.updatedAt, + ); + await setPrincipalSlot(index, "revoked", index.retireAt); return null; } if (index.state === "counter-pending") { @@ -642,6 +1316,12 @@ export function createPasskeyService( ); } await assertCredentialMirror(finalized.value); + await ensurePrincipalState( + finalized.value.principalId, + finalized.value.principalHash, + finalized.value.updatedAt, + ); + await setPrincipalSlot(finalized.value, "active", null); return mirrored.value; } const current = await credentials.get(credentialKey(index.credentialHash)); @@ -661,7 +1341,13 @@ export function createPasskeyService( await assertCredentialMirror(index); } const passkey = await ensurePasskey(index); - await activateCredential(index); + const active = await activateCredential(index); + await ensurePrincipalState( + active.principalId, + active.principalHash, + active.updatedAt, + ); + await setPrincipalSlot(active, "active", null); return passkey; } @@ -680,13 +1366,19 @@ export function createPasskeyService( "Credential is already bound to another registration.", ); } - const proofHash = await persistRegistrationProof(material); + const proofExpiresAt = after( + Date.parse(material.updatedAt), + options.registrationProofRetentionMs, + ); + await reservePrincipalSlot(material, proofExpiresAt); + const proofHash = await persistRegistrationProof(material, proofExpiresAt); const proposed: CredentialIndexRecord = { ...key, ...material, nextCounter: material.counter, registrationProofHash: proofHash, state: "reserved", + retireAt: null, }; let index = (await credentials.insertIfAbsent(proposed)).value; await assertCredentialOwner(index); @@ -771,6 +1463,17 @@ export function createPasskeyService( options.registrationLimiter, `webauthn-registration:${principalDigest}:${rateLimitKey}`, ); + const state = await ensurePrincipalState( + principalId, + principalDigest, + timestampFromClock(options.clock).value, + ); + if ( + state.slots.filter((slot) => slot.state !== "revoked").length >= + options.maxActiveCredentials + ) { + throw new IdentityError("limit_exceeded", "Passkey limit reached."); + } const existing = ( await passkeys.list(passkeyPartition(principalDigest)) ).filter((passkey) => passkey.state === "active"); @@ -881,7 +1584,6 @@ export function createPasskeyService( createdAt: now, updatedAt: now, }); - await options.challengeService.consumeClaim(claim); } catch (cause) { throw cause instanceof IdentityError ? cause @@ -891,6 +1593,12 @@ export function createPasskeyService( { cause }, ); } + try { + await options.challengeService.consumeClaim(claim); + } catch { + // The credential is already durable and the verifying claim remains + // single-flight and eligible for collection after expiry. + } return publicPasskey(stored); }, @@ -1091,45 +1799,145 @@ export function createPasskeyService( ); const digest = await credentialHash(credentialId); const principalDigest = await principalHash(principalId); - const interrupted = await credentials.get(credentialKey(digest)); - if ( - interrupted?.state === "counter-pending" && - interrupted.credentialId === credentialId && - interrupted.principalId === principalId && - interrupted.principalHash === principalDigest - ) { - await repair(interrupted); - } - const now = timestampFromClock(options.clock).value; - let revoked = false; - const result = await credentials.update( - credentialKey(digest), - async (current) => { - if (current?.state === "active") { - await assertCredentialMirror(current); + const startedAt = timestampFromClock(options.clock); + await ensurePrincipalState(principalId, principalDigest, startedAt.value); + for (let attempt = 0; attempt < 8; attempt += 1) { + const observed = await credentials.get(credentialKey(digest)); + if ( + observed === null || + observed.principalId !== principalId || + observed.principalHash !== principalDigest || + observed.credentialId !== credentialId || + observed.state === "reserved" + ) { + return false; + } + if (observed.state === "revoked") { + await repair(observed); + const mirror = await passkeys.get( + passkeyKey(principalDigest, digest), + ); + if ( + mirror !== null && + (mirror.state !== "revoked" || + !sameCredentialBinding(mirror, observed) || + mirror.retireAt !== observed.retireAt) + ) { + throw new IdentityError( + "conflict", + "Passkey removal did not converge.", + ); + } + return false; + } + if (observed.state === "counter-pending") { + try { + await repair(observed); + } catch (cause) { + if ( + !(cause instanceof IdentityError) || + cause.code !== "conflict" + ) { + throw cause; + } } + continue; + } + const retireAt = after( + startedAt.milliseconds, + options.tombstoneRetentionMs, + ); + const result = await credentials.update( + credentialKey(digest), + async (current) => { + if (current?.state === "active") { + await assertCredentialMirror(current); + } + if ( + current === null || + current.principalId !== principalId || + current.principalHash !== principalDigest || + current.credentialId !== credentialId || + current.registrationId !== observed.registrationId || + current.state !== "active" + ) { + return { action: "keep" }; + } + return { + action: "write", + value: { + ...current, + state: "revoked", + retireAt, + updatedAt: startedAt.value, + }, + }; + }, + { maxAttempts: 10 }, + ); + if ( + result.written && + result.value?.state === "revoked" && + result.value.principalId === principalId && + result.value.principalHash === principalDigest && + result.value.credentialId === credentialId && + result.value.registrationId === observed.registrationId + ) { + await repair(result.value); + const [confirmed, mirror] = await Promise.all([ + credentials.get(credentialKey(digest)), + passkeys.get(passkeyKey(principalDigest, digest)), + ]); if ( - current === null || - current.principalId !== principalId || - current.principalHash !== principalDigest || - current.credentialId !== credentialId || - current.state !== "active" + confirmed?.state === "revoked" && + confirmed.principalId === principalId && + confirmed.principalHash === principalDigest && + confirmed.credentialId === credentialId && + confirmed.registrationId === observed.registrationId && + mirror?.state === "revoked" && + mirror.principalId === principalId && + mirror.principalHash === principalDigest && + mirror.credentialId === credentialId && + mirror.registrationId === observed.registrationId && + sameCredentialBinding(mirror, confirmed) && + mirror.retireAt === confirmed.retireAt ) { - return { action: "keep" }; + return true; } - revoked = true; - return { - action: "write", - value: { ...current, state: "revoked", updatedAt: now }, - }; - }, - { maxAttempts: 10 }, - ); - if (!revoked || result.value === null) { - return false; + throw new IdentityError( + "conflict", + "Passkey removal did not converge.", + ); + } + if ( + result.value?.state === "counter-pending" && + result.value.principalId === principalId && + result.value.principalHash === principalDigest && + result.value.credentialId === credentialId + ) { + try { + await repair(result.value); + } catch (cause) { + if ( + !(cause instanceof IdentityError) || + cause.code !== "conflict" + ) { + throw cause; + } + } + continue; + } + if ( + result.value === null || + result.value.principalId !== principalId || + result.value.principalHash !== principalDigest || + result.value.credentialId !== credentialId || + result.value.state === "revoked" + ) { + return false; + } } - await repair(result.value); - return true; + throw new IdentityError("conflict", "Passkey removal did not converge."); }, async repairPasskey(credentialInput) { @@ -1147,5 +1955,336 @@ export function createPasskeyService( const repaired = await repair(index); return repaired === null ? null : publicPasskey(repaired); }, + + async sweep(limitInput = 100, cursorInput) { + if ( + !Number.isSafeInteger(limitInput) || + limitInput < 1 || + limitInput > 1_000 + ) { + throw new IdentityError("invalid_input", "Sweep limit is invalid."); + } + const stages = ["proofs", "indexes", "mirrors", "principals"] as const; + type Stage = (typeof stages)[number]; + let stage: Stage = "proofs"; + let adapterCursor: string | undefined; + if (cursorInput !== undefined) { + const cursor = assertBoundedString(cursorInput, "Sweep cursor", 16_384); + const separator = cursor.indexOf(":"); + const candidate = cursor.slice(0, separator) as Stage; + if (separator < 0 || !stages.includes(candidate)) { + throw new IdentityError("invalid_input", "Sweep cursor is invalid."); + } + stage = candidate; + const nested = cursor.slice(separator + 1); + adapterCursor = nested === "" ? undefined : nested; + } + const now = timestampFromClock(options.clock); + let inspected = 0; + let deletedProofs = 0; + let deletedTombstones = 0; + let releasedReservations = 0; + let rejected = 0; + let nextAdapterCursor: string | null; + + if (stage === "proofs") { + const page = passkeyScanPage( + await registrationProofScan.scan({ + limit: limitInput, + ...(adapterCursor === undefined ? {} : { cursor: adapterCursor }), + }), + limitInput, + ); + inspected = page.records.length; + nextAdapterCursor = page.nextCursor; + for (const rawRow of page.records) { + let row: SafePasskeyScanRecord; + let proof: RegistrationProofRecord; + try { + ({ row, value: proof } = decodePasskeyScanRecord( + rawRow, + registrationProofsCollection, + )); + await assertCredentialOwner(proof); + } catch { + rejected += 1; + continue; + } + const expiresAt = + proof.expiresAt ?? + after( + Date.parse(proof.updatedAt), + options.registrationProofRetentionMs, + ); + if (Date.parse(expiresAt) > now.milliseconds) { + continue; + } + let index = await credentials.get( + credentialKey(proof.credentialHash), + ); + if ( + index !== null && + index.state === "reserved" && + sameRegistrationProof(proof, index) + ) { + try { + await repair(index); + } catch { + continue; + } + index = await credentials.get(credentialKey(proof.credentialHash)); + } + if ( + index !== null && + sameRegistrationProof(proof, index) && + index.state === "reserved" + ) { + continue; + } + if ( + index !== null && + sameRegistrationProof(proof, index) && + (index.state === "active" || index.state === "counter-pending") + ) { + try { + if (index.state === "counter-pending") { + await repair(index); + } else { + await assertCredentialMirror(index); + } + } catch { + continue; + } + } + if ( + await registrationProofs.deleteIfUnchanged(row.key, row.version) + ) { + deletedProofs += 1; + } + } + } else if (stage === "indexes") { + const page = passkeyScanPage( + await credentialIndexScan.scan({ + limit: limitInput, + ...(adapterCursor === undefined ? {} : { cursor: adapterCursor }), + }), + limitInput, + ); + inspected = page.records.length; + nextAdapterCursor = page.nextCursor; + for (const rawRow of page.records) { + let row: SafePasskeyScanRecord; + let index: CredentialIndexRecord; + try { + ({ row, value: index } = decodePasskeyScanRecord( + rawRow, + credentialIndexesCollection, + )); + await assertCredentialOwner(index); + } catch { + rejected += 1; + continue; + } + if (index.state !== "revoked") { + continue; + } + const retireAt = + index.retireAt ?? + after(Date.parse(index.updatedAt), options.tombstoneRetentionMs); + if (Date.parse(retireAt) > now.milliseconds) { + continue; + } + const mirrorKey = passkeyKey( + index.principalHash, + index.credentialHash, + ); + const mirror = await passkeys.getVersioned(mirrorKey); + if (mirror !== null) { + const mirrorRetireAt = + mirror.value.retireAt ?? + after( + Date.parse(mirror.value.updatedAt), + options.tombstoneRetentionMs, + ); + if ( + mirror.value.state !== "revoked" || + !sameCredentialBinding(mirror.value, index) || + Date.parse(mirrorRetireAt) > now.milliseconds || + (mirror.value.retireAt !== null && + index.retireAt !== null && + mirror.value.retireAt !== index.retireAt) + ) { + continue; + } + if ( + !(await passkeys.deleteIfUnchanged(mirrorKey, mirror.version)) + ) { + continue; + } + } + if (await credentials.deleteIfUnchanged(row.key, row.version)) { + deletedTombstones += 1; + await releasePrincipalSlot( + index.principalId, + index.principalHash, + index.credentialHash, + index.registrationId, + now.value, + ); + } + } + } else if (stage === "mirrors") { + const page = passkeyScanPage( + await passkeyMirrorScan.scan({ + limit: limitInput, + ...(adapterCursor === undefined ? {} : { cursor: adapterCursor }), + }), + limitInput, + ); + inspected = page.records.length; + nextAdapterCursor = page.nextCursor; + for (const rawRow of page.records) { + let row: SafePasskeyScanRecord; + let mirror: PasskeyRecord; + try { + ({ row, value: mirror } = decodePasskeyScanRecord( + rawRow, + passkeysCollection, + )); + await assertCredentialOwner(mirror); + } catch { + rejected += 1; + continue; + } + if (mirror.state !== "revoked") { + continue; + } + const retireAt = + mirror.retireAt ?? + after(Date.parse(mirror.updatedAt), options.tombstoneRetentionMs); + if (Date.parse(retireAt) > now.milliseconds) { + continue; + } + const index = await credentials.get( + credentialKey(mirror.credentialHash), + ); + if ( + index !== null && + index.state === "revoked" && + sameCredentialBinding(mirror, index) + ) { + continue; + } + if (await passkeys.deleteIfUnchanged(row.key, row.version)) { + await releasePrincipalSlot( + mirror.principalId, + mirror.principalHash, + mirror.credentialHash, + mirror.registrationId, + now.value, + ); + } + } + } else { + const page = passkeyScanPage( + await passkeyPrincipalScan.scan({ + limit: limitInput, + ...(adapterCursor === undefined ? {} : { cursor: adapterCursor }), + }), + limitInput, + ); + inspected = page.records.length; + nextAdapterCursor = page.nextCursor; + for (const rawRow of page.records) { + let row: SafePasskeyScanRecord; + let current: PasskeyPrincipalRecord; + try { + ({ row, value: current } = decodePasskeyScanRecord( + rawRow, + passkeyPrincipalsCollection, + )); + await assertPrincipalStateOwner(current); + } catch { + rejected += 1; + continue; + } + const retained: PasskeySlot[] = []; + for (const slot of current.slots) { + if ( + slot.expiresAt === null || + Date.parse(slot.expiresAt) > now.milliseconds + ) { + retained.push(slot); + continue; + } + const [index, mirror] = await Promise.all([ + credentials.get(credentialKey(slot.credentialHash)), + passkeys.get( + passkeyKey(current.principalHash, slot.credentialHash), + ), + ]); + const exactIndex = + index !== null && + index.principalId === current.principalId && + index.principalHash === current.principalHash && + index.registrationId === slot.registrationId; + const exactMirror = + mirror !== null && + mirror.principalId === current.principalId && + mirror.principalHash === current.principalHash && + mirror.registrationId === slot.registrationId; + if (slot.state === "reserved" && exactIndex) { + try { + await repair(index); + const refreshed = await principals.get(row.key); + const refreshedSlot = refreshed?.slots.find( + (candidate) => + candidate.credentialHash === slot.credentialHash && + candidate.registrationId === slot.registrationId, + ); + if (refreshedSlot !== undefined) { + retained.push(refreshedSlot); + continue; + } + } catch { + retained.push(slot); + continue; + } + } + if (exactIndex || exactMirror) { + retained.push(slot); + continue; + } + if (slot.state === "reserved") { + releasedReservations += 1; + } + } + if (!sameSlots(current.slots, retained)) { + await principals.putIfUnchanged( + { ...current, slots: retained, updatedAt: now.value }, + row.version, + ); + } + } + } + + let cursor: string | null; + if (nextAdapterCursor !== null) { + cursor = `${stage}:${nextAdapterCursor}`; + } else { + const position = stages.indexOf(stage); + cursor = + position === stages.length - 1 ? null : `${stages[position + 1]}:`; + } + return Object.freeze({ + inspected, + deletedProofs, + deletedTombstones, + releasedReservations, + rejected, + cursor, + hasMore: cursor !== null, + }); + }, }; } diff --git a/packages/identity/src/records.ts b/packages/identity/src/records.ts index a4aca2d..81a76dd 100644 --- a/packages/identity/src/records.ts +++ b/packages/identity/src/records.ts @@ -88,6 +88,7 @@ export interface PasskeyRecord { readonly transports: readonly string[]; readonly label: string; readonly state: PasskeyState; + readonly retireAt: string | null; readonly createdAt: string; readonly updatedAt: string; readonly lastUsedAt: string | null; @@ -111,6 +112,7 @@ export interface CredentialIndexRecord { readonly transports: readonly string[]; readonly label: string; readonly state: CredentialIndexState; + readonly retireAt: string | null; readonly createdAt: string; readonly updatedAt: string; } @@ -128,10 +130,30 @@ export interface RegistrationProofRecord { readonly counter: number; readonly transports: readonly string[]; readonly label: string; + readonly expiresAt: string | null; readonly createdAt: string; readonly updatedAt: string; } +export type PasskeySlotState = "reserved" | "active" | "revoked"; + +export interface PasskeySlot { + readonly credentialHash: string; + readonly registrationId: string; + readonly state: PasskeySlotState; + readonly expiresAt: string | null; + readonly updatedAt: string; +} + +export interface PasskeyPrincipalRecord { + readonly partition: string; + readonly id: string; + readonly principalId: string; + readonly principalHash: string; + readonly slots: readonly PasskeySlot[]; + readonly updatedAt: string; +} + function enumValue( record: StoredRecord, name: string, @@ -151,6 +173,22 @@ function timestamp(record: StoredRecord, name: string): string { return assertCanonicalTimestamp(readDataProperty(record, name), name); } +function optionalTimestamp(record: StoredRecord, name: string): string | null { + const descriptor = Object.getOwnPropertyDescriptor(record, name); + if (descriptor === undefined) { + return null; + } + if (!("value" in descriptor)) { + throw new IdentityError( + "storage_corrupt", + `Stored property ${name} is missing or unsafe.`, + ); + } + return descriptor.value === null + ? null + : assertCanonicalTimestamp(descriptor.value, name); +} + function hash(record: StoredRecord, name: string): string { return assertHash(storedString(record, name, 64), name); } @@ -386,6 +424,7 @@ function decodePasskey(record: StoredRecord): PasskeyRecord { id: hash(record, "id"), ...fields, state: enumValue(record, "state", ["active", "revoked"]), + retireAt: optionalTimestamp(record, "retireAt"), lastUsedAt: (() => { const value = storedNullableString(record, "lastUsedAt", 32); return value === null @@ -395,7 +434,8 @@ function decodePasskey(record: StoredRecord): PasskeyRecord { }; if ( decoded.id !== decoded.credentialHash || - decoded.partition !== `passkeys-${decoded.principalHash.slice(0, 32)}` + decoded.partition !== `passkeys-${decoded.principalHash.slice(0, 32)}` || + (decoded.state === "active" && decoded.retireAt !== null) ) { throw new IdentityError( "storage_corrupt", @@ -414,6 +454,7 @@ export const passkeysCollection = defineCollection({ id: value.id, ...encodePasskeyFields(value), state: value.state, + retireAt: value.retireAt, lastUsedAt: value.lastUsedAt, }), decode: decodePasskey, @@ -434,13 +475,15 @@ function decodeCredentialIndex(record: StoredRecord): CredentialIndexRecord { "counter-pending", "revoked", ]), + retireAt: optionalTimestamp(record, "retireAt"), }; if ( decoded.id !== decoded.credentialHash || decoded.partition !== `credential-${decoded.credentialHash.slice(0, 16)}` || (decoded.state === "counter-pending" ? decoded.nextCounter <= decoded.counter - : decoded.nextCounter !== decoded.counter) + : decoded.nextCounter !== decoded.counter) || + (decoded.state !== "revoked" && decoded.retireAt !== null) ) { throw new IdentityError( "storage_corrupt", @@ -462,6 +505,7 @@ export const credentialIndexesCollection = nextCounter: value.nextCounter, registrationProofHash: value.registrationProofHash, state: value.state, + retireAt: value.retireAt, }), decode: decodeCredentialIndex, }, @@ -476,11 +520,14 @@ function decodeRegistrationProof( id: hash(record, "id"), registrationProofHash: hash(record, "registrationProofHash"), ...fields, + expiresAt: optionalTimestamp(record, "expiresAt"), }; if ( decoded.id !== decoded.registrationProofHash || decoded.partition !== - `registration-${decoded.registrationProofHash.slice(0, 16)}` + `registration-${decoded.registrationProofHash.slice(0, 16)}` || + (decoded.expiresAt !== null && + Date.parse(decoded.expiresAt) <= Date.parse(decoded.updatedAt)) ) { throw new IdentityError( "storage_corrupt", @@ -500,7 +547,126 @@ export const registrationProofsCollection = id: value.id, registrationProofHash: value.registrationProofHash, ...encodePasskeyFields(value), + expiresAt: value.expiresAt, }), decode: decodeRegistrationProof, }, }); + +function decodePasskeySlots(record: StoredRecord): readonly PasskeySlot[] { + const serialized = storedString(record, "slots", 64 * 1_024); + let value: unknown; + try { + value = JSON.parse(serialized); + } catch (cause) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey slots are malformed.", + { + cause, + }, + ); + } + if (!Array.isArray(value) || value.length > 128) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey slots are malformed.", + ); + } + const seen = new Set(); + return Object.freeze( + value.map((candidate) => { + if ( + typeof candidate !== "object" || + candidate === null || + Array.isArray(candidate) || + Object.getPrototypeOf(candidate) !== Object.prototype + ) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey slots are malformed.", + ); + } + const credentialHash = assertHash( + storedString(candidate as StoredRecord, "credentialHash", 64), + "credentialHash", + ); + if (seen.has(credentialHash)) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey slots are malformed.", + ); + } + seen.add(credentialHash); + const registrationId = storedString( + candidate as StoredRecord, + "registrationId", + 256, + ); + const state = enumValue(candidate as StoredRecord, "state", [ + "reserved", + "active", + "revoked", + ]); + const expiresAt = optionalTimestamp( + candidate as StoredRecord, + "expiresAt", + ); + const updatedAt = timestamp(candidate as StoredRecord, "updatedAt"); + if ( + (state === "active") !== (expiresAt === null) || + (expiresAt !== null && Date.parse(expiresAt) <= Date.parse(updatedAt)) + ) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey slots are malformed.", + ); + } + return Object.freeze({ + credentialHash, + registrationId, + state, + expiresAt, + updatedAt, + }); + }), + ); +} + +function decodePasskeyPrincipal(record: StoredRecord): PasskeyPrincipalRecord { + const decoded: PasskeyPrincipalRecord = { + partition: storedString(record, "partition", 96), + id: hash(record, "id"), + principalId: storedString(record, "principalId", 512), + principalHash: hash(record, "principalHash"), + slots: decodePasskeySlots(record), + updatedAt: timestamp(record, "updatedAt"), + }; + if ( + decoded.id !== decoded.principalHash || + decoded.partition !== `passkeys-${decoded.principalHash.slice(0, 32)}` + ) { + throw new IdentityError( + "storage_corrupt", + "Stored passkey principal state is malformed.", + ); + } + return decoded; +} + +export const passkeyPrincipalsCollection = + defineCollection({ + name: "pegma_identity_passkey_principals", + key: ({ partition, id }) => ({ partition, id }), + codec: { + encode: (value) => ({ + partition: value.partition, + id: value.id, + principalId: value.principalId, + principalHash: value.principalHash, + slots: JSON.stringify(value.slots), + updatedAt: value.updatedAt, + }), + decode: decodePasskeyPrincipal, + }, + }); diff --git a/scripts/release-package.test.mjs b/scripts/release-package.test.mjs index 1055ef1..087fa71 100644 --- a/scripts/release-package.test.mjs +++ b/scripts/release-package.test.mjs @@ -190,8 +190,10 @@ test("trusted publishing rejects npm older than 11.5.1", () => { }); test("runNpm invokes npm even when npm_execpath points at pnpm", () => { - const npmVersion = spawnSync("npm", ["--version"], { + const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm"; + const npmVersion = spawnSync(npmCommand, ["--version"], { encoding: "utf8", + shell: process.platform === "win32", }).stdout.trim(); const previous = process.env.npm_execpath; process.env.npm_execpath = "/tmp/fake-pnpm.cjs";