Skip to content
Open
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
129 changes: 129 additions & 0 deletions docs/incoming-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,135 @@ remote effects. No public route, transfer credential or activation is added. Exh
crash/rehydration qualification, activation implementation and public migration qualification remain
deferred.

### Development: tracked credentials and guarded activation

`composeIncomingArrival` also exposes dormant credential and activation callables.
It now takes the application's `legacy` credential instance. No route, page, XRPC
handler, stock-callback consumer or pending guard is mounted; plan 012 injects these.
Failures use stable codes from `DomainError` (`code`) or `HttpError` (`error`).

```text
issueArrivalSession(request, operationId, expectedVersion) -> session
issueCreationSession({did, operationId, arrivalCode}) -> session
refreshArrivalSession(refreshCredential) -> session
recoverArrivalSession(request, otp, {operationId, expectedVersion}) -> session
authorizeArrivalAccess(bearer) -> {operationId, did, userId, familyId}
activateArrivalAsUser(request, otp, {operationId, expectedVersion})
-> {state: "active", operationId, version}
activateArrivalWithCredential(bearer) -> {state: "active", operationId, version}
```

The C3 `owner` is acquired inside each callable (`resumePending` on `arrival:<did>`)
because ownership is scoped to the running operation. `issueArrivalSession` takes the
saved user from the normalized browser principal. `issueCreationSession` is the
cookie-less continuation for the standard `createAccount` response, which carries no
browser cookie (C1). Its saved user is never supplied: it is the user saved on the
arrival, reached only through the current, unexpired arrival code for the same DID
and operation (renewal supersedes it; only its hash is stored), so an operation id
alone mints nothing. The arrival must also be bound and carry an accepted
`createAccount` admission for that saved user and DID with a recorded code
generation. The version is read under the fence because the tool cannot know it. The
source JWT is verified by the admission step, not repeated here. A repeat issuance is
`OperationConflict`.

Consequences, stated plainly. Once the creation admission and binding exist, the code
together with the DID and operation id from the same preparation response is enough to
obtain the first family: no source JWT (it cannot verify after cutover) and no browser
session. The window closes at first issuance or code expiry. A repeat call is
`OperationConflict`; a lost or pre-empted first issuance is recovered through
`recoverArrivalSession` with a fresh email code, which revokes the earlier family apart
from the stock access-token expiry gap. For plan 012: the exported `admitIncoming` still
takes the saved user from a browser principal, so the cookie-less creation admission
that precedes this call must be resolved there.

A session holds the standard fields `did`, `handle`, `email`, `emailConfirmed`,
`didDoc`, `accessJwt` and `refreshJwt`, plus `active: false` and
`status: "deactivated"` because the backend is still paused. The access token is
`at+jwt` with the issuer, subject the DID, audience the placement's PDS DID and scope
`com.atproto.access`; the refresh token is `refresh+jwt` for the Entryway service DID
with scope `com.atproto.refresh`. These are the existing legacy families.

Issuance and recovery require observed provisioning, observed deactivation, the
saved-user binding, a pending (`provisioning`) account on the configured host that
matches the saved arrival, and no unresolved attempt. Refresh requires the same saved
facts and bound unfinished state under the fence, but is not refused by an unresolved
attempt (accepted decision). The family, its arrival association and, for recovery, the
revocation of every prior family commit in one authority transaction; tokens are signed
before it but returned only after it. Recovery needs the exact saved version (a
bound-pending continuation returns it without remote effects), no source JWT (the
source key is no longer current after cutover), and does not depend on the arrival
code's expiry. Revoking local families does not revoke access tokens already issued,
which stock PDS accepts until they expire (five minutes); this gap applies to every
recovery.

