Files
crosscode-platform/packages/contracts/src/identity-request.ts
T
joshuaandClaude Opus 5.5 514a6d8bc0 contracts 1.20.0: devotionals, Bible passages, messaging.get, WhatsApp opt-out, App export
The contracts for Church App 1.0.0 (docs/APP-1.0-PLAN.md §12). Additive.

- crosscode.devotional/1, the Hub's devotionals reply, and the devotionals CSV
  import (parseCsv, checkDevotionalCsv, template), shared by the Hub and the App
- Bible books (USFM, English and Afrikaans), seven translations with YouVersion
  ids and copyright lines, parseBibleReference, youVersionUrl
- messaging.get and the messaging.changed hint; whatsapp.optout and
  whatsapp_opted_out on the profile
- APP_MODULES, hub.DEVOTIONALS_PATH, agent.APP_DEMO_PROFILES, app in DEMO_PRODUCTS
- the app section of the church export, people[].roles
- Accounts refuses the two new requests until 1.9.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:54:25 +02:00

440 lines
21 KiB
TypeScript

import { z } from "zod";
import { dateTimeSchema, emailSchema, idSchema, phoneSchema } from "./common";
import { profileSchema, twoFactorMethodSchema } from "./identity";
import { schemaName } from "./schema-name";
import { churchObjectSchema, churchSchema } from "./church";
/**
* `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.
* - **`messaging.*`** (1.9.0): whether Accounts can send email and WhatsApp (its sign-in codes and
* links need them), and setting them up from a product: a test first, saved only if it worked.
* The SMTP password and WAWP access token are sealed with the link's secret. 1.20.0 adds
* `messaging.get` (the App sends with the church's settings) and the `messaging.changed` hint
* back to the product.
* - **`whatsapp.optout`** (1.20.0): a STOP to the church's WhatsApp number, passed on to Accounts,
* which keeps the opt-out for every product.
* - **`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`. 1.11.0 adds
* `people.removeDemo`: new demo data in a product removes the old demo people's accounts.
* - **`church.*`**: the church profile from a product. `church.branding` (1.9.0) fills in the
* look; `church.update` (1.17.0) changes shared facts from the Website's admin.
*/
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.* ────────────────────────────────────────────────────────────────
/**
* The church's look as a product has it, for Accounts' sign-in pages: its name, logo (an https
* address) and colours. 1.9.0 adds the logo and accent colour (optional, so 1.8.0 senders still fit).
*/
export const churchLookSchema = z.object({
name: z.string().trim().min(1).max(200).nullable(),
primaryColour: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable(),
accentColour: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(),
logoUrl: z.url({ protocol: /^https?$/ }).max(2048).nullable().optional(),
});
export type ChurchLook = z.infer<typeof churchLookSchema>;
/** 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: churchLookSchema,
});
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),
});
/** At most this many subs in an `import.finish`. */
export const IMPORT_FINISH_MAX = 50_000;
/**
* Ends a move: every account the product now relies on (each of its users' `sub`). Accounts checks
* each is an account it holds, not deleted, and known to this product (moved in, added, or signed
* in through it), and only then ends the move. So people who signed up through Accounts since an
* earlier move, or a move run again after a failure, check out too.
*/
export const importFinishSchema = base.extend({
type: z.literal("import.finish"),
subs: z.array(idSchema).max(IMPORT_FINISH_MAX),
});
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"]) });
/** The one address domain demo people have (RFC 2606: reserved, so no real person has it). */
export const DEMO_EMAIL_DOMAIN = "example.com";
/** Accounts per `people.removeDemo`. */
export const REMOVE_DEMO_MAX = 1000;
/**
* 1.11.0: the product's demo data was replaced (a new demo profile), so the old demo people's
* accounts go too: signed out everywhere and anonymised. Accounts only removes accounts the
* product knows, at `@example.com`, that aren't Accounts admins; it says why it kept any other.
*/
export const peopleRemoveDemoSchema = base.extend({
type: z.literal("people.removeDemo"),
subs: z.array(idSchema).max(REMOVE_DEMO_MAX),
});
/** Subs per `people.check`. */
export const PEOPLE_CHECK_MAX = 500;
/**
* 1.14.0: the product's regular check that its copies of people are current (Cross Events does it
* nightly), in case a `user.updated` or `user.deleted` never arrived. Accounts answers for each sub
* with the current profile, or says the account was deleted, or that it doesn't know the person
* through this product (`unknown`; never a reason to delete anything).
*/
export const peopleCheckSchema = base.extend({
type: z.literal("people.check"),
subs: z.array(idSchema).min(1).max(PEOPLE_CHECK_MAX),
});
export const PEOPLE_CHECK_STATUSES = ["active", "deactivated", "deleted", "unknown"] as const;
export const peopleCheckReplySchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
people: z.array(z.object({
sub: idSchema,
status: z.enum(PEOPLE_CHECK_STATUSES),
/** The profile as `user.updated` sends it; null for `deleted` and `unknown`. */
profile: profileSchema.nullable(),
})).max(PEOPLE_CHECK_MAX),
});
export type PeopleCheckReply = z.infer<typeof peopleCheckReplySchema>;
// ─── messaging.* (contracts 1.9.0) ───────────────────────────────────────────
/** SMTP settings as Cross Events and Accounts both keep them (`smtp_*`). `pass` sealed; null: keep the saved one. */
export const smtpSettingsSchema = z.object({
host: z.string().trim().min(1).max(253),
port: z.int().min(1).max(65535),
secure: z.boolean(),
user: z.string().max(254),
pass: sealedValueSchema.nullable(),
from: z.string().trim().min(3).max(320),
});
export type SmtpSettings = z.infer<typeof smtpSettingsSchema>;
/** WAWP (wawp.net) settings, as both keep them. `accessToken` sealed; null: keep the saved one. */
export const wawpSettingsSchema = z.object({
accessToken: sealedValueSchema.nullable(),
instanceId: z.string().trim().min(1).max(200),
});
export type WawpSettings = z.infer<typeof wawpSettingsSchema>;
/** Whether Accounts can send email and WhatsApp now (never its secrets). */
export const messagingStatusSchema = base.extend({ type: z.literal("messaging.status") });
/**
* Sends a test with the settings given (not saved): an email to `email.to`, a WhatsApp message to
* `whatsapp.to`. Each part is tried on its own; the answer says how each went.
*/
export const messagingTestSchema = base.extend({
type: z.literal("messaging.test"),
email: z.object({ settings: smtpSettingsSchema, to: emailSchema }).optional(),
whatsapp: z.object({ settings: wawpSettingsSchema, to: phoneSchema }).optional(),
});
/** Tests the settings given as messaging.test does, and saves each part only if its test worked. */
export const messagingSetSchema = messagingTestSchema.extend({ type: z.literal("messaging.set") });
/**
* 1.20.0 (APP-1.0-PLAN §8, decision 4): the church's email and WhatsApp settings, for a product
* that sends with them but never asks for its own (the Church App). One set per church: kept in
* Events or Accounts, copied to the others. The SMTP password and WAWP token come sealed with the
* link's secret. Accounts remembers who asked, and sends each a `messaging.changed` when they
* change (`MESSAGING_CHANGED_PATH`), so it fetches them again.
*/
export const messagingGetSchema = base.extend({ type: z.literal("messaging.get") });
/**
* 1.20.0 (APP-1.0-PLAN §8, decision 11): someone replied STOP to the church's WhatsApp number.
* Whichever product's webhook received it tells Accounts, which keeps the opt-out for every
* product: it sets `whatsapp_opted_out` on each account with that verified number and sends
* `user.updated` to every linked product. Only ever turns WhatsApp off; turning it back on is the
* person's own choice in Accounts. Accounts also keeps a number without an account, so an account
* made with it later starts opted out.
*/
export const whatsappOptOutSchema = base.extend({
type: z.literal("whatsapp.optout"),
phone: phoneSchema,
/** When the reply arrived. */
receivedAt: dateTimeSchema,
/** The word they sent (`STOP`, `UNSUBSCRIBE`, `STOPP`), for the audit. */
keyword: z.string().trim().min(1).max(40),
});
/**
* 1.9.0: use the product's look (name, logo, colours) on Accounts' pages. `overwrite: false` only
* fills what Accounts doesn't have yet; `true` replaces it (an admin pressing the button).
*/
export const churchBrandingSchema = base.extend({ type: z.literal("church.branding"), church: churchLookSchema, overwrite: z.boolean() });
/**
* The profile fields a product may change: the profile without what Accounts fills in itself
* (`customerId`, `updatedAt`, `links`).
*/
export const churchEditableSchema = churchObjectSchema.omit({ schema: true, customerId: true, updatedAt: true, links: true });
/**
* 1.17.0: change shared profile facts from a product's admin (the Website's, WEBSITE-1.0-PLAN
* decision 10). The product checks the person may do it (its own roles: Accounts doesn't know
* them) and sends it with them as `actor`; Accounts audits it with the product and the actor.
*
* Only the fields given change. A given field replaces Accounts' value as a whole (a list, an
* address, `branding.colours`), except `branding`, whose own fields can be given one at a time
* (only `style`, say). It goes live at once (shared facts aren't drafts) and Accounts sends
* `church.changed` to every linked product. With `ifUpdatedAt`, Accounts refuses with
* `PROFILE_CHANGED` when the profile changed since (someone saved in between).
*
* Accounts takes it from the Website only (`WRONG_PRODUCT` otherwise) and needs an `actor`
* (`NOT_ALLOWED`). The reply is the profile after the change.
*/
export const churchUpdateSchema = base.extend({
type: z.literal("church.update"),
actor: idSchema,
ifUpdatedAt: dateTimeSchema.optional(),
church: churchEditableSchema
.extend({ branding: churchEditableSchema.shape.branding.partial() })
.partial()
.refine((c) => Object.keys(c).length > 0, "Nothing to change"),
});
export const identityRequestSchema = z.discriminatedUnion("type", [
importBeginSchema, importBatchSchema, importFinishSchema, importAbortSchema,
peopleEnsureSchema, peopleUpdateSchema, peopleResetTwoFactorSchema, peopleUnlockSchema, peopleSetActiveSchema, peopleNewsOffSchema,
peopleRemoveDemoSchema, peopleCheckSchema, messagingStatusSchema, messagingTestSchema, messagingSetSchema, churchBrandingSchema, churchUpdateSchema,
messagingGetSchema, whatsappOptOutSchema,
]);
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),
/** Every sub checked out; the move has ended. */
matched: z.boolean(),
/** How many of the subs Accounts holds for this product. */
count: z.int().nonnegative(),
/** Some of the subs that didn't check out (at most 100). */
missing: z.array(idSchema).max(100),
});
export const peopleEnsureReplySchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
sub: idSchema,
created: z.boolean(),
/** 1.9.0: whether the "choose your password" email went (false: Accounts' email isn't working). */
emailSent: z.boolean().optional(),
});
/** people.removeDemo: how many accounts went, and each one kept with why. */
export const peopleRemoveDemoReplySchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
removed: z.int().nonnegative(),
kept: z.array(z.object({ sub: idSchema, reason: z.enum(["not_demo", "admin", "unknown"]) })).max(REMOVE_DEMO_MAX),
});
export type PeopleRemoveDemoReply = z.infer<typeof peopleRemoveDemoReplySchema>;
export const okReplySchema = z.object({ schema: z.literal(IDENTITY_REQUEST_SCHEMA), ok: z.literal(true) });
/** messaging.status: what's set up (no secrets; `from` and `host` to recognise it). */
export const messagingStatusReplySchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }),
whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }),
});
export type MessagingStatusReply = z.infer<typeof messagingStatusReplySchema>;
/** One part's test: sent, or why not. `saved` only on messaging.set. */
export const messagingResultSchema = z.object({ ok: z.boolean(), error: z.string().max(500).nullable(), saved: z.boolean() });
/** messaging.test / messaging.set: each part that was given, and the status after. */
export const messagingTestReplySchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
email: messagingResultSchema.nullable(),
whatsapp: messagingResultSchema.nullable(),
status: messagingStatusReplySchema.omit({ schema: true }),
});
export type MessagingTestReply = z.infer<typeof messagingTestReplySchema>;
/**
* messaging.get: the settings, secrets sealed with the link's secret; null for a part that isn't
* set up (or doesn't work: `ready` false in messaging.status). `email.pass` null: the server
* takes no password. `updatedAt`: the last change to either part.
*/
export const messagingGetReplySchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
email: smtpSettingsSchema.nullable(),
whatsapp: wawpSettingsSchema.extend({ accessToken: sealedValueSchema }).nullable(),
updatedAt: dateTimeSchema.nullable(),
});
export type MessagingGetReply = z.infer<typeof messagingGetReplySchema>;
/** whatsapp.optout: how many accounts have the number (0 is fine: the number is kept anyway). */
export const whatsappOptOutReplySchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
accounts: z.int().nonnegative(),
});
export type WhatsappOptOutReply = z.infer<typeof whatsappOptOutReplySchema>;
// ─── Accounts → product: messaging.changed (1.20.0) ─────────────────────────
/** On the product's address. Signed with the link's secret (LINK_HEADERS). */
export const MESSAGING_CHANGED_PATH = "/api/accounts/v1/messaging-changed";
/**
* A hint, as `church.changed` is: the church's email or WhatsApp settings changed (in Accounts,
* or copied in from Events), so send `messaging.get` again. Sent to the products that asked for
* them. The product answers `{ ok: true }` (`okReplySchema`); Accounts retries otherwise.
*/
export const messagingChangedSchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
type: z.literal("messaging.changed"),
occurredAt: dateTimeSchema,
/** Which parts changed. */
email: z.boolean(),
whatsapp: z.boolean(),
});
export type MessagingChanged = z.infer<typeof messagingChangedSchema>;
/** church.update: the profile after the change. */
export const churchUpdateReplySchema = z.object({ schema: z.literal(IDENTITY_REQUEST_SCHEMA), church: churchSchema });
export type ChurchUpdateReply = z.infer<typeof churchUpdateReplySchema>;
/** 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",
/** 1.17.0, church.update with `ifUpdatedAt`: the profile changed since. */
"PROFILE_CHANGED",
] as const;