contracts 1.8.0: crosscode.identity-request/1 (import and people.* calls to Accounts)
Product -> Accounts requests at /api/accounts/v1/requests, signed with the link secret: import.begin/batch/finish/abort for moving a product's users in (EVENTS-3.0-PLAN §4), people.* for product admins (§8). sealLinkValue / openLinkValue seal password hashes and TOTP secrets with a key derived from the link secret; importIdsHash for the final check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
import { z } from "zod";
|
||||
import { dateTimeSchema, emailSchema, idSchema, phoneSchema } from "./common";
|
||||
import { twoFactorMethodSchema } from "./identity";
|
||||
import { schemaName } from "./schema-name";
|
||||
|
||||
/**
|
||||
* `crosscode.identity-request/1` (contracts 1.8.0, docs/EVENTS-3.0-PLAN.md §4 and §8): what a
|
||||
* linked product asks of its church's Accounts. The other direction from `crosscode.identity/1`
|
||||
* (Accounts → product), so it has its own schema and path:
|
||||
*
|
||||
* POST <accounts>/api/accounts/v1/requests signed with the link's secret (LINK_HEADERS)
|
||||
*
|
||||
* - **`import.*`**: moving a product's existing users into Accounts (Cross Events 3.0), with their
|
||||
* password hashes and authenticator secrets. Secret fields are sealed with the link's secret
|
||||
* (`sealLinkValue` in `@crosscode/contracts/signing`) on top of the request signature.
|
||||
* - **`people.*`**: what a product's admin can do to someone's account from the product (add a
|
||||
* person, change their name or email, reset 2FA, unlock, deactivate, news off from an
|
||||
* unsubscribe link). Accounts only acts on people the product knows (signed in through it or
|
||||
* imported by it), and audits each with the product and the admin's `sub`.
|
||||
*/
|
||||
|
||||
export const IDENTITY_REQUEST_SCHEMA = schemaName("identity-request", 1);
|
||||
|
||||
/** On Accounts' address. */
|
||||
export const ACCOUNTS_REQUEST_PATH = "/api/accounts/v1/requests";
|
||||
|
||||
/** People per `import.batch`. */
|
||||
export const IMPORT_BATCH_MAX = 200;
|
||||
|
||||
/** A value sealed with `sealLinkValue`: `sealed1.<base64url iv ‖ ciphertext ‖ tag>`. */
|
||||
export const sealedValueSchema = z.string().regex(/^sealed1\.[A-Za-z0-9_-]{40,}$/, "Expected a sealed value").max(4096);
|
||||
|
||||
const base = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
/** Unique per request; Accounts answers a repeat with the first answer's outcome. */
|
||||
requestId: idSchema,
|
||||
/** The product admin this is done for (their `sub`), or null for the product itself. */
|
||||
actor: idSchema.nullable(),
|
||||
});
|
||||
|
||||
// ─── import.* ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** A privacy notice version, numbers kept (EVENTS-3.0-PLAN decision 5). */
|
||||
export const importNoticeSchema = z.object({
|
||||
version: z.int().positive(),
|
||||
title: z.string().trim().min(1).max(200),
|
||||
body: z.string().min(1).max(200_000),
|
||||
publishedAt: dateTimeSchema,
|
||||
});
|
||||
|
||||
/** One person to move into Accounts. `id` becomes the account's `sub`. */
|
||||
export const importPersonSchema = z.object({
|
||||
id: idSchema,
|
||||
name: z.string().trim().min(1).max(200),
|
||||
email: emailSchema,
|
||||
emailVerified: z.boolean(),
|
||||
phone: phoneSchema.nullable(),
|
||||
/** bcrypt or Argon2id hash, sealed. Null: the person has to set a password (never activated). */
|
||||
passwordHash: sealedValueSchema.nullable(),
|
||||
twoFactor: twoFactorMethodSchema.nullable(),
|
||||
/** The authenticator secret (base32), sealed; only with `twoFactor: "totp"`. */
|
||||
totpSecret: sealedValueSchema.nullable(),
|
||||
totpLastStep: z.int().nonnegative().nullable(),
|
||||
failedSignIns: z.int().nonnegative().max(1000),
|
||||
lockedUntil: dateTimeSchema.nullable(),
|
||||
news: z.object({ email: z.boolean(), whatsapp: z.boolean() }),
|
||||
newsAskedAt: dateTimeSchema.nullable(),
|
||||
/** 0: never accepted a numbered version. */
|
||||
noticeVersionAccepted: z.int().nonnegative(),
|
||||
noticeAcceptances: z.array(z.object({ version: z.int().nonnegative(), acceptedAt: dateTimeSchema })).max(100),
|
||||
consentChanges: z.array(z.object({ channel: z.enum(["email", "whatsapp"]), granted: z.boolean(), at: dateTimeSchema })).max(500),
|
||||
lastSignInAt: dateTimeSchema.nullable(),
|
||||
status: z.enum(["active", "deactivated"]),
|
||||
/** Also an Accounts admin (ticked at the move). */
|
||||
admin: z.boolean(),
|
||||
createdAt: dateTimeSchema,
|
||||
});
|
||||
export type ImportPerson = z.infer<typeof importPersonSchema>;
|
||||
|
||||
/**
|
||||
* Starts (or, with `check: true`, tries) a move. Accounts remembers that this link is moving until
|
||||
* `import.finish` or `import.abort`; `import.batch` is refused otherwise.
|
||||
*/
|
||||
export const importBeginSchema = base.extend({
|
||||
type: z.literal("import.begin"),
|
||||
check: z.boolean(),
|
||||
/** The product's privacy notice versions. Taken only when Accounts has published none of its own. */
|
||||
notices: z.array(importNoticeSchema).max(100),
|
||||
/** Fills the church profile's empty fields, so the sign-in page looks like the church at once. */
|
||||
church: z.object({ name: z.string().trim().min(1).max(200).nullable(), primaryColour: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable() }),
|
||||
});
|
||||
|
||||
export const importBatchSchema = base.extend({
|
||||
type: z.literal("import.batch"),
|
||||
/** With `check: true` nothing is written; the answer says what would happen. */
|
||||
check: z.boolean(),
|
||||
people: z.array(importPersonSchema).min(1).max(IMPORT_BATCH_MAX),
|
||||
});
|
||||
|
||||
/** Ends a move: Accounts compares the count and the ids' hash (`importIdsHash`) with what it holds. */
|
||||
export const importFinishSchema = base.extend({
|
||||
type: z.literal("import.finish"),
|
||||
count: z.int().nonnegative(),
|
||||
idsHash: z.string().regex(/^[0-9a-f]{64}$/),
|
||||
});
|
||||
|
||||
export const importAbortSchema = base.extend({ type: z.literal("import.abort") });
|
||||
|
||||
// ─── people.* ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Find the account with this email, or make one without a password and email a "set your password" link. */
|
||||
export const peopleEnsureSchema = base.extend({
|
||||
type: z.literal("people.ensure"),
|
||||
name: z.string().trim().min(1).max(200),
|
||||
email: emailSchema,
|
||||
phone: phoneSchema.nullable(),
|
||||
/** Where the "set your password" email's link ends (the product's address), after the password is set. */
|
||||
returnUrl: z.url({ protocol: /^https?$/ }).max(2048),
|
||||
});
|
||||
|
||||
const onePerson = { sub: idSchema };
|
||||
|
||||
export const peopleUpdateSchema = base.extend({
|
||||
type: z.literal("people.update"),
|
||||
...onePerson,
|
||||
name: z.string().trim().min(1).max(200).optional(),
|
||||
email: emailSchema.optional(),
|
||||
phone: phoneSchema.nullable().optional(),
|
||||
});
|
||||
export const peopleResetTwoFactorSchema = base.extend({ type: z.literal("people.resetTwoFactor"), ...onePerson });
|
||||
export const peopleUnlockSchema = base.extend({ type: z.literal("people.unlock"), ...onePerson });
|
||||
export const peopleSetActiveSchema = base.extend({ type: z.literal("people.setActive"), ...onePerson, active: z.boolean() });
|
||||
/** Only ever turns news off (an unsubscribe link); turning it on is the person's own choice in Accounts. */
|
||||
export const peopleNewsOffSchema = base.extend({ type: z.literal("people.newsOff"), ...onePerson, channel: z.enum(["email", "whatsapp", "all"]) });
|
||||
|
||||
export const identityRequestSchema = z.discriminatedUnion("type", [
|
||||
importBeginSchema, importBatchSchema, importFinishSchema, importAbortSchema,
|
||||
peopleEnsureSchema, peopleUpdateSchema, peopleResetTwoFactorSchema, peopleUnlockSchema, peopleSetActiveSchema, peopleNewsOffSchema,
|
||||
]);
|
||||
export type IdentityRequest = z.infer<typeof identityRequestSchema>;
|
||||
export type IdentityRequestType = IdentityRequest["type"];
|
||||
|
||||
// ─── Replies ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const importBeginReplySchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
/** False when Accounts has its own notice versions: the move stops and an admin chooses. */
|
||||
noticesTaken: z.boolean(),
|
||||
/** Accounts' own notice versions, when it has some (so the product can show the choice). */
|
||||
accountsNoticeVersions: z.array(z.int().positive()),
|
||||
accountsVersion: z.string(),
|
||||
});
|
||||
|
||||
export const IMPORT_OUTCOMES = ["created", "updated", "linked", "refused"] as const;
|
||||
|
||||
export const importResultSchema = z.object({
|
||||
id: idSchema,
|
||||
outcome: z.enum(IMPORT_OUTCOMES),
|
||||
/** The account's `sub`: the same as `id`, except `linked` (the email already had an account). */
|
||||
sub: idSchema.nullable(),
|
||||
reason: z.string().max(300).nullable(),
|
||||
});
|
||||
export type ImportResult = z.infer<typeof importResultSchema>;
|
||||
|
||||
export const importBatchReplySchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
results: z.array(importResultSchema),
|
||||
});
|
||||
|
||||
export const importFinishReplySchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
matched: z.boolean(),
|
||||
count: z.int().nonnegative(),
|
||||
});
|
||||
|
||||
export const peopleEnsureReplySchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
sub: idSchema,
|
||||
created: z.boolean(),
|
||||
});
|
||||
|
||||
export const okReplySchema = z.object({ schema: z.literal(IDENTITY_REQUEST_SCHEMA), ok: z.literal(true) });
|
||||
|
||||
/** Errors: `{ message, code }` as the other link calls. */
|
||||
export const IDENTITY_REQUEST_ERROR_CODES = [
|
||||
"NOT_LINKED", "BAD_SIGNATURE", "STALE_REQUEST", "INVALID_REQUEST", "NOT_MOVING", "WRONG_PRODUCT", "UNKNOWN_PERSON", "EMAIL_TAKEN", "NOT_ALLOWED",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* The hash `import.finish` carries: SHA-256 (hex) of the sorted ids joined by "\n". Pure JS so it
|
||||
* works in the browser build too; products compute it over the ids they sent (not `refused`).
|
||||
*/
|
||||
export function importIdsInput(ids: Iterable<string>): string {
|
||||
return [...ids].sort().join("\n");
|
||||
}
|
||||
@@ -7,6 +7,7 @@ export * from "./common";
|
||||
export * from "./event";
|
||||
export * from "./church";
|
||||
export * from "./identity";
|
||||
export * from "./identity-request";
|
||||
export * from "./return-to";
|
||||
export * from "./link";
|
||||
export * from "./oidc";
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
createHash,
|
||||
createHmac,
|
||||
createPrivateKey,
|
||||
createPublicKey,
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
} from "node:crypto";
|
||||
import { AGENT_HEADERS, type Sealed } from "./agent";
|
||||
import { canonicalJson } from "./canonical";
|
||||
import { importIdsInput } from "./identity-request";
|
||||
|
||||
export { canonicalJson } from "./canonical";
|
||||
|
||||
@@ -292,3 +294,38 @@ export function verifyLink(message: Record<string, unknown>, publicKeyPem: strin
|
||||
export function oidcClientSecret(linkSecret: string): string {
|
||||
return b64u(createHmac("sha256", linkSecret).update("crosscode.oidc-client/1").digest());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Moving users into Accounts (contracts 1.8.0, docs/EVENTS-3.0-PLAN.md §4): secret fields of an
|
||||
// `import.batch` are sealed with a key derived from the link's secret, on top of the request's
|
||||
// signature, so a password hash or authenticator secret never shows up in a proxy or error log.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const SEALED_PREFIX = "sealed1.";
|
||||
|
||||
function linkSealKey(linkSecret: string): Buffer {
|
||||
return Buffer.from(hkdfSync("sha256", Buffer.from(linkSecret), Buffer.alloc(0), Buffer.from("crosscode.identity-import/1"), 32));
|
||||
}
|
||||
|
||||
/** `sealed1.<base64url(iv ‖ ciphertext ‖ tag)>`, AES-256-GCM with a key from the link's secret. */
|
||||
export function sealLinkValue(linkSecret: string, plain: string): string {
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv("aes-256-gcm", linkSealKey(linkSecret), iv);
|
||||
const data = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
|
||||
return `${SEALED_PREFIX}${b64u(Buffer.concat([iv, data, cipher.getAuthTag()]))}`;
|
||||
}
|
||||
|
||||
/** Opens a value from {@link sealLinkValue}. Throws if it was changed or sealed with another link's secret. */
|
||||
export function openLinkValue(linkSecret: string, sealed: string): string {
|
||||
if (!sealed.startsWith(SEALED_PREFIX)) throw new Error("Not a sealed value");
|
||||
const raw = unb64u(sealed.slice(SEALED_PREFIX.length));
|
||||
if (raw.length < 12 + 16) throw new Error("Not a sealed value");
|
||||
const decipher = createDecipheriv("aes-256-gcm", linkSealKey(linkSecret), raw.subarray(0, 12));
|
||||
decipher.setAuthTag(raw.subarray(raw.length - 16));
|
||||
return Buffer.concat([decipher.update(raw.subarray(12, raw.length - 16)), decipher.final()]).toString("utf8");
|
||||
}
|
||||
|
||||
/** The `idsHash` of `import.finish`: SHA-256 (hex) of the sorted ids joined by "\n". */
|
||||
export function importIdsHash(ids: Iterable<string>): string {
|
||||
return createHash("sha256").update(importIdsInput(ids)).digest("hex");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user