Ordinary paths are unchanged. A pending account has status `provisioning`, so ordinary
login, access verification and refresh refuse its families with `AccountUnavailable`
without revoking them, even with a real main password. Ordinary status changes stay
refused by the existing `MigrationPending` and pending-arrival guards. After activation
the same families are ordinary account sessions. `refreshArrivalSession` serves only
tracked families of a bound, unfinished arrival (`InvalidToken` for others,
`ArrivalExpired` for finished ones). Replay revokes the family as for ordinary sessions.

Errors: `AccountNotFound` (unknown operation or other user, identical),
`ArrivalProofRequired`, `InvalidRequest`, `OperationConflict` (version, state, host,
account, repeat issuance), `ArrivalExpired` (cancelled or complete, or an unknown,
superseded or expired code for creation issuance), `OperationRecoveryRequired`,
`InvalidToken`, `ExpiredToken`, `AccountMismatch` (binding or missing creation
admission) and `AccountUnavailable`.

Activation is one operation for every consumer. Intent comes from the saved verified
user or from a live tracked access credential for the arrival (exact subject,
audience, type, main-access scope, unrevoked family, bound unfinished arrival,
re-proved under the fence). No client ready flag, count or digest is read. Under live
ownership it checks, before journaling anything: the canonical PLC head is the exact
saved destination move and its endpoint, repository key, ordered rotation custody and
handle equal the saved facts (`IdentityConflict`; an unreadable directory is
`AccountUnavailable`); the configured host (a changed placement is `OperationConflict`),
local account and saved-user binding match (`OperationConflict`, `AccountMismatch`); no
other unresolved attempt exists; and the backend is observed, is the same DID and
handle, and is paused (`AccountUnavailable` when unobservable; an active backend
without this arrival's journaled activation is `OperationRecoveryRequired`). Raw
transport errors never surface. It then journals the `incoming-activation` attempt and
sets `deactivated: {applied: false}` through the administrator `updateSubjectStatus`
hook. A fresh send requires the backend still paused, otherwise
`OperationRecoveryRequired` with the receipt left unresolved. It observes the backend
active, rechecks identity and, in one transaction, settles the attempt (and any attempt
replaced by an approved safe retry), completes the arrival checkpoint through the
storage primitive (which also marks the local account active), and completes the ownership claim. A
lost acknowledgement keeps the attempt unresolved: backend status alone never
completes, and only isolation/drain recovery allows the exact operation to finish.
Retrying a completed arrival as the saved user returns the committed result. Activation
does not fence in-flight imports and makes no inventory or finality claim (C4).

Accepted decisions for this slice:

- `issueCreationSession` is gated by the current, unexpired arrival code plus an
accepted `createAccount` admission for the saved user and DID on a bound arrival.
That gating is the tool's capability for the first family (consequences above).
- Recovery and browser activation each require a fresh destination email code, with
the separate `incoming-recover` and `incoming-activate` budgets on the existing
challenge producer at its existing limits.
- Refresh stays allowed while an external attempt is unresolved; issuance and
recovery are refused.
- A retry of `activateArrivalWithCredential` after activation completed returns the
committed `{state: "active", operationId, version}` with no backend write and no
journal change. It applies only to a bearer that verifies exactly as before (live,
unrevoked family tracked against that arrival, same DID, host and scope pins), so a
revoked or replaced family, another bearer or an ordinary unrelated session still
gets the earlier refusal and learns nothing about completion. A cancelled arrival
never qualifies. `authorizeArrivalAccess` itself still refuses a finished arrival
with `AccountUnavailable`. An expired access token needs an ordinary refresh first.
- Marking the local account `active` is part of the storage primitive:
`completeArrivalActivation` moves the exact placed account (`provisioning`, same
email, handle and placement) to `active` through the account authority in the same
transaction, fence and version checks as the checkpoint, and refuses an account that
does not match. An arrival cannot complete without the account becoming active.

Storage ownership note: this change adds to plan 009's storage code, with no schema
change. `ArrivalAuthority` gains `activatePlacedAccount`, `completeArrivalActivation`
performs the flip, `settleArrivalAttempt` also retires an attempt replaced by an
approved safe retry, and `readArrivalFamilies` and `readArrivalFamily` are read-only.

## Contract qualification gates for implementers

These are delivery contracts for implementers, not public APIs. The development
Expand Down
2 changes: 1 addition & 1 deletion src/accounts/operation-ownership.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ function canonical(value: unknown): unknown {
);
return value;
}
const requestDigest = (value: unknown) =>
export const requestDigest = (value: unknown) =>
createHash("sha256")
.update(JSON.stringify(canonical(value)) ?? "null")
.digest("hex");
Expand Down
111 changes: 86 additions & 25 deletions src/compose-incoming-arrival.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@
import { createArrivalLifecycle } from "./features/external-migration/manage-arrival.js";
import { createAuthenticatedArrival } from "./features/external-migration/submit-handoff.js";
import { readIncomingObservation } from "./plc/incoming-observation.js";
import { createArrivalCredentials } from "./features/external-migration/arrival-credentials.js";
import { createArrivalActivation } from "./features/external-migration/activate-arrival.js";

