diff --git a/backend/src/services/__tests__/invites.test.ts b/backend/src/services/__tests__/invites.test.ts new file mode 100644 index 00000000..89587bb2 --- /dev/null +++ b/backend/src/services/__tests__/invites.test.ts @@ -0,0 +1,322 @@ +import { + INVITE_STATES, + INVITE_EVENTS, + TERMINAL_INVITE_STATES, + InviteErrorCode, + InviteError, + DEFAULT_INVITE_CONFIG, + transition, + canTransition, + normalizeInvite, + createInviteMachine, + isInviteState, + isInviteEvent, + isInviteExpired, + isTerminalInviteState, + noopInviteMetrics, + noopInviteLogger, + type InviteState, + type InviteEvent, + type InviteMetrics, + type InviteLogger, +} from '../invites'; + +const T0 = Date.UTC(2026, 10, 20, 12, 0, 0); + +/** Return the stable code of the error thrown by `fn`. */ +function codeOf(fn: () => unknown): string { + try { + fn(); + } catch (e) { + return (e as InviteError).code; + } + throw new Error('expected fn to throw'); +} + +describe('invite vocabulary (#2255)', () => { + it('exposes all six states in order and freezes them', () => { + expect(INVITE_STATES).toEqual(['draft', 'pending', 'accepted', 'declined', 'expired', 'revoked']); + expect(Object.isFrozen(INVITE_STATES)).toBe(true); + expect(INVITE_STATES).toHaveLength(6); + }); + + it('exposes all five events and freezes them', () => { + expect(INVITE_EVENTS).toEqual(['send', 'accept', 'decline', 'expire', 'revoke']); + expect(Object.isFrozen(INVITE_EVENTS)).toBe(true); + }); + + it('defines the terminal states', () => { + expect(TERMINAL_INVITE_STATES).toEqual(['accepted', 'declined', 'expired', 'revoked']); + expect(isTerminalInviteState('accepted')).toBe(true); + expect(isTerminalInviteState('pending')).toBe(false); + }); + + it('exposes stable, frozen error codes', () => { + expect(Object.isFrozen(InviteErrorCode)).toBe(true); + expect(InviteErrorCode.INVALID_TRANSITION).toBe('INVALID_TRANSITION'); + expect(InviteErrorCode.INVITE_EXPIRED).toBe('INVITE_EXPIRED'); + }); + + it('exposes a frozen default config', () => { + expect(Object.isFrozen(DEFAULT_INVITE_CONFIG)).toBe(true); + expect(DEFAULT_INVITE_CONFIG.ttlMs).toBe(7 * 24 * 60 * 60 * 1000); + expect(DEFAULT_INVITE_CONFIG.maxActivePerHousehold).toBe(10); + }); +}); + +describe('valid transitions', () => { + it('sends a draft invite to pending', () => { + expect(transition('draft', 'send')).toBe('pending'); + }); + + it('accepts a pending invite', () => { + expect(transition('pending', 'accept', { nowMs: T0, expiresAt: T0 + 1000 })).toBe('accepted'); + }); + + it('declines a pending invite', () => { + expect(transition('pending', 'decline')).toBe('declined'); + }); + + it('expires a pending invite', () => { + expect(transition('pending', 'expire')).toBe('expired'); + }); + + it('revokes a pending invite', () => { + expect(transition('pending', 'revoke')).toBe('revoked'); + }); +}); + +describe('invalid transitions throw typed errors', () => { + it('rejects accepting a draft invite', () => { + expect(() => transition('draft', 'accept')).toThrow(InviteError); + expect(codeOf(() => transition('draft', 'accept'))).toBe(InviteErrorCode.INVALID_TRANSITION); + }); + + it('rejects sending an already-pending invite', () => { + expect(codeOf(() => transition('pending', 'send'))).toBe(InviteErrorCode.INVALID_TRANSITION); + }); + + it('rejects every transition out of a terminal state', () => { + const terminals: InviteState[] = ['accepted', 'declined', 'expired', 'revoked']; + const events: InviteEvent[] = ['send', 'accept', 'decline', 'expire', 'revoke']; + for (const state of terminals) { + for (const event of events) { + expect(codeOf(() => transition(state, event))).toBe(InviteErrorCode.INVALID_TRANSITION); + } + } + }); + + it('rejects an unknown state', () => { + expect(codeOf(() => transition('bananas' as InviteState, 'send'))).toBe(InviteErrorCode.INVALID_STATE); + }); + + it('rejects an unknown event', () => { + expect(codeOf(() => transition('draft', 'teleport' as InviteEvent))).toBe(InviteErrorCode.INVALID_EVENT); + }); + + it('attaches non-sensitive details to the error', () => { + try { + transition('draft', 'accept'); + throw new Error('expected throw'); + } catch (e) { + const err = e as InviteError; + expect(err.name).toBe('InviteError'); + expect(err.code).toBe(InviteErrorCode.INVALID_TRANSITION); + expect(err.details.state).toBe('draft'); + expect(err.details.event).toBe('accept'); + expect(Object.isFrozen(err.details)).toBe(true); + } + }); +}); + +describe('guards', () => { + it('blocks sending when the household is at its active limit', () => { + expect(codeOf(() => transition('draft', 'send', { activeInvites: 10 }))).toBe( + InviteErrorCode.MAX_ACTIVE_EXCEEDED, + ); + }); + + it('allows sending when a slot is free', () => { + expect(transition('draft', 'send', { activeInvites: 9 })).toBe('pending'); + }); + + it('honours a per-transition active-invite override', () => { + const ctx = { activeInvites: 3, maxActivePerHousehold: 3 }; + expect(codeOf(() => transition('draft', 'send', ctx))).toBe(InviteErrorCode.MAX_ACTIVE_EXCEEDED); + expect(transition('draft', 'send', { activeInvites: 1, maxActivePerHousehold: 3 })).toBe('pending'); + }); + + it('rejects a non-positive active limit as invalid config', () => { + expect(codeOf(() => transition('draft', 'send', { maxActivePerHousehold: 0 }))).toBe( + InviteErrorCode.INVALID_CONFIG, + ); + }); + + it('rejects malformed active counts as invalid input', () => { + expect(codeOf(() => transition('draft', 'send', { activeInvites: -1 }))).toBe( + InviteErrorCode.INVALID_INPUT, + ); + }); + + it('refuses to accept an expired invite using the injectable clock', () => { + expect(codeOf(() => transition('pending', 'accept', { nowMs: T0 + 1001, expiresAt: T0 + 1000 }))).toBe( + InviteErrorCode.INVITE_EXPIRED, + ); + }); + + it('accepts an invite one millisecond before expiry', () => { + expect(transition('pending', 'accept', { nowMs: T0 + 999, expiresAt: T0 + 1000 })).toBe('accepted'); + }); + + it('rejects a non-finite clock value', () => { + expect(codeOf(() => transition('pending', 'accept', { nowMs: Number.NaN }))).toBe( + InviteErrorCode.INVALID_INPUT, + ); + }); +}); + +describe('canTransition', () => { + it('is true for legal, guard-passing transitions', () => { + expect(canTransition('draft', 'send', { activeInvites: 0 })).toBe(true); + expect(canTransition('pending', 'accept', { nowMs: T0, expiresAt: T0 + 1 })).toBe(true); + }); + + it('is false for illegal transitions and failed guards', () => { + expect(canTransition('accepted', 'accept')).toBe(false); + expect(canTransition('draft', 'send', { activeInvites: 10 })).toBe(false); + expect(canTransition('pending', 'accept', { nowMs: T0 + 5000, expiresAt: T0 + 1 })).toBe(false); + }); + + it('never throws on unknown states or events', () => { + expect(canTransition('nope' as InviteState, 'send')).toBe(false); + expect(canTransition('draft', 'nope' as InviteEvent)).toBe(false); + }); +}); + +describe('pure helpers', () => { + it('detects valid states and events', () => { + expect(isInviteState('pending')).toBe(true); + expect(isInviteState('nope')).toBe(false); + expect(isInviteEvent('revoke')).toBe(true); + expect(isInviteEvent('nope')).toBe(false); + }); + + it('checks expiry against an injectable clock', () => { + expect(isInviteExpired(T0 + 1000, T0 + 999)).toBe(false); + expect(isInviteExpired(T0 + 1000, T0 + 1000)).toBe(true); + expect(codeOf(() => isInviteExpired(Number.NaN, T0))).toBe(InviteErrorCode.INVALID_INPUT); + }); +}); + +describe('normalizeInvite', () => { + it('applies all defaults and freezes the result', () => { + const invite = normalizeInvite({ id: 'a-1', householdId: 'h-1' }, T0); + expect(invite.id).toBe('a-1'); + expect(invite.householdId).toBe('h-1'); + expect(invite.state).toBe('draft'); + expect(invite.token).toBe('inv_a-1'); + expect(invite.issuedAt).toBe(T0); + expect(invite.expiresAt).toBe(T0 + DEFAULT_INVITE_CONFIG.ttlMs); + expect(Object.isFrozen(invite)).toBe(true); + }); + + it('preserves explicitly supplied fields and trims identifiers', () => { + const invite = normalizeInvite( + { + id: ' a-2 ', + householdId: ' h-2 ', + state: 'pending', + token: 'tok-2', + issuedAt: T0, + expiresAt: T0 + 100, + }, + T0 + 999, + ); + expect(invite.id).toBe('a-2'); + expect(invite.householdId).toBe('h-2'); + expect(invite.state).toBe('pending'); + expect(invite.token).toBe('tok-2'); + expect(invite.expiresAt).toBe(T0 + 100); + }); + + it('rejects malformed input', () => { + expect(codeOf(() => normalizeInvite({ id: '', householdId: 'h' }, T0))).toBe( + InviteErrorCode.INVALID_INPUT, + ); + expect(codeOf(() => normalizeInvite({ id: 'a', householdId: ' ' }, T0))).toBe( + InviteErrorCode.INVALID_INPUT, + ); + expect(codeOf(() => normalizeInvite({ id: 'a', householdId: 'h', state: 'bogus' }, T0))).toBe( + InviteErrorCode.INVALID_STATE, + ); + expect( + codeOf(() => normalizeInvite({ id: 'a', householdId: 'h', expiresAt: T0 - 1 }, T0)), + ).toBe(InviteErrorCode.INVALID_INPUT); + }); +}); + +describe('observability hooks', () => { + it('calls metrics.transition on success and metrics.rejection on failure', () => { + const events: string[] = []; + const metrics: InviteMetrics = { + transition: (from, event, to) => events.push(`${from}:${event}:${to}`), + rejection: (code) => events.push(`reject:${code}`), + }; + const machine = createInviteMachine({}, metrics); + expect(machine.transition('draft', 'send')).toBe('pending'); + expect(events).toEqual(['draft:send:pending']); + try { + machine.transition('draft', 'accept'); + } catch { + /* expected */ + } + expect(events).toHaveLength(2); + expect(events[1]).toBe('reject:INVALID_TRANSITION'); + }); + + it('calls the logger with non-sensitive context', () => { + const messages: string[] = []; + const logger: InviteLogger = { + debug: (message) => messages.push(message), + }; + const machine = createInviteMachine({}, noopInviteMetrics, logger); + machine.transition('draft', 'send'); + machine.canTransition('pending', 'accept', { nowMs: T0 + 5000, expiresAt: T0 }); + expect(messages[0]).toBe('invite transition applied'); + expect(messages).toContain('invite transition rejected'); + }); + + it('exports usable no-op hooks', () => { + expect(typeof noopInviteMetrics.transition).toBe('function'); + expect(typeof noopInviteMetrics.rejection).toBe('function'); + expect(typeof noopInviteLogger.debug).toBe('function'); + expect(() => noopInviteMetrics.rejection(InviteErrorCode.INVALID_STATE, 'draft', 'send')).not.toThrow(); + }); +}); + +describe('createInviteMachine', () => { + it('merges config overrides and freezes the machine', () => { + const machine = createInviteMachine({ ttlMs: 1000, maxActivePerHousehold: 2 }); + expect(machine.config.ttlMs).toBe(1000); + expect(machine.config.maxActivePerHousehold).toBe(2); + expect(Object.isFrozen(machine.config)).toBe(true); + expect(Object.isFrozen(machine)).toBe(true); + expect(machine.states).toBe(INVITE_STATES); + }); + + it('rejects invalid configuration', () => { + expect(codeOf(() => createInviteMachine({ ttlMs: 0 }))).toBe(InviteErrorCode.INVALID_CONFIG); + expect(codeOf(() => createInviteMachine({ maxActivePerHousehold: 0 }))).toBe( + InviteErrorCode.INVALID_CONFIG, + ); + }); + + it('applies its own config in bound guards', () => { + const machine = createInviteMachine({ maxActivePerHousehold: 2 }); + expect(machine.transition('draft', 'send', { activeInvites: 1 })).toBe('pending'); + expect(codeOf(() => machine.transition('draft', 'send', { activeInvites: 2 }))).toBe( + InviteErrorCode.MAX_ACTIVE_EXCEEDED, + ); + expect(machine.canTransition('draft', 'send', { activeInvites: 2 })).toBe(false); + }); +}); diff --git a/backend/src/services/invites.ts b/backend/src/services/invites.ts new file mode 100644 index 00000000..bdfc06ec --- /dev/null +++ b/backend/src/services/invites.ts @@ -0,0 +1,516 @@ +/** + * backend/src/services/invites.ts + * + * Issue #2255: one shared, typed state machine for every household-invite flow. + * + * Both the API (this file) and the React Native client + * (`mobile/src/features/invites/index.ts`) import this module, so the set of + * invite states, the legal transitions between them and the guards that reject + * illegal ones live in exactly one place. A client can therefore ask + * "can I accept this invite?" and the server will apply the very same rule. + * + * Lifecycle: + * + * draft --send--> pending --accept--> accepted + * |--decline--> declined + * |--expire --> expired + * `--revoke --> revoked + * + * The four terminal states have no outgoing transitions. Expiry is decided by + * an injectable clock (`nowMs`), never by `Date.now()` inside a guard, which + * keeps the machine deterministic and unit-testable. + * + * Zero dependencies and no I/O: every export is pure (observability is done + * through injected no-op-by-default hooks). + */ + +/** All invite states, in lifecycle order. Frozen. */ +export const INVITE_STATES = Object.freeze([ + 'draft', + 'pending', + 'accepted', + 'declined', + 'expired', + 'revoked', +] as const); + +/** A single invite state. */ +export type InviteState = (typeof INVITE_STATES)[number]; + +/** All invite events, frozen. */ +export const INVITE_EVENTS = Object.freeze([ + 'send', + 'accept', + 'decline', + 'expire', + 'revoke', +] as const); + +/** An event that can be applied to an invite. */ +export type InviteEvent = (typeof INVITE_EVENTS)[number]; + +/** States from which no further transition is legal. Frozen. */ +export const TERMINAL_INVITE_STATES = Object.freeze([ + 'accepted', + 'declined', + 'expired', + 'revoked', +] as const); + +/** Stable, machine-readable error codes. Frozen. */ +export const InviteErrorCode = Object.freeze({ + INVALID_STATE: 'INVALID_STATE', + INVALID_EVENT: 'INVALID_EVENT', + INVALID_TRANSITION: 'INVALID_TRANSITION', + INVALID_CONFIG: 'INVALID_CONFIG', + INVALID_INPUT: 'INVALID_INPUT', + INVITE_EXPIRED: 'INVITE_EXPIRED', + MAX_ACTIVE_EXCEEDED: 'MAX_ACTIVE_EXCEEDED', +} as const); + +/** Union of {@link InviteErrorCode} values. */ +export type InviteErrorCode = (typeof InviteErrorCode)[keyof typeof InviteErrorCode]; + +/** + * Error thrown for every rejected invite operation. + * + * The `code` is stable and safe to expose to clients; `details` carries + * non-sensitive context (states, events, limits) for logging and tests. + */ +export class InviteError extends Error { + /** Stable machine-readable code. */ + readonly code: InviteErrorCode; + /** Additional non-sensitive context about the rejection. */ + readonly details: Readonly>; + + constructor(code: InviteErrorCode, message: string, details: Readonly> = {}) { + super(message); + this.name = 'InviteError'; + this.code = code; + this.details = Object.freeze({ ...details }); + } +} + +/** Tunable policy for an invite machine. */ +export interface InviteConfig { + /** Time-to-live of a freshly issued invite, in milliseconds. */ + readonly ttlMs: number; + /** Maximum number of simultaneously pending invites per household. */ + readonly maxActivePerHousehold: number; +} + +/** Default policy: one week TTL, ten concurrently pending invites. Frozen. */ +export const DEFAULT_INVITE_CONFIG: Readonly = Object.freeze({ + ttlMs: 7 * 24 * 60 * 60 * 1000, + maxActivePerHousehold: 10, +}); + +/** Context available to guards while evaluating a transition. */ +export interface InviteTransitionContext { + /** Current time in milliseconds. Defaults to `Date.now()`. */ + readonly nowMs?: number; + /** Expiry timestamp of the invite in milliseconds, when one has been issued. */ + readonly expiresAt?: number; + /** Number of currently pending invites for the household. */ + readonly activeInvites?: number; + /** Overrides `config.maxActivePerHousehold` for this transition. */ + readonly maxActivePerHousehold?: number; + /** Optional actor identifier, forwarded to metrics/logging only. */ + readonly actor?: string; +} + +/** Observability hooks called on accepted and rejected transitions. */ +export interface InviteMetrics { + /** Called after a transition succeeds. */ + transition(from: InviteState, event: InviteEvent, to: InviteState): void; + /** Called after a transition is rejected by a guard. */ + rejection(code: InviteErrorCode, from: InviteState, event: InviteEvent): void; +} + +/** No-op metrics, safe to use in pure/browser contexts. Frozen. */ +export const noopInviteMetrics: InviteMetrics = Object.freeze({ + transition() {}, + rejection() {}, +}); + +/** Minimal structured logger interface. Receives no secrets. */ +export interface InviteLogger { + /** Emit a debug-level event with optional non-sensitive context. */ + debug(message: string, details?: Readonly>): void; +} + +/** No-op logger. Frozen. */ +export const noopInviteLogger: InviteLogger = Object.freeze({ + debug() {}, +}); + +/** + * The single transition table. `undefined` means "no legal transition", which + * is turned into an {@link InviteErrorCode.INVALID_TRANSITION} error. + */ +const TRANSITION_TABLE: Readonly< + Record>>> +> = Object.freeze({ + draft: Object.freeze({ send: 'pending' }), + pending: Object.freeze({ + accept: 'accepted', + decline: 'declined', + expire: 'expired', + revoke: 'revoked', + }), + accepted: Object.freeze({}), + declined: Object.freeze({}), + expired: Object.freeze({}), + revoked: Object.freeze({}), +}); + +/** Input accepted by {@link normalizeInvite}. */ +export interface InviteInput { + /** Stable invite identifier. Must be a non-empty string. */ + readonly id: string; + /** Household the invite belongs to. Must be a non-empty string. */ + readonly householdId: string; + /** Desired state; defaults to `draft`. */ + readonly state?: unknown; + /** Opaque invite token; defaults to `inv_`. */ + readonly token?: string; + /** Issue time in milliseconds; defaults to `nowMs`. */ + readonly issuedAt?: number; + /** Expiry time in milliseconds; defaults to `issuedAt + config.ttlMs`. */ + readonly expiresAt?: number; +} + +/** A normalized, fully populated invite record. All fields are read-only. */ +export interface Invite { + readonly id: string; + readonly householdId: string; + readonly state: InviteState; + readonly token: string; + readonly issuedAt: number; + readonly expiresAt: number; +} + +/** Result of a successful transition (kept for callers that want detail). */ +export interface InviteTransitionResult { + readonly from: InviteState; + readonly event: InviteEvent; + readonly to: InviteState; + readonly changed: boolean; +} + +/** A bound invite machine. */ +export interface InviteMachine { + /** Apply `event` to `state`, throwing {@link InviteError} on rejection. */ + transition(state: InviteState, event: InviteEvent, ctx?: InviteTransitionContext): InviteState; + /** Whether the transition (including its guards) would succeed. */ + canTransition(state: InviteState, event: InviteEvent, ctx?: InviteTransitionContext): boolean; + /** All states, shared and frozen. */ + readonly states: readonly InviteState[]; + /** The validated, frozen configuration in use. */ + readonly config: Readonly; +} + +/** Type guard for {@link InviteState}. */ +export function isInviteState(value: unknown): value is InviteState { + return typeof value === 'string' && (INVITE_STATES as readonly string[]).includes(value); +} + +/** Type guard for {@link InviteEvent}. */ +export function isInviteEvent(value: unknown): value is InviteEvent { + return typeof value === 'string' && (INVITE_EVENTS as readonly string[]).includes(value); +} + +/** Whether a state is terminal (accept/decline/expire/revoke are final). */ +export function isTerminalInviteState(state: InviteState): boolean { + return (TERMINAL_INVITE_STATES as readonly string[]).includes(state); +} + +/** + * Pure expiry check against an injectable clock. + * + * @param expiresAt Expiry timestamp in milliseconds. + * @param nowMs Current time in milliseconds (defaults to `Date.now()`). + */ +export function isInviteExpired(expiresAt: number, nowMs: number = Date.now()): boolean { + if (!Number.isFinite(expiresAt) || !Number.isFinite(nowMs)) { + throw new InviteError(InviteErrorCode.INVALID_INPUT, 'expiresAt and nowMs must be finite numbers', { + expiresAt, + nowMs, + }); + } + return nowMs >= expiresAt; +} + +function fail( + code: InviteErrorCode, + message: string, + details: Readonly>, + from: InviteState, + event: InviteEvent, + metrics: InviteMetrics, + logger: InviteLogger, +): never { + const error = new InviteError(code, message, details); + metrics.rejection(code, from, event); + logger.debug('invite transition rejected', { from, event, code, details }); + throw error; +} + +function runTransition( + state: InviteState, + event: InviteEvent, + ctx: InviteTransitionContext, + config: Readonly, + metrics: InviteMetrics, + logger: InviteLogger, +): InviteState { + if (!isInviteState(state)) { + throw new InviteError(InviteErrorCode.INVALID_STATE, `Unknown invite state: ${String(state)}`, { + state, + }); + } + if (!isInviteEvent(event)) { + throw new InviteError(InviteErrorCode.INVALID_EVENT, `Unknown invite event: ${String(event)}`, { + event, + }); + } + + const next = TRANSITION_TABLE[state][event]; + if (next === undefined) { + fail( + InviteErrorCode.INVALID_TRANSITION, + `Cannot ${event} an invite in state ${state}`, + { state, event }, + state, + event, + metrics, + logger, + ); + } + + const now = ctx.nowMs ?? Date.now(); + if (!Number.isFinite(now)) { + fail( + InviteErrorCode.INVALID_INPUT, + 'nowMs must be a finite number', + { nowMs: ctx.nowMs }, + state, + event, + metrics, + logger, + ); + } + + if (event === 'send') { + const max = ctx.maxActivePerHousehold ?? config.maxActivePerHousehold; + const active = ctx.activeInvites ?? 0; + if (!Number.isFinite(max) || max < 1) { + fail( + InviteErrorCode.INVALID_CONFIG, + 'maxActivePerHousehold must be at least 1', + { max }, + state, + event, + metrics, + logger, + ); + } + if (!Number.isFinite(active) || active < 0) { + fail( + InviteErrorCode.INVALID_INPUT, + 'activeInvites must be a non-negative finite number', + { active }, + state, + event, + metrics, + logger, + ); + } + if (active >= max) { + fail( + InviteErrorCode.MAX_ACTIVE_EXCEEDED, + `Household already has ${active} active invites (limit ${max})`, + { active, max }, + state, + event, + metrics, + logger, + ); + } + } + + if (event === 'accept' && ctx.expiresAt !== undefined) { + if (!Number.isFinite(ctx.expiresAt)) { + fail( + InviteErrorCode.INVALID_INPUT, + 'expiresAt must be a finite number', + { expiresAt: ctx.expiresAt }, + state, + event, + metrics, + logger, + ); + } + if (now >= ctx.expiresAt) { + fail( + InviteErrorCode.INVITE_EXPIRED, + `Invite expired at ${ctx.expiresAt} (now ${now})`, + { expiresAt: ctx.expiresAt, nowMs: now }, + state, + event, + metrics, + logger, + ); + } + } + + metrics.transition(state, event, next); + logger.debug('invite transition applied', { from: state, event, to: next, actor: ctx.actor }); + return next; +} + +/** + * Apply `event` to `state` using the default configuration and no-op hooks. + * + * @throws {@link InviteError} for unknown states/events, illegal transitions or + * failed guards. + */ +export function transition( + state: InviteState, + event: InviteEvent, + ctx: InviteTransitionContext = {}, +): InviteState { + return runTransition(state, event, ctx, DEFAULT_INVITE_CONFIG, noopInviteMetrics, noopInviteLogger); +} + +/** + * Whether a transition would succeed, including all guards. Never throws. + */ +export function canTransition( + state: InviteState, + event: InviteEvent, + ctx: InviteTransitionContext = {}, +): boolean { + try { + runTransition(state, event, ctx, DEFAULT_INVITE_CONFIG, noopInviteMetrics, noopInviteLogger); + return true; + } catch { + return false; + } +} + +/** + * Normalize untrusted invite input into a frozen, complete record. + * + * Defaults: `state` becomes `draft`, `issuedAt` becomes `nowMs`, `expiresAt` + * becomes `issuedAt + config.ttlMs`, and `token` becomes `inv_`. + * + * @throws {@link InviteError} for missing identifiers, unknown states or + * malformed timestamps. + */ +export function normalizeInvite( + input: InviteInput, + nowMs: number = Date.now(), + config: Readonly = DEFAULT_INVITE_CONFIG, +): Invite { + if (!input || typeof input !== 'object') { + throw new InviteError(InviteErrorCode.INVALID_INPUT, 'invite input must be an object'); + } + if (typeof input.id !== 'string' || input.id.trim().length === 0) { + throw new InviteError(InviteErrorCode.INVALID_INPUT, 'id must be a non-empty string', { + id: input.id, + }); + } + if (typeof input.householdId !== 'string' || input.householdId.trim().length === 0) { + throw new InviteError(InviteErrorCode.INVALID_INPUT, 'householdId must be a non-empty string', { + householdId: input.householdId, + }); + } + if (!Number.isFinite(nowMs)) { + throw new InviteError(InviteErrorCode.INVALID_INPUT, 'nowMs must be a finite number', { nowMs }); + } + + const state: InviteState = input.state === undefined ? 'draft' : (input.state as InviteState); + if (!isInviteState(state)) { + throw new InviteError(InviteErrorCode.INVALID_STATE, `Unknown invite state: ${String(state)}`, { + state: input.state, + }); + } + + const issuedAt = input.issuedAt ?? nowMs; + const expiresAt = input.expiresAt ?? issuedAt + config.ttlMs; + if (!Number.isFinite(issuedAt) || !Number.isFinite(expiresAt)) { + throw new InviteError(InviteErrorCode.INVALID_INPUT, 'issuedAt and expiresAt must be finite numbers', { + issuedAt, + expiresAt, + }); + } + if (expiresAt < issuedAt) { + throw new InviteError(InviteErrorCode.INVALID_INPUT, 'expiresAt must not precede issuedAt', { + issuedAt, + expiresAt, + }); + } + + const token = input.token ?? `inv_${input.id}`; + if (typeof token !== 'string' || token.length === 0) { + throw new InviteError(InviteErrorCode.INVALID_INPUT, 'token must be a non-empty string', { token }); + } + + return Object.freeze({ + id: input.id.trim(), + householdId: input.householdId.trim(), + state, + token, + issuedAt, + expiresAt, + }); +} + +function validateConfig(config: Readonly): void { + if ( + !Number.isFinite(config.ttlMs) || + config.ttlMs <= 0 || + !Number.isFinite(config.maxActivePerHousehold) || + config.maxActivePerHousehold < 1 + ) { + throw new InviteError(InviteErrorCode.INVALID_CONFIG, 'Invalid invite configuration', { + ttlMs: config.ttlMs, + maxActivePerHousehold: config.maxActivePerHousehold, + }); + } +} + +/** + * Create a bound machine with a custom configuration and observability hooks. + * + * @param config Partial overrides merged onto {@link DEFAULT_INVITE_CONFIG}. + * @param metrics Called on every successful/rejected transition. + * @param logger Receives non-sensitive debug events. + */ +export function createInviteMachine( + config: Partial = {}, + metrics: InviteMetrics = noopInviteMetrics, + logger: InviteLogger = noopInviteLogger, +): InviteMachine { + const merged: Readonly = Object.freeze({ + ...DEFAULT_INVITE_CONFIG, + ...config, + }); + validateConfig(merged); + + const machine: InviteMachine = { + transition: (state, event, ctx = {}) => runTransition(state, event, ctx, merged, metrics, logger), + canTransition: (state, event, ctx = {}) => { + try { + runTransition(state, event, ctx, merged, metrics, logger); + return true; + } catch { + return false; + } + }, + states: INVITE_STATES, + config: merged, + }; + return Object.freeze(machine); +} diff --git a/mobile/src/features/invites/__tests__/index.test.ts b/mobile/src/features/invites/__tests__/index.test.ts new file mode 100644 index 00000000..8fde2e29 --- /dev/null +++ b/mobile/src/features/invites/__tests__/index.test.ts @@ -0,0 +1,48 @@ +import { + INVITE_STATES, + InviteError, + InviteErrorCode, + transition, + inviteStatusLabel, + isTerminal, + buildInviteDeepLink, + type InviteState, +} from '../index'; + +describe('mobile invite adapter (#2255)', () => { + it('re-exports the shared vocabulary and machine', () => { + expect(INVITE_STATES).toContain('pending'); + expect(transition('draft', 'send')).toBe('pending'); + }); + + it('labels every state', () => { + expect(inviteStatusLabel('draft')).toBe('Draft'); + expect(inviteStatusLabel('pending')).toBe('Pending'); + expect(inviteStatusLabel('accepted')).toBe('Accepted'); + expect(inviteStatusLabel('declined')).toBe('Declined'); + expect(inviteStatusLabel('expired')).toBe('Expired'); + expect(inviteStatusLabel('revoked')).toBe('Revoked'); + expect(inviteStatusLabel('nope' as InviteState)).toBe('Unknown'); + }); + + it('delegates terminal-state detection', () => { + expect(isTerminal('accepted')).toBe(true); + expect(isTerminal('revoked')).toBe(true); + expect(isTerminal('draft')).toBe(false); + expect(isTerminal('pending')).toBe(false); + }); + + it('builds an encoded deep link', () => { + expect(buildInviteDeepLink('abc 123/')).toBe('subtrackr://invite/abc%20123%2F'); + }); + + it('rejects an empty token with a typed error', () => { + try { + buildInviteDeepLink(''); + throw new Error('expected throw'); + } catch (e) { + expect(e).toBeInstanceOf(InviteError); + expect((e as InviteError).code).toBe(InviteErrorCode.INVALID_INPUT); + } + }); +}); diff --git a/mobile/src/features/invites/index.ts b/mobile/src/features/invites/index.ts new file mode 100644 index 00000000..7faca393 --- /dev/null +++ b/mobile/src/features/invites/index.ts @@ -0,0 +1,106 @@ +/** + * mobile/src/features/invites/index.ts + * + * Issue #2255: mobile adapter for the shared household-invite state machine. + * + * This module is the single mobile entry point for invite state handling. It + * re-exports the backend machine verbatim (via the relative `.ts` path below) + * and adds a few device-facing helpers. Because both platforms import the same + * backend module, invite states and transitions cannot drift between the app + * and the API. + * + * Zero dependencies, no React imports, no I/O — safe to unit-test in Node. + */ + +import { + INVITE_STATES, + INVITE_EVENTS, + TERMINAL_INVITE_STATES, + InviteErrorCode, + InviteError, + DEFAULT_INVITE_CONFIG, + transition, + canTransition, + normalizeInvite, + createInviteMachine, + isInviteState, + isInviteEvent, + isInviteExpired, + isTerminalInviteState, + noopInviteMetrics, + noopInviteLogger, + type InviteState, + type InviteEvent, + type InviteConfig, + type InviteInput, + type Invite, + type InviteMetrics, + type InviteLogger, + type InviteMachine, + type InviteTransitionContext, + type InviteTransitionResult, +} from '../../../../backend/src/services/invites.ts'; + +export { + INVITE_STATES, + INVITE_EVENTS, + TERMINAL_INVITE_STATES, + InviteErrorCode, + InviteError, + DEFAULT_INVITE_CONFIG, + transition, + canTransition, + normalizeInvite, + createInviteMachine, + isInviteState, + isInviteEvent, + isInviteExpired, + isTerminalInviteState, + noopInviteMetrics, + noopInviteLogger, + type InviteState, + type InviteEvent, + type InviteConfig, + type InviteInput, + type Invite, + type InviteMetrics, + type InviteLogger, + type InviteMachine, + type InviteTransitionContext, + type InviteTransitionResult, +}; + +/** Human-readable label for an invite state, used by status badges. */ +export function inviteStatusLabel(state: InviteState): string { + switch (state) { + case 'draft': + return 'Draft'; + case 'pending': + return 'Pending'; + case 'accepted': + return 'Accepted'; + case 'declined': + return 'Declined'; + case 'expired': + return 'Expired'; + case 'revoked': + return 'Revoked'; + default: + return 'Unknown'; + } +} + +/** Whether no further action is possible for an invite in this state. */ +export function isTerminal(state: InviteState): boolean { + return isTerminalInviteState(state); +} + +/** Build the in-app deep link that opens the accept/decline screen for a token. */ +export function buildInviteDeepLink(token: string): string { + if (typeof token !== 'string' || token.length === 0) { + throw new InviteError(InviteErrorCode.INVALID_INPUT, 'token must be a non-empty string', { + token, + }); + } + return `subtrackr://invite/${encodeURIComponent(token)}`; +}