Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
## 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
Expand Down
44 changes: 35 additions & 9 deletions docs/THREAT_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Threat model version bump references @​pegma/mail@​0.1.1 without lockfile evidence in diff (nit)

Concrete failure: docs/THREAT_MODEL.md:25 changes the prose from @​pegma/mail@​0.1.0 to @​pegma/mail@​0.1.1 to match the new retention wording, but the diff does not show a corresponding packages/identity/package.json or pnpm-lock.yaml change in this PR. If the dependency remains pinned at 0.1.0, the documented at-least-once delivery guarantee wording diverges from the actually reviewed dependency, weakening the threat-model audit trail.

Evidence: REQUIRED_DEPENDENCIES in scripts/release-package.mjs:13 already expects @​pegma/mail: "0.1.1", matching the doc change, but that file is not in the embedded diff; the review could not confirm the lockfile or manifest were updated atomically with the doc.

Checked: grep for @​pegma/mail shows only docs/THREAT_MODEL.md and scripts/release-package.mjs mention 0.1.1; pnpm-lock.yaml was not listed among changed paths, leaving a proof gap.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No code change: packages/identity/package.json already pins @pegma/mail to 0.1.1, and pnpm-lock.yaml already contains the matching importer and package entries. This corrects stale prose without changing the dependency.

at-least-once delivery state while the provider remains host-owned.

## Threat Model, Trust Boundaries, and Assumptions
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
25 changes: 23 additions & 2 deletions packages/identity/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
```

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions packages/identity/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export type IdentityErrorCode =
| "conflict"
| "not_found"
| "invalid_state"
| "limit_exceeded"
| "rate_limited"
| "verification_failed"
| "storage_corrupt";
Expand Down
50 changes: 50 additions & 0 deletions packages/identity/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
type FinishAuthenticationInput,
type FinishRegistrationInput,
type Passkey,
type PasskeySweepResult,
type RegistrationStart,
} from "./passkeys.js";
import {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -97,6 +106,7 @@ export interface Identity {
limit?: number,
cursor?: string,
): Promise<ChallengeSweepResult>;
sweepPasskeys(limit?: number, cursor?: string): Promise<PasskeySweepResult>;
beginAccountCreation(
email: string,
rateLimitKey: string,
Expand Down Expand Up @@ -171,6 +181,10 @@ const IDENTITY_OPTION_KEYS = new Set([
"emailCodeTtlMs",
"emailCodeMaxAttempts",
"emailOperationRetentionMs",
"passkeyMaxActiveCredentials",
"passkeyMaxRetainedCredentials",
"passkeyRegistrationProofRetentionMs",
"passkeyTombstoneRetentionMs",
]);

function snapshotOptions(value: unknown): Record<string, unknown> {
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -425,6 +474,7 @@ export type {
FinishRegistrationInput,
IdentityErrorCode,
Passkey,
PasskeySweepResult,
ProvisionVerifiedUserInput,
RegistrationStart,
User,
Expand Down
Loading
Loading