export async function composeIncomingArrival({
db,
arrivals,
config,
accounts,
legacy,
authentication,
browserFlow,
}) {
Expand All @@ -27,6 +30,36 @@
accounts,
});
const { choosePds } = await createPdsAccountClient({ config, accounts });
const placement = (pdsId) => config.pds.find((pds) => pds.id === pdsId);
const arrivalBackend = (saved) => {
const pds = choosePds(saved.pdsId);
if (pds.url !== saved.endpoint)
throw new DomainError(
"OperationConflict",
409,
"Arrival placement changed",
);
const transport = new ArrivalPdsClient({
endpoint: saved.endpoint,
did: saved.did,
pdsDid: pds.did,
issuer: config.serviceDid,
jwtJwk: config.jwtJwk,
});
const authorization = () =>
`Basic ${Buffer.from(`admin:${pds.adminPassword}`).toString("base64")}`;

Check warning on line 50 in src/compose-incoming-arrival.mjs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this code to not use nested template literals.

See more on https://sonarcloud.io/project/issues?id=hypercerts-org_hypercerts-entryway&issues=AaHPZ7YTZnsLrpokc3yt&open=AaHPZ7YTZnsLrpokc3yt&pullRequest=28
return {
inspect: () => transport.getAccountInfo(authorization),
create: (operation) =>
transport.createAccount({
did: saved.did,
handle: saved.handle,
operation,
}),
pause: () => transport.pauseAccount(authorization),
activate: () => transport.activateAccount(authorization),
};
};
const prepareArrival = createIncomingPreparation({
arrivals,
ownership: accounts.ownership,
Expand All @@ -41,7 +74,12 @@
entrywayDid: config.serviceDid,
reserveSigningKey: ({ did, pdsId, endpoint }) => {
const pds = choosePds(pdsId);
if (pds.url !== endpoint) throw new Error("Arrival placement changed");
if (pds.url !== endpoint)
throw new DomainError(
"OperationConflict",
409,
"Arrival placement changed",
);
return new ArrivalPdsClient({
endpoint,
did,
Expand Down Expand Up @@ -73,30 +111,7 @@
client: accounts.plcClient,
signer: accounts.plcSigner,
bindPending: admission.bindPending,
backend: (saved) => {
const pds = choosePds(saved.pdsId);
if (pds.url !== saved.endpoint)
throw new Error("Arrival placement changed");
const transport = new ArrivalPdsClient({
endpoint: saved.endpoint,
did: saved.did,
pdsDid: pds.did,
issuer: config.serviceDid,
jwtJwk: config.jwtJwk,
});
const authorization = () =>
`Basic ${Buffer.from(`admin:${pds.adminPassword}`).toString("base64")}`;
return {
inspect: () => transport.getAccountInfo(authorization),
create: (operation) =>
transport.createAccount({
did: saved.did,
handle: saved.handle,
operation,
}),
pause: () => transport.pauseAccount(authorization),
};
},
backend: arrivalBackend,
}),
verify: createIncomingAuthorization({
serviceDid: config.serviceDid,
Expand All @@ -118,9 +133,55 @@
);
return principal.userId;
};
const credentials = createArrivalCredentials({
arrivals,
ownership: accounts.ownership,
transact: (work) => db.transact(work),
signer: legacy.arrivalSessions,
readAccount: (did) => accounts.storage.getByDid(did),
readBinding: (did) => accounts.storage.getVerifiedBinding(did),
readDocument: (did) => accounts.plcClient.getDocument(did),
placement,
authentication,
checkCsrf: browserFlow.checkCsrf,
loadBrowser: browserFlow.loadBrowser,
rateLimit,
});
const activation = createArrivalActivation({
arrivals,
ownership: accounts.ownership,
receipts: createOperationOwnershipStore(db),
transact: (work) => db.transact(work),
plcClient: accounts.plcClient,
accounts: {
getByDid: (did) => accounts.storage.getByDid(did),
getVerifiedBinding: (did) => accounts.storage.getVerifiedBinding(did),
},
placement,
backend: arrivalBackend,
authorizeAccess: credentials.identifyArrivalAccess,
authentication,
checkCsrf: browserFlow.checkCsrf,
loadBrowser: browserFlow.loadBrowser,
rateLimit,
});
return {
...admission,
prepareArrival,
// Tracked migration credentials and the one guarded activation. Dormant:
// plan 012 injects these into routes, XRPC and the stock callback.
issueArrivalSession: async (request, operationId, expectedVersion) =>
credentials.issueArrivalSession(
await savedUser(request),
operationId,
expectedVersion,
),
issueCreationSession: credentials.issueCreationSession,
refreshArrivalSession: credentials.refreshArrivalSession,
recoverArrivalSession: credentials.recoverArrivalSession,
authorizeArrivalAccess: credentials.authorizeArrivalAccess,
activateArrivalAsUser: activation.activateArrivalAsUser,
activateArrivalWithCredential: activation.activateArrivalWithCredential,
renewArrival: lifecycle.renew,
cancelArrival: lifecycle.cancel,
admitIncoming: async (request, input) =>
Expand Down
4 changes: 4 additions & 0 deletions src/database/accounts.port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ export interface AccountTransactor extends AccountReader {
reserveExternalMigration(input: ExternalMigrationReservation): Promise<void>;
bindProvisionedArrival(input: BindProvisionedArrival): Promise<AccountRow>;
activateBoundArrival(input: ActivateBoundArrival): Promise<AccountRow>;
/** Incoming-arrival completion: moves the saved placed account from
* `provisioning` to `active` through `saveAccount`'s reviewed invariants. The
* arrival storage calls this inside its completion transaction. */
activatePlacedAccount(did: string): Promise<void>;
reserveEmail(
email: string,
did: string,
Expand Down
12 changes: 12 additions & 0 deletions src/database/drizzle/account-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,18 @@
return row;
});
},
async activatePlacedAccount(did) {
await db.transact(async () => {
const row = await getByDid(did);
if (!row || row.status !== "provisioning")

Check warning on line 799 in src/database/drizzle/account-storage.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer using an optional chain expression instead, as it's more concise and easier to read.

See more on https://sonarcloud.io/project/issues?id=hypercerts-org_hypercerts-entryway&issues=AaHPZ7U0ZnsLrpokc3yr&open=AaHPZ7U0ZnsLrpokc3yr&pullRequest=28
throw new DomainError(
"IdentityConflict",
409,
"Placed account is not pending activation",
);
await saveAccount({ ...row, status: "active" });
});
},
async activateBoundArrival(input) {
return db.transact(async () => {
const reservation = await one(
Expand Down
Loading
Loading