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
66 changes: 66 additions & 0 deletions .changeset/incoming-arrival-authority.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
"hypercerts-entryway": minor
---

For operators initializing fresh state, the database schema now includes durable
storage for dormant incoming arrivals: an immutable
`{operation, incoming DID, selected PDS and endpoint}` tuple with the saved
verified user and email, a hashed 24-hour arrival authorization, conditional
persistence of the reserved public repository key, and one live arrival per DID
with completed history retained.

Storage and shared-claim behavior:

- A destination email used by an individual arrival must be unique. It is no
longer shared with another identity's claim, reservation or live arrival.
Whole-server association imports keep their existing shared-claim behaviour,
so the two paths stay explicitly distinct.
- An arrival authorization is stored only as a hash and must expire no later than
24 hours after issue. The ceiling is enforced when the code is written and again
by a database constraint, so a reissued or shortened lifetime cannot exceed a
day and code expiry does not release destination reservations or erase progress.
- A saved public key is immutable for its arrival and is included when a valid
arrival code resolves the saved arrival. Reservation-result validation checks
the expected version and owner first: stale versions return `OperationConflict`
and lost ownership returns `OperationLeaseLost`. With current ownership and
version, saved allocation uncertainty returns `OperationRecoveryRequired` before
tuple comparison; otherwise a changed DID, host or endpoint is
`OperationConflict`. A different key for the unchanged tuple returns
`reconciliation-required` with reason `saved-key-differs`. Nothing silently
reallocates or switches placement.
- Cancellation releases local reservations only when the arrival recorded no
allocation at all. The allocation intent is saved before the destination host is
asked for a signing key, so a recorded intent whose key is not yet known already
means dispatch began or is still in flight; cancelling then requires
`OperationRecoveryRequired` and the arrival stays pending for verified recovery.
Cancellation also needs the owning operation's claim and the caller's own
no-remote-obligation and unchanged-PLC evidence; an expired lease authorizes
nothing. Local cancellation never claims remote private material was removed.
- A signed public PLC operation is journaled before it is dispatched. The
source-authorized handoff and the Entryway-signed destination move are stored
with their exact bytes, CID and kind, in the same fenced transaction that
advances the arrival, so an accepted operation is durable before directory
submission and a destination move cannot be recorded ahead of its handoff.
Recorded bytes are immutable: repeating the same operation and CID is
idempotent and changes nothing, while a different operation or CID for the same
kind is a conflict rather than an overwrite. A stale worker records nothing.
Private key material never enters this table, and no new status value is added.
- Preparation requires the actual signed source predecessor, its CID, source
public facts and approved ordered custody. The original source endpoint is
saved from those facts. Signed handoffs and moves must match that authority,
their signed CIDs and the saved destination reservation.
- Accepted admissions are immutable per method and bind the saved principal,
DID, request digest, code generation and verified credential issuer and ID.
Exact retries under current ownership do not advance the version. Creation
admission and invitation reservation can commit together; pending account
binding and invitation completion can also commit together. Bearer credentials,
arrival codes and invitation codes are not stored in arrival admissions.

Operators must initialize fresh state for the changed database schema. This is
not a database-upgrade procedure or a qualification of public account migration.
- Migration-pending access is derived from the current operation, not a new
account status. An arrival does not gain ordinary access or activation from
storage alone, and no readiness or completeness claim is made here.

No public route, remote write, credential signing or activation is added by this
change. Readiness and public exposure remain separately gated.
7 changes: 7 additions & 0 deletions .changeset/incoming-arrival-claim-exclusion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"hypercerts-entryway": patch
---

For operators managing incoming migrations, active arrivals now reserve their destination email, handle and DID against competing account and migration writes. Existing claims also prevent a conflicting arrival from starting. Expired arrival codes do not release pending reservations; the arrival's own validated binding remains atomic, and established shared-primary-email associations remain supported.

