Accounts 1.1.0: moving Events' users in, people.* requests, new recovery codes
POST /api/accounts/v1/requests (crosscode.identity-request/1): import.* keeps each person's Events id as sub, password hash and authenticator secret (sealed in transit), consent, notices and lockout; linked when the email already has an account. people.* for product admins, limited to people the product knows. New recovery codes after the first 2FA sign-in for people moved in with 2FA. screen=signup. auth-client: request(), seal(), signUp. 8 new tests (47 in all). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -12,6 +12,8 @@
|
||||
* const { sub, sid } = await auth.verifyLogoutToken(form.logout_token); // end that person's sessions
|
||||
* // POST /api/accounts/v1/events:
|
||||
* const call = auth.verifyAccountsCall(rawBody, headers); // user.updated / user.deleted / user.export
|
||||
* // Asking Accounts something (contracts 1.8.0, crosscode.identity-request/1):
|
||||
* const { sub } = await auth.request({ type: 'people.ensure', actor, name, email, phone: null, returnUrl });
|
||||
*
|
||||
* The client secret is derived from the product's link with Accounts (Connect), so a product only
|
||||
* keeps its link secret. Roles are never in the claims: each product keeps its own, keyed by `sub`.
|
||||
@@ -19,10 +21,10 @@
|
||||
import crypto from 'node:crypto';
|
||||
import * as oidc from 'openid-client';
|
||||
import {
|
||||
accountsCallSchema, ACR_MFA, decodeState, encodeState, identityClaimsSchema, OIDC_CLIENT_PATHS, OIDC_PROVIDER_PATHS, OIDC_SCOPES,
|
||||
safeReturnPath, type AccountsCall, type IdentityClaims,
|
||||
accountsCallSchema, ACCOUNTS_REQUEST_PATH, ACR_MFA, decodeState, encodeState, IDENTITY_REQUEST_SCHEMA, identityClaimsSchema, OIDC_CLIENT_PATHS,
|
||||
OIDC_PROVIDER_PATHS, OIDC_SCOPES, safeReturnPath, type AccountsCall, type IdentityClaims, type IdentityRequest,
|
||||
} from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, oidcClientSecret, verify } from '@crosscode/contracts/signing';
|
||||
import { LINK_HEADERS, oidcClientSecret, sealLinkValue, signedHeaders, verify } from '@crosscode/contracts/signing';
|
||||
|
||||
export type AccountsClientOptions = {
|
||||
/** The church's Accounts address, e.g. https://accounts.hopefamily.co.za */
|
||||
@@ -46,6 +48,16 @@ export class SignInError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** Accounts refused or couldn't answer a request (`code` from IDENTITY_REQUEST_ERROR_CODES, or UNREACHABLE / BAD_REPLY). */
|
||||
export class AccountsRequestError extends Error {
|
||||
constructor(message: string, public code: string, public status: number) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** A request without its envelope: `schema` and `requestId` are filled in (pass `requestId` to retry the same one). */
|
||||
export type RequestInput = IdentityRequest extends infer R ? R extends IdentityRequest ? Omit<R, 'schema' | 'requestId'> & { requestId?: string } : never : never;
|
||||
|
||||
export async function accountsClient(o: AccountsClientOptions) {
|
||||
const base = o.productUrl.replace(/\/+$/, '');
|
||||
const issuer = new URL(`${o.accountsUrl.replace(/\/+$/, '')}${OIDC_PROVIDER_PATHS.issuer}`);
|
||||
@@ -56,7 +68,7 @@ export async function accountsClient(o: AccountsClientOptions) {
|
||||
config,
|
||||
|
||||
/** Starts a sign-in that comes back to `returnTo` (the page the person was on). `requireTwoFactor` for staff roles. */
|
||||
async startSignIn(returnTo: string, opts: { requireTwoFactor?: boolean; loginHint?: string } = {}) {
|
||||
async startSignIn(returnTo: string, opts: { requireTwoFactor?: boolean; loginHint?: string; signUp?: boolean } = {}) {
|
||||
const nonce = oidc.randomNonce();
|
||||
const verifier = oidc.randomPKCECodeVerifier();
|
||||
const state = encodeState({ nonce: crypto.randomBytes(16).toString('base64url'), returnTo: safeReturnPath(returnTo) });
|
||||
@@ -69,6 +81,8 @@ export async function accountsClient(o: AccountsClientOptions) {
|
||||
code_challenge_method: 'S256',
|
||||
...(opts.requireTwoFactor ? { acr_values: ACR_MFA } : {}),
|
||||
...(opts.loginHint ? { login_hint: opts.loginHint } : {}),
|
||||
// Accounts 1.1.0: open on "Create an account".
|
||||
...(opts.signUp ? { screen: 'signup' } : {}),
|
||||
});
|
||||
const pending: Pending = { nonce, verifier, state };
|
||||
return { url: url.toString(), cookie: Buffer.from(JSON.stringify(pending)).toString('base64url') };
|
||||
@@ -129,6 +143,30 @@ export async function accountsClient(o: AccountsClientOptions) {
|
||||
return { sub: String(payload.sub), sid: payload.sid ? String(payload.sid) : null };
|
||||
},
|
||||
|
||||
/** Seals a secret for an `import.batch` (a password hash, an authenticator secret) with the link's secret. */
|
||||
seal(value: string): string {
|
||||
return sealLinkValue(o.linkSecret, value);
|
||||
},
|
||||
|
||||
/** Sends a `crosscode.identity-request/1` request to Accounts, signed with the link's secret, and returns its answer. */
|
||||
async request<T = Record<string, unknown>>(input: RequestInput, opts: { timeoutMs?: number } = {}): Promise<T> {
|
||||
const body = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), ...input });
|
||||
const headers = signedHeaders(LINK_HEADERS, { senderId: o.clientId, secret: o.linkSecret, rawBody: body });
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${o.accountsUrl.replace(/\/+$/, '')}${ACCOUNTS_REQUEST_PATH}`, {
|
||||
method: 'POST', body, redirect: 'manual', signal: AbortSignal.timeout(opts.timeoutMs ?? 30000),
|
||||
headers: { 'content-type': 'application/json', accept: 'application/json', ...headers },
|
||||
});
|
||||
} catch (e) {
|
||||
throw new AccountsRequestError(`Accounts could not be reached: ${(e as Error).message}`, 'UNREACHABLE', 502);
|
||||
}
|
||||
const data = (await res.json().catch(() => null)) as (Record<string, unknown> & { message?: string; code?: string }) | null;
|
||||
if (!res.ok) throw new AccountsRequestError(data?.message || `Accounts answered ${res.status}`, data?.code || `HTTP_${res.status}`, res.status);
|
||||
if (!data || data.schema !== IDENTITY_REQUEST_SCHEMA) throw new AccountsRequestError('Accounts answered in a way this product doesn\'t understand.', 'BAD_REPLY', 502);
|
||||
return data as T;
|
||||
},
|
||||
|
||||
/** Checks and reads a back-channel call from Accounts (signed with the link secret). */
|
||||
verifyAccountsCall(rawBody: string | Uint8Array, headers: Record<string, string | string[] | undefined>): AccountsCall {
|
||||
const get = (n: string) => {
|
||||
|
||||
@@ -97,7 +97,10 @@ export const importBatchSchema = base.extend({
|
||||
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. */
|
||||
/**
|
||||
* Ends a move: Accounts compares the count and the hash (`importIdsHash`) of the **subs** it gave
|
||||
* back (`created`, `updated` and `linked`) with the people it holds as moved from this product.
|
||||
*/
|
||||
export const importFinishSchema = base.extend({
|
||||
type: z.literal("import.finish"),
|
||||
count: z.int().nonnegative(),
|
||||
|
||||
Reference in New Issue
Block a user