Cancellation now refuses persisted remote obligations, including a signed source handoff even when no repository-key allocation exists. Keep these arrivals pending for verified recovery rather than releasing their claims. No configuration change is required.
1 change: 1 addition & 0 deletions .sonarcloud.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sonar.cpd.exclusions=src/database/schema/postgresql.ts,src/database/schema/sqlite.ts
16 changes: 13 additions & 3 deletions docs/incoming-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -562,8 +562,17 @@ outcome, and none overwrites an already-saved tuple member.
recordAllocationIntent(tx, owner, expectedVersion, {operationId, did, pdsId, endpoint})
recordReservationResult(tx, owner, expectedVersion, {operationId, did, pdsId, endpoint, signingKey})
retainUncertainAttempt(tx, owner, expectedVersion, attemptBinding)
recordSignedOperation(tx, owner, expectedVersion, {operationId, did, kind, operation, cid})
```

`recordSignedOperation` journals a signed public PLC operation before it is
dispatched, where `kind` is `handoff` or `destination-move`. The CID must match the
normalized operation bytes, a destination move cannot be recorded before its
handoff, and private key material is rejected. Repeating the same operation and CID
for a kind is idempotent and does not advance the version; a different operation or
CID for that kind is a conflict. A caller holding the pre-record version may receive
`already-settled`, so it must not treat that version as a fresh baseline.

Binding rules these calls must enforce:

- The tuple `{operationId, did, pdsId, endpoint}` is immutable after intent. A
Expand Down Expand Up @@ -616,9 +625,10 @@ derived from the current operation and never stored as a permanent imported-acco
category. Account status values remain `provisioning`, `active`, `deactivated` and
`deleted` as enforced at `src/accounts/rules.ts:19-39`; no new status value is added.

Pending projection. Existing evidence is `hasPendingExternalMigration` at
`src/database/drizzle/account-storage.ts:631-641`, true while any migration
reservation is not complete. The proposed richer projection is owned by plan 009:
Pending projection. `hasPendingExternalMigration` in
`src/database/drizzle/account-storage.ts` checks both incomplete migration
reservations and active incoming arrivals whose completion checkpoint is absent.
The richer arrival projection is owned by plan 009:

```text
readArrivalAccess(did) -> {operationId, version, did, userId, pdsId, provisioned,
Expand Down
4 changes: 2 additions & 2 deletions src/accounts/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export interface ExternalMigrationReservation {
targetPdsUrl: string;
}

export interface FinalizeImportedAccount {
export interface BindProvisionedArrival {
workflowId: string;
did: string;
userId: string;
Expand All @@ -102,7 +102,7 @@ export interface FinalizeImportedAccount {
pdsUrl: string;
}

export interface ActivateImportedAccount {
export interface ActivateBoundArrival {
workflowId: string;
did: string;
userId: string;
Expand Down
4 changes: 2 additions & 2 deletions src/accounts/values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ export type {
} from "../database/accounts.port.js";
export type {
AccountRow,
ActivateImportedAccount,
ActivateBoundArrival,
AccountStatus,
BindVerifiedIdentity,
ExternalMigrationReservation,
FinalizeImportedAccount,
BindProvisionedArrival,
LegacyVerifiedEmail,
OwnerSession,
VerifiedBinding,
Expand Down
10 changes: 6 additions & 4 deletions src/database/accounts.port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import type {
EmailClaim,
StoredEmailClaimPurpose,
ExternalEmailReservation,
ActivateImportedAccount,
ActivateBoundArrival,
BindVerifiedIdentity,
ExternalMigrationReservation,
FinalizeImportedAccount,
BindProvisionedArrival,
LegacyVerifiedEmail,
OwnerSession,
VerifiedBinding,
Expand Down Expand Up @@ -34,6 +34,8 @@ export interface AccountReader {
getVerifiedBinding(did: string): Promise<VerifiedBinding | null>;
getVerifiedOwner(input: OwnerSession): Promise<VerifiedOwner | null>;
hasPendingExternalMigration(did: string): Promise<boolean>;
/** Observation only: whether this DID already has a saved published PLC operation. */
hadPublishedPlcOperation(did: string): Promise<boolean>;
listAccounts(): Promise<AccountRow[]>;
}

Expand All @@ -52,8 +54,8 @@ export interface AccountTransactor extends AccountReader {
/** Bind an account to its verified email user. Callers must validate mailbox proof first. */
bindAccountToVerifiedEmailUser(input: LegacyVerifiedEmail): Promise<string>;
reserveExternalMigration(input: ExternalMigrationReservation): Promise<void>;
finalizeImportedAccount(input: FinalizeImportedAccount): Promise<AccountRow>;
activateImportedAccount(input: ActivateImportedAccount): Promise<AccountRow>;
bindProvisionedArrival(input: BindProvisionedArrival): Promise<AccountRow>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Renaming the whole-server finalizeImportedAccount/activateImportedAccount to bindProvisionedArrival/activateBoundArrival makes them collide with the new ArrivalTransactor.bindProvisionedArrival, which does something different (binds an arrivals row, not a migration_reservations workflow). Nothing in this PR needs the rename, and it touches import-account.ts and two test files. Please revert it, or give the arrival-side methods distinct names.

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.

Deferred: the similarly named whole-server and arrival binding operations remain at ce37a9e. This is a naming/maintainability concern, not a claim that the two operations are equivalent.

activateBoundArrival(input: ActivateBoundArrival): Promise<AccountRow>;
reserveEmail(
email: string,
did: string,
Expand Down
9 changes: 9 additions & 0 deletions src/database/drizzle/account-authority.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,15 @@ export function createAccountAuthority({ db, accounts }) {
} = {},
) => {
email = normalizeEmail(email);
const arrival = await db.read("arrivals", {
where: and(
eq(t.arrivals.active, 1),
eq(sql`lower(${t.arrivals.email})`, email),
),
limit: 1,
});
if (arrival.length > 0)
throw fail(409, "EmailNotAvailable", "This email address cannot be used");
const isCurrentEmail = normalizeEmail((await account(did)).email) === email;
let existing = await claims(email);
for (const pending of existing.filter(
Expand Down
68 changes: 63 additions & 5 deletions src/database/drizzle/account-storage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
import { and, asc, desc, eq, ne, sql } from "drizzle-orm";
import { and, asc, desc, eq, ne, or, sql } from "drizzle-orm";
import {
assertAccountShape,
assertBindingMatchesAccount,
Expand Down Expand Up @@ -187,6 +187,38 @@ export function createAccountStorage(
return null;
return { userId: user.id, email: user.email, authenticatedAt };
};
const assertNoActiveArrival = async (
email: string,
did?: string,
handle?: string,
) => {
const arrivals = await db.read("arrivals", {
where: and(
eq(t.arrivals.active, 1),
or(
eq(sql`lower(${t.arrivals.email})`, normalizeEmail(email)),
did ? eq(t.arrivals.did, did) : undefined,
handle
? eq(sql`lower(${t.arrivals.handle})`, handle.trim().toLowerCase())
: undefined,
),
),
});
if (arrivals.some((arrival) => arrival.did === did))
throw new DomainError(
"IdentityConflict",
409,
"Identity has a pending arrival",
);
if (arrivals.some((arrival) => arrival.email === normalizeEmail(email)))
throw new DomainError(
"EmailNotAvailable",
409,
"Email address is reserved",
);
if (arrivals.length > 0)
throw new DomainError("HandleNotAvailable", 409, "Handle is reserved");
};
const reserveEmail = async (
email: string,
did: string,
Expand All @@ -195,6 +227,7 @@ export function createAccountStorage(
) =>
db.transact(async () => {
email = normalizeEmail(email);
await assertNoActiveArrival(email, did);
const [claims, reservations] = await Promise.all([
db.read("email_claims", {
where: eq(sql`lower(${t.email_claims.email})`, email),
Expand Down Expand Up @@ -242,6 +275,18 @@ export function createAccountStorage(
const reserveHandle = async (handle: string, did: string) =>
db.transact(async () => {
handle = handle.trim().toLowerCase();
const arrival = await one(
"arrivals",
and(
eq(t.arrivals.active, 1),
or(
eq(sql`lower(${t.arrivals.handle})`, handle),
eq(t.arrivals.did, did),
),
)!,
);
if (arrival)
throw new DomainError("HandleNotAvailable", 409, "Handle is reserved");
const external = await one(
"migration_reservations",
eq(t.migration_reservations.handle, handle),
Expand Down Expand Up @@ -281,6 +326,7 @@ export function createAccountStorage(
assertPds(row);
try {
await db.transact(async () => {
await assertNoActiveArrival(row.email, row.did, row.handle);
const previous = (
await db.read("accounts", {
orderBy: [desc(t.accounts.sequence)],
Expand Down Expand Up @@ -309,6 +355,7 @@ export function createAccountStorage(
assertPds(row);
try {
await db.transact(async () => {
await assertNoActiveArrival(row.email, row.did, row.handle);
const previous = await getByDid(row.did);
if (!previous)
throw new DomainError("AccountNotFound", 404, "Account not found");
Expand Down Expand Up @@ -499,6 +546,7 @@ export function createAccountStorage(
"Recent verified owner session required",
);
const email = normalizeEmail(owner.email);
await assertNoActiveArrival(email, input.did, input.handle);
const [emailClaims, emailReservations] = await Promise.all([
db.read("email_claims", {
where: eq(sql`lower(${t.email_claims.email})`, email),
Expand Down Expand Up @@ -618,14 +666,24 @@ export function createAccountStorage(
);
},
async hasPendingExternalMigration(did) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

hasPendingExternalMigration now also returns true for an active arrival, but docs/incoming-migration.md:628-630 still describes it as true only while a migration reservation is incomplete, and cites account-storage.ts:631-641. Please update that paragraph.

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.

Still open at ce37a9e: the pending-projection documentation still describes only incomplete migration reservations and does not reflect the active-arrival check.

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.

Updated in 7bd9e1c: the pending projection documentation now includes active arrivals as well as incomplete migration reservations.

return Boolean(
await one(
const [adopting, arrival] = await Promise.all([
one(
"migration_reservations",
and(
eq(t.migration_reservations.did, did),
ne(t.migration_reservations.state, "complete"),
)!,
),
one(
"arrivals",
and(eq(t.arrivals.did, did), eq(t.arrivals.active, 1))!,
),
]);
return Boolean(adopting || arrival);
},
async hadPublishedPlcOperation(did) {
return Boolean(
await one("custody_operations", eq(t.custody_operations.did, did)),
);
},
async listAccounts() {
Expand Down Expand Up @@ -659,7 +717,7 @@ export function createAccountStorage(
and(eq(t.handle_claims.handle, handle), eq(t.handle_claims.did, did))!,
);
},
async finalizeImportedAccount(input) {
async bindProvisionedArrival(input) {
return db.transact(async () => {
const reservation = await one(
"migration_reservations",
Expand Down Expand Up @@ -735,7 +793,7 @@ export function createAccountStorage(
return row;
});
},
async activateImportedAccount(input) {
async activateBoundArrival(input) {
return db.transact(async () => {
const reservation = await one(
"migration_reservations",
Expand Down
Loading
Loading