diff --git a/cloud-v2/packages/runtime/src/services/audio/providers/audioTimeline.test.ts b/cloud-v2/packages/runtime/src/services/audio/providers/audioTimeline.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2aeca8a2b3d150e0f916f5bbcc374e5025be0fac --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/providers/audioTimeline.test.ts @@ -0,0 +1,17 @@ +import { expect, test } from "bun:test"; +import { AudioTimeline } from "./audioTimeline"; + +test("provider samples map back to submitted frames despite gaps, loss and session changes", () => { + const timeline = new AudioTimeline(); + timeline.add(160, { sessionTag: 1, offsetMs: 100 }); + timeline.add(160, { sessionTag: 1, offsetMs: 140 }); + expect(timeline.at(5)).toEqual({ sessionTag: 1, offsetMs: 105 }); + expect(timeline.at(10)).toEqual({ sessionTag: 1, offsetMs: 140 }); + timeline.add(160, { sessionTag: 2, offsetMs: 0 }); + expect(timeline.at(20)).toEqual({ sessionTag: 2, offsetMs: 0 }); + timeline.prune(10); + expect(timeline.at(0)).toBeUndefined(); + timeline.reset(); + timeline.add(160, { sessionTag: 2, offsetMs: 90 }); + expect(timeline.at(0)).toEqual({ sessionTag: 2, offsetMs: 90 }); +}); diff --git a/cloud-v2/packages/runtime/src/services/audio/providers/audioTimeline.ts b/cloud-v2/packages/runtime/src/services/audio/providers/audioTimeline.ts new file mode 100644 index 0000000000000000000000000000000000000000..279dedd00e81ca897ba6cdf672cd7bdfc3e33ab1 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/providers/audioTimeline.ts @@ -0,0 +1,36 @@ +import type { AudioPosition } from "@mentra/cloud-protocol"; + +/** Maps Soniox's contiguous submitted-sample clock back to phone frame positions. */ +export class AudioTimeline { + private endMs = 0; + private spans: Array<{ + start: number; + end: number; + position?: AudioPosition; + }> = []; + + add(sampleCount: number, position?: AudioPosition): void { + const end = this.endMs + sampleCount / 16; + this.spans.push({ start: this.endMs, end, position }); + this.endMs = end; + } + + at(startMs: number): AudioPosition | undefined { + const span = this.spans.find((s) => startMs >= s.start && startMs < s.end); + return ( + span?.position && { + sessionTag: span.position.sessionTag, + offsetMs: span.position.offsetMs + startMs - span.start, + } + ); + } + + prune(beforeMs: number): void { + this.spans = this.spans.filter((s) => s.end > beforeMs); + } + + reset(): void { + this.endMs = 0; + this.spans = []; + } +} diff --git a/cloud-v2/packages/runtime/src/services/audio/providers/mock.ts b/cloud-v2/packages/runtime/src/services/audio/providers/mock.ts new file mode 100644 index 0000000000000000000000000000000000000000..55234453205847f10192c037de140ccc3a294ead --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/providers/mock.ts @@ -0,0 +1,65 @@ +/** + * @fileoverview MockProvider — synthetic transcripts for tests and local dev. + * + * Emits a deterministic transcript on every `writeAudio` call so end-to-end + * tests can verify "PCM reached a provider and a transcript flowed back" + * without depending on a real ASR API. + * + * Text format: `mock ` where `n` increments per write. Includes + * the scope (typically the user identifier) so multi-user tests can confirm + * routing didn't cross-talk. + */ + +import type { + ProviderOptions, + TranscriptionProvider, +} from "./provider"; + +export interface CreateMockProviderOptions extends ProviderOptions { + /** + * If true, emit one interim then one final per write (mimics a real ASR + * that streams partials). Default: false — single final per write. + */ + emitInterim?: boolean; +} + +export async function createMockProvider( + opts: CreateMockProviderOptions, +): Promise { + let writeCount = 0; + let totalSamples = 0; + let closed = false; + + return { + name: "mock", + writeAudio(pcm: Int16Array): void { + if (closed) return; + writeCount++; + // Audio is 16kHz mono Int16 → 16 samples per millisecond. + const startMs = Math.round(totalSamples / 16); + totalSamples += pcm.length; + const endMs = Math.round(totalSamples / 16); + const text = `mock ${opts.scope} ${writeCount}`; + + if (opts.emitInterim) { + opts.onTranscript({ + text, + isFinal: false, + startMs, + endMs, + language: opts.language, + }); + } + opts.onTranscript({ + text, + isFinal: true, + startMs, + endMs, + language: opts.language, + }); + }, + async close(): Promise { + closed = true; + }, + }; +} diff --git a/cloud-v2/packages/runtime/src/services/audio/providers/provider.ts b/cloud-v2/packages/runtime/src/services/audio/providers/provider.ts new file mode 100644 index 0000000000000000000000000000000000000000..18e16d9ae1d6514d829466c5dbe6845f66a53f78 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/providers/provider.ts @@ -0,0 +1,85 @@ +/** + * @fileoverview Transcription provider interface. + * + * Abstracts the "PCM in, transcript out" pipeline so we can swap between: + * - `MockProvider` for tests + local dev (no API key needed) + * - `SonioxProvider` (next iteration) wrapping `@soniox/node` + * - Future: alternative ASR vendors as failover or for specific languages + * + * Lifecycle: + * const provider = await createMockProvider({ onTranscript: handler }); + * provider.writeAudio(pcm); // many times + * await provider.close(); // on detach + * + * Callbacks are passed at construction time (set-and-forget). Providers + * don't expose subscribe/unsubscribe — there's one handler per provider + * instance, owned by the worker that created it. + */ + +import type { AudioPosition, TranscriptionToken } from "@mentra/cloud-protocol"; + +export interface TranscriptEvent { + frameTimelineVersion?: 1; + /** Transcribed text. May be a partial token or a complete word/phrase. */ + text: string; + /** Whether the provider considers this finalized (vs. interim/in-progress). */ + isFinal: boolean; + /** + * Stable id for the utterance this event belongs to. Interim and final + * events for the same speech segment share one id so the client can + * correlate them and update a single card in place, then commit it on + * the final. Reset at each utterance boundary (endpoint / speaker change). + */ + utteranceId?: string; + /** Speaker id if the provider reports diarization (e.g. `"1"`, `"2"`). */ + speakerId?: string; + /** Audio timeline window this transcript covers, in milliseconds. */ + startMs?: number; + endMs?: number; + /** ISO language code if the provider reports it (e.g. `"en"`). */ + language?: string; + /** + * For translation: the source-language text of the same window, when the + * provider supplies original tokens alongside the translated ones. Lets a + * client render combined original + translated captions from one stream. + */ + originalText?: string; + /** + * For translation: the DETECTED source-audio language (e.g. `"en"`), taken + * from the original-language tokens. `language` carries the language of + * `text` (the target language), so the detected source needs its own field. + */ + sourceLanguage?: string; + /** Internal timing retained for phone-runtime subscription projection. */ + tokens?: TranscriptionToken[]; +} + +export interface ProviderOptions { + /** Identifier for logging — typically the user's `mentraUserId`. */ + scope: string; + /** Source language (`"auto"` for detection, otherwise BCP-47 code). */ + language: string; + /** + * Optional detection hints for `language: "auto"` — bare ISO 639-1 codes + * ("en", "ja") that bias language identification without pinning it. Ignored + * for a specific `language` (the language itself is the hint there). Carries + * the miniapp's `transcription.configure({languageHints})` through to the + * provider (issue 021). + */ + languageHints?: string[]; + /** Fired when the provider has a transcript event to emit. */ + onTranscript: (event: TranscriptEvent) => void; + /** Fired on provider-side errors. Worker logs + decides whether to recreate. */ + onError?: (err: Error) => void; +} + +export interface TranscriptionProvider { + /** Feed a PCM (Int16 mono, 16kHz) chunk. Non-blocking. */ + writeAudio(pcm: Int16Array, position?: AudioPosition): void; + + /** Close cleanly. Best-effort flushes any pending interim transcripts. */ + close(): Promise; + + /** Provider identifier for diagnostics — `"mock"`, `"soniox"`, etc. */ + readonly name: string; +} diff --git a/cloud-v2/packages/runtime/src/services/audio/providers/soniox.auth.test.ts b/cloud-v2/packages/runtime/src/services/audio/providers/soniox.auth.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e633a3a7819be60e694f68f25d83f11e99e6067 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/providers/soniox.auth.test.ts @@ -0,0 +1,108 @@ +import {describe, expect, test} from "bun:test"; +import {createRequire} from "node:module"; +import {SonioxNodeClient} from "@soniox/node"; + +import {createSonioxProvider} from "./soniox"; +import type {TranscriptEvent, TranscriptionProvider} from "./provider"; + +const require = createRequire(import.meta.url); +const clients: Array<[string, typeof SonioxNodeClient]> = [ + ["ESM", SonioxNodeClient], + ["CommonJS", require("@soniox/node").SonioxNodeClient], +]; + +async function waitUntil(check: () => boolean): Promise { + const deadline = Date.now() + 5_000; + while (!check()) { + if (Date.now() >= deadline) throw new Error("Timed out waiting for Soniox session"); + await Bun.sleep(10); + } +} + +describe("Soniox connection authentication", () => { + for (const [format, Client] of clients) { + for (const targetLanguage of [undefined, "es"] as const) { + test(`${format}: ${targetLanguage ? "translation" : "transcription"} authenticates initial and replacement sessions`, async () => { + const apiKey = "soniox-auth-test-key"; + const connections: string[] = []; + const configs: Array> = []; + const events: TranscriptEvent[] = []; + let upstream: Bun.ServerWebSocket | undefined; + let provider: TranscriptionProvider | undefined; + const server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request, server) { + const protocols = request.headers.get("sec-websocket-protocol") ?? ""; + // Simulate the post-deadline service: refuse connections without + // connection authentication, even if a later message has api_key. + if (protocols.split(",").map((p) => p.trim()).join(",") !== `soniox-api-key,${apiKey}`) { + return new Response("Unauthenticated", {status: 401}); + } + connections.push(protocols); + if (server.upgrade(request, {headers: {"Sec-WebSocket-Protocol": "soniox-api-key"}})) return; + return new Response("Upgrade required", {status: 400}); + }, + websocket: { + open(ws) { + upstream = ws; + }, + message(ws, message) { + if (message === "") { + ws.send(JSON.stringify({tokens: [], finished: true})); + } else if (typeof message === "string") { + const config = JSON.parse(message); + if (config.model) configs.push(config); + } else { + ws.send(JSON.stringify({tokens: [ + {text: targetLanguage ? "Hola" : "Hello", is_final: true, confidence: 1, + language: targetLanguage ?? "en", + ...(targetLanguage ? {translation_status: "translation"} : {})}, + {text: "", is_final: true, confidence: 1}, + ]})); + } + }, + }, + }); + try { + provider = await createSonioxProvider({ + scope: "auth-test", + language: "en", + targetLanguage, + client: new Client({api_key: apiKey, realtime: { + ws_base_url: `ws://127.0.0.1:${server.port}`, + }}), + onTranscript: (event) => events.push(event), + }); + await waitUntil(() => configs.length === 1); + provider.writeAudio(new Int16Array(160)); + await waitUntil(() => events.some((event) => event.isFinal)); + upstream!.close(1011, "test reconnect"); + await waitUntil(() => configs.length === 2); + const beforeReconnectAudio = events.length; + provider.writeAudio(new Int16Array(160)); + await waitUntil(() => events.length > beforeReconnectAudio); + + expect(connections).toHaveLength(2); + for (const config of configs) { + expect(config).not.toHaveProperty("api_key"); + expect(config.model).toBe(process.env.SONIOX_MODEL ?? "stt-rt-v5"); + expect(config.audio_format).toBe("pcm_s16le"); + if (targetLanguage) { + expect(config.translation).toEqual({type: "one_way", target_language: "es"}); + } else { + expect(config).not.toHaveProperty("translation"); + } + } + expect(events.at(-1)?.text).toBe(targetLanguage ? "Hola" : "Hello"); + } finally { + try { + await provider?.close(); + } finally { + server.stop(true); + } + } + }, 15_000); + } + } +}); diff --git a/cloud-v2/packages/runtime/src/services/audio/providers/soniox.test.ts b/cloud-v2/packages/runtime/src/services/audio/providers/soniox.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1f5dc3a87e6c43aa555e9a277278265535eb8e6 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/providers/soniox.test.ts @@ -0,0 +1,861 @@ +/** + * @fileoverview Tests for SonioxProvider's utterance lifecycle. + * + * Focus: the transcript pile-up bug. Soniox delivers a ROLLING WINDOW that it + * RE-DIARIZES across results, so a token's `speaker` label can flip between + * rounds within ONE real utterance. The provider must NOT finalize / mint a new + * utteranceId on that per-token flicker — it must emit interims under a single + * stable utteranceId and commit exactly one FINAL on the Soniox `endpoint` + * boundary (or on close()). + * + * We inject a fake Soniox client/session so we can drive `result` / `endpoint` + * events deterministically without a network or API key. + */ +import { describe, test, expect } from "bun:test"; + +// Shrink the self-heal backoff so reconnect tests run in milliseconds. Read +// per-provider inside createSonioxProvider, so setting it here (before any +// provider is constructed) is sufficient. +process.env.SONIOX_RECONNECT_BASE_MS = "1"; +process.env.SONIOX_RECONNECT_MAX_MS = "4"; +process.env.SONIOX_RECONNECT_MAX_ATTEMPTS = "5"; +process.env.SONIOX_ENDPOINT_DEBOUNCE_MS = "1"; + +import { createSonioxProvider, sonioxLanguageHints, sonioxTranslationTarget } from "./soniox"; +import type { TranscriptEvent } from "./provider"; + +// Minimal shape of a Soniox realtime token we care about in these tests. +type FakeToken = { + text: string; + confidence: number; + is_final: boolean; + speaker?: string; + language?: string; + start_ms?: number; + end_ms?: number; + /** Set on translation-session tokens; absent for same-language passthrough. */ + translation_status?: "original" | "translation"; +}; + +/** + * A fake `RealtimeSttSession` that records event handlers so the test can + * synthesize Soniox `result` / `endpoint` events. Stands in for the real + * `@soniox/node` session, which is otherwise a live WebSocket. + */ +class FakeSession { + private handlers = new Map void>>(); + + on(event: string, handler: (arg?: unknown) => void): this { + const list = this.handlers.get(event) ?? []; + list.push(handler); + this.handlers.set(event, list); + return this; + } + + off(event: string, handler: (arg?: unknown) => void): this { + const list = this.handlers.get(event); + if (list) this.handlers.set(event, list.filter((h) => h !== handler)); + return this; + } + + emit(event: string, arg?: unknown): void { + for (const h of this.handlers.get(event) ?? []) h(arg); + } + + // Lifecycle methods the provider calls. Instrumented so self-heal tests can + // assert connect/sendAudio/close behavior and inject a connect failure. + connectCount = 0; + sendAudioCount = 0; + closeCount = 0; + pauseCount = 0; + resumeCount = 0; + /** When > 0, the next N connect() calls reject (simulate a flaky reconnect). */ + failNextConnects = 0; + + async connect(): Promise { + this.connectCount += 1; + if (this.failNextConnects > 0) { + this.failNextConnects -= 1; + throw new Error("fake connect failure"); + } + } + sendAudio(): void { + this.sendAudioCount += 1; + } + pause(): void { + this.pauseCount += 1; + this.emit("finalized"); + } + resume(): void { + this.resumeCount += 1; + } + async finish(): Promise {} + async close(): Promise { + this.closeCount += 1; + } + + /** Simulate an unexpected upstream drop (not triggered by our close()). */ + disconnect(reason = "upstream closed"): void { + this.emit("disconnected", reason); + } + + /** Convenience: push a Soniox result with the given rolling token window. */ + result(tokens: FakeToken[]): void { + this.emit("result", { tokens }); + } + + /** Convenience: fire the endpoint (real utterance boundary). */ + endpoint(): void { + this.emit("endpoint"); + } +} + +/** Build a fake SonioxNodeClient whose `realtime.stt()` returns our session. */ +function fakeClient(session: FakeSession): any { + return { + realtime: { + stt: () => session, + }, + }; +} + +/** + * A fake client that hands out a NEW session per `realtime.stt()` call, in + * order. Mirrors the real client, which mints a fresh session each call — the + * self-heal path builds a replacement session, so the test needs more than one. + * Records every session it produced so the test can drive/inspect them. + */ +function multiSessionClient(): { client: any; sessions: FakeSession[] } { + const sessions: FakeSession[] = []; + const client = { + realtime: { + stt: () => { + const s = new FakeSession(); + sessions.push(s); + return s; + }, + }, + }; + return { client, sessions }; +} + +/** Resolve after `ms` of real time (kept small so tests stay fast). */ +function wait(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function withFastGapConfig(fn: () => Promise): Promise { + const prevCheck = process.env.SONIOX_GAP_CHECK_INTERVAL_MS; + const prevThreshold = process.env.SONIOX_AUDIO_GAP_THRESHOLD_MS; + process.env.SONIOX_GAP_CHECK_INTERVAL_MS = "5"; + process.env.SONIOX_AUDIO_GAP_THRESHOLD_MS = "20"; + try { + return await fn(); + } finally { + if (prevCheck == null) { + delete process.env.SONIOX_GAP_CHECK_INTERVAL_MS; + } else { + process.env.SONIOX_GAP_CHECK_INTERVAL_MS = prevCheck; + } + if (prevThreshold == null) { + delete process.env.SONIOX_AUDIO_GAP_THRESHOLD_MS; + } else { + process.env.SONIOX_AUDIO_GAP_THRESHOLD_MS = prevThreshold; + } + } +} + +async function makeProvider(): Promise<{ + session: FakeSession; + events: TranscriptEvent[]; + provider: Awaited>; +}> { + const session = new FakeSession(); + const events: TranscriptEvent[] = []; + const provider = await createSonioxProvider({ + scope: "user_test", + language: "auto", + client: fakeClient(session) as never, + onTranscript: (e) => events.push(e), + }); + return { session, events, provider }; +} + +async function makeTranslationProvider(target: string): Promise<{ + session: FakeSession; + events: TranscriptEvent[]; + provider: Awaited>; +}> { + const session = new FakeSession(); + const events: TranscriptEvent[] = []; + const provider = await createSonioxProvider({ + scope: "user_xlate_test", + language: "auto", + targetLanguage: target, + client: fakeClient(session) as never, + onTranscript: (e) => events.push(e), + }); + return { session, events, provider }; +} + +describe("SonioxProvider translation same-language passthrough", () => { + test("untagged tokens (spoken language == target) emit as transcription text with their source language", async () => { + const { session, events, provider } = await makeTranslationProvider("es-ES"); + + // Soniox emits NO translation_status when there is nothing to translate + // (verified live: EN speech -> target en). Simulate Spanish speech with a + // Spanish target: plain untagged tokens. + session.result([ + { text: "Hola ", confidence: 0.9, is_final: false, language: "es" }, + { text: "mundo", confidence: 0.9, is_final: false, language: "es" }, + ]); + session.endpoint(); + await wait(5); + + const finals = events.filter((e) => e.isFinal); + expect(finals.length).toBe(1); + expect(finals[0]!.text).toBe("Hola mundo"); + expect(finals[0]!.sourceLanguage).toBe("es"); + expect(finals[0]!.originalText).toBeUndefined(); + + await provider.close(); + }); + + test("cross-language windows still emit only the translation half with originalText", async () => { + const { session, events, provider } = await makeTranslationProvider("es-ES"); + + session.result([ + { text: "Hello ", confidence: 0.9, is_final: false, language: "en", translation_status: "original" }, + { text: "world", confidence: 0.9, is_final: false, language: "en", translation_status: "original" }, + { text: "Hola ", confidence: 0.9, is_final: false, language: "es", translation_status: "translation" }, + { text: "mundo", confidence: 0.9, is_final: false, language: "es", translation_status: "translation" }, + ]); + session.endpoint(); + await wait(5); + + const finals = events.filter((e) => e.isFinal); + expect(finals.length).toBe(1); + expect(finals[0]!.text).toBe("Hola mundo"); + expect(finals[0]!.originalText).toBe("Hello world"); + expect(finals[0]!.sourceLanguage).toBe("en"); + + await provider.close(); + }); +}); + +describe("sonioxLanguageHints", () => { + test("a specific language becomes its own bare-code hint (region stripped)", () => { + expect(sonioxLanguageHints("fr-FR", undefined)).toEqual(["fr"]); + expect(sonioxLanguageHints("en-US", ["ja"])).toEqual(["en"]); // specific wins; hints ignored + expect(sonioxLanguageHints("ZH-hans", undefined)).toEqual(["zh"]); + }); + + test("auto with no hints yields undefined (never a BCP-47 tag)", () => { + expect(sonioxLanguageHints("auto", undefined)).toBeUndefined(); + expect(sonioxLanguageHints("auto", [])).toBeUndefined(); + expect(sonioxLanguageHints(undefined, undefined)).toBeUndefined(); + }); + + test("auto passes detection hints, reduced to bare codes and deduped", () => { + expect(sonioxLanguageHints("auto", ["en", "ja"])).toEqual(["en", "ja"]); + expect(sonioxLanguageHints("auto", ["en-US", "en-GB"])).toEqual(["en"]); + expect(sonioxLanguageHints("auto", ["fr-FR", "ja"])).toEqual(["fr", "ja"]); + }); +}); + +describe("sonioxTranslationTarget", () => { + test("strips the region to a bare code (Soniox rejects BCP-47 targets)", () => { + expect(sonioxTranslationTarget("es-ES")).toBe("es"); + expect(sonioxTranslationTarget("zh-CN")).toBe("zh"); + expect(sonioxTranslationTarget("en")).toBe("en"); + expect(sonioxTranslationTarget("PT-BR")).toBe("pt"); + }); +}); + +describe("SonioxProvider session configuration", () => { + test("configures one-way translation with a bare target_language", async () => { + const session = new FakeSession(); + let sessionConfig: Record | undefined; + const client = { + realtime: { + stt: (config: Record) => { + sessionConfig = config; + return session; + }, + }, + }; + + const provider = await createSonioxProvider({ + scope: "user_xlate", + language: "auto", + targetLanguage: "es-ES", + client: client as never, + onTranscript: () => {}, + }); + + expect(sessionConfig).toMatchObject({ + translation: { type: "one_way", target_language: "es" }, + }); + + await provider.close(); + }); + + test("passes auto-mode detection hints to Soniox language_hints", async () => { + const session = new FakeSession(); + let sessionConfig: Record | undefined; + const client = { + realtime: { + stt: (config: Record) => { + sessionConfig = config; + return session; + }, + }, + }; + + const provider = await createSonioxProvider({ + scope: "user_hints", + language: "auto", + languageHints: ["ja", "en-US"], + client: client as never, + onTranscript: () => {}, + }); + + expect(sessionConfig).toMatchObject({ + enable_language_identification: true, + language_hints: ["ja", "en"], + }); + + await provider.close(); + }); + + test("sends the Mentra activation phrase as recognition context", async () => { + const session = new FakeSession(); + let sessionConfig: Record | undefined; + const client = { + realtime: { + stt: (config: Record) => { + sessionConfig = config; + return session; + }, + }, + }; + + const provider = await createSonioxProvider({ + scope: "user_test", + language: "auto", + client: client as never, + onTranscript: () => {}, + }); + + expect(sessionConfig).toMatchObject({ + context: { + terms: ["Mentra", "Hey Mentra"], + text: "Mentra, Hey Mentra (an AI assistant)", + }, + }); + + await provider.close(); + }); +}); + +describe("SonioxProvider utterance lifecycle", () => { + test("endpoint character overlap keeps token timing without losing interim/final text", async () => { + const {session, provider, events} = await makeProvider(); + try { + provider.writeAudio(new Int16Array(480), {sessionTag: 1, offsetMs: 0}); + session.result([{text: "Hello wonderful world", confidence: 1, is_final: false, start_ms: 0, end_ms: 10}]); + session.endpoint(); + session.result([{text: "wonderful world again", confidence: 1, is_final: false, start_ms: 10, end_ms: 20}]); + const interim = events.at(-1)!; + expect(interim.text).toBe("Hello wonderful world again"); + expect(interim.tokens?.map((t) => t.text).join("")).toBe(interim.text); + expect(interim.tokens?.at(-1)?.audioPosition).toEqual({sessionTag: 1, offsetMs: 10}); + session.emit("finalized"); + expect(events.at(-1)?.tokens?.map((t) => t.text).join("")).toBe("Hello wonderful world again"); + } finally {await provider.close()} + }); + test("timing survives repeated/compacted windows, endpoint merge and mapping pruning", async () => { + const {session, events, provider} = await makeProvider(); + const word = (text: string, start_ms: number): FakeToken => ({ + text, start_ms, end_ms: start_ms + 10, confidence: 1, is_final: true, + }); + try { + provider.writeAudio(new Int16Array(320), {sessionTag: 1, offsetMs: 100}); + provider.writeAudio(new Int16Array(320), {sessionTag: 1, offsetMs: 120}); + const before = word("BEFORE ", 0), after = word("AFTER", 10), more = word(" MORE", 20); + session.emit("result", {tokens: [before, after], final_audio_proc_ms: 20}); + session.endpoint(); + session.result([before, after, more]); + session.result([more]); + session.emit("finalized"); + const final = events.at(-1)!; + expect(final.text).toBe("BEFORE AFTER MORE"); + expect(final.tokens?.map((t) => t.text)).toEqual(["BEFORE ", "AFTER", " MORE"]); + expect(final.tokens?.map((t) => t.audioPosition)).toEqual([ + {sessionTag: 1, offsetMs: 100}, {sessionTag: 1, offsetMs: 110}, {sessionTag: 1, offsetMs: 120}, + ]); + expect(events.filter((event) => event.isFinal)).toHaveLength(1); + } finally {await provider.close()} + }); + + test("provider replacement restarts its sample clock without reusing old frame positions", async () => { + const {client, sessions} = multiSessionClient(); + const events: TranscriptEvent[] = []; + const provider = await createSonioxProvider({scope: "timed-heal", language: "auto", client: client as never, onTranscript: (event) => events.push(event)}); + const timed = (text: string): FakeToken => ({text, confidence: 1, is_final: true, start_ms: 0, end_ms: 10}); + try { + provider.writeAudio(new Int16Array(160), {sessionTag: 1, offsetMs: 10}); + sessions[0]!.result([timed("BEFORE ")]); + sessions[0]!.disconnect(); + await wait(50); + provider.writeAudio(new Int16Array(160), {sessionTag: 1, offsetMs: 100}); + sessions[1]!.result([timed("AFTER")]); + expect(events.at(-1)?.text).toBe("BEFORE AFTER"); + expect(events.at(-1)?.tokens?.map((t) => t.audioPosition?.offsetMs)).toEqual([10, 100]); + } finally {await provider.close()} + }); + + test("retains timed confirmed tokens and replaces interims through the final", async () => { + const session = new FakeSession(); + const events: TranscriptEvent[] = []; + const provider = await createSonioxProvider({ + scope: "timing", + language: "auto", + client: fakeClient(session), + onTranscript: (event) => events.push(event), + }); + try { + provider.writeAudio(new Int16Array(160), { sessionTag: 1, offsetMs: 0 }); + provider.writeAudio(new Int16Array(320), { sessionTag: 1, offsetMs: 20 }); + const before = { + text: "BEFORE ", + is_final: true, + confidence: 1, + start_ms: 0, + end_ms: 10, + }; + session.result([ + before, + { + text: "guess", + is_final: false, + confidence: 1, + start_ms: 10, + end_ms: 20, + }, + ]); + session.result([ + { + text: "AFTER", + is_final: true, + confidence: 1, + start_ms: 10, + end_ms: 20, + }, + ]); + expect(events.at(-1)?.text).toBe("BEFORE AFTER"); + expect( + events.at(-1)?.tokens?.map((token) => token.audioPosition), + ).toEqual([ + { sessionTag: 1, offsetMs: 0 }, + { sessionTag: 1, offsetMs: 20 }, + ]); + session.emit("finalized"); + expect(events.at(-1)?.isFinal).toBe(true); + expect(events.at(-1)?.tokens?.map((token) => token.text)).toEqual([ + "BEFORE ", + "AFTER", + ]); + expect(events.at(-1)?.tokens?.every((token) => token.isFinal)).toBe(true); + expect(events.at(-1)?.frameTimelineVersion).toBe(1); + } finally { + await provider.close(); + } + }); + test("missing token timing retains the negotiated occurrence capability through its final", async () => { + const {session, provider, events} = await makeProvider(); + try { + provider.writeAudio(new Int16Array(160), {sessionTag: 1, offsetMs: 0}); + session.result([{text: "unknown", confidence: 1, is_final: false}]); + expect(events.at(-1)?.frameTimelineVersion).toBe(1); + expect(events.at(-1)?.tokens).toEqual([]); + session.endpoint(); + // A legacy frame arriving while the prior final is pending does not + // change that positioned occurrence's missing-timing policy. + provider.writeAudio(new Int16Array(160)); + session.emit("finalized"); + expect(events.at(-1)?.frameTimelineVersion).toBe(1); + expect(events.at(-1)?.tokens).toEqual([]); + } finally {await provider.close()} + }); + test("does not churn finals/utteranceIds when the rolling window's speaker flips mid-utterance", async () => { + const { session, events, provider } = await makeProvider(); + + // Round 1: rolling window where the (single, non-final) token is speaker "1". + session.result([ + { text: "Okay ", confidence: 0.9, is_final: false, speaker: "1" }, + ]); + + // Round 2: SAME logical utterance, but Soniox re-diarized the window — the + // first token now reads speaker "2", and more text has streamed in. Under + // the old per-token speaker-compare this would emitFinal + mint a new id. + session.result([ + { text: "Okay ", confidence: 0.9, is_final: false, speaker: "2" }, + { text: "um I should ", confidence: 0.9, is_final: false, speaker: "2" }, + ]); + + // Round 3: window keeps growing, speaker flips back to "1" — still one + // logical utterance, no endpoint yet. + session.result([ + { text: "Okay um I should ", confidence: 0.9, is_final: false, speaker: "1" }, + { text: "buy my ticket", confidence: 0.9, is_final: false, speaker: "1" }, + ]); + + // Before the endpoint: every event so far must be an interim, all sharing + // ONE utteranceId. No finals, no new ids — i.e. no pile-up. + expect(events.length).toBeGreaterThan(0); + expect(events.every((e) => e.isFinal === false)).toBe(true); + const interimIds = new Set(events.map((e) => e.utteranceId)); + expect(interimIds.size).toBe(1); + const utteranceId = events[0]!.utteranceId; + expect(utteranceId).toBeDefined(); + + // The interim text grows in place (cumulative) under the same card. + expect(events.at(-1)!.text).toBe("Okay um I should buy my ticket"); + + // Now the real utterance boundary fires: exactly ONE final, same id. + session.endpoint(); + await wait(5); + + const finals = events.filter((e) => e.isFinal); + expect(finals.length).toBe(1); + expect(finals[0]!.utteranceId).toBe(utteranceId); + expect(finals[0]!.text).toBe("Okay um I should buy my ticket"); + + await provider.close(); + }); + + test("emits one final per endpoint-bounded utterance and starts a fresh id after", async () => { + const { session, events, provider } = await makeProvider(); + + // Utterance A. + session.result([ + { text: "first utterance", confidence: 0.9, is_final: false, speaker: "1" }, + ]); + session.endpoint(); + + // Utterance B (after a commit, a fresh id is minted lazily on next token). + session.result([ + { text: "second utterance", confidence: 0.9, is_final: false, speaker: "1" }, + ]); + session.endpoint(); + await wait(5); + + const finals = events.filter((e) => e.isFinal); + expect(finals.length).toBe(2); + expect(finals[0]!.text).toBe("first utterance"); + expect(finals[1]!.text).toBe("second utterance"); + // Distinct utterances → distinct ids. + expect(finals[0]!.utteranceId).not.toBe(finals[1]!.utteranceId); + + await provider.close(); + }); + + test("merges a repeated rolling window after endpoint instead of emitting a duplicate utterance", async () => { + const { session, events, provider } = await makeProvider(); + + session.result([ + { text: "Can you hear me?", confidence: 0.9, is_final: false, speaker: "1" }, + ]); + const utteranceId = events.at(-1)!.utteranceId; + + // Soniox can fire an endpoint, then keep the previous words in the next + // rolling window. This is the exact shape that produced a duplicate local + // captions card in E2E testing. + session.endpoint(); + session.result([ + { text: " Can", confidence: 0.9, is_final: false, speaker: "1" }, + ]); + session.result([ + { + text: " Can you hear me? What did you do?", + confidence: 0.9, + is_final: false, + speaker: "1", + }, + ]); + session.endpoint(); + await wait(5); + + const finals = events.filter((e) => e.isFinal); + expect(finals.length).toBe(1); + expect(finals[0]!.utteranceId).toBe(utteranceId); + expect(finals[0]!.text).toBe("Can you hear me? What did you do?"); + + const ids = new Set(events.map((e) => e.utteranceId)); + expect(ids.size).toBe(1); + + await provider.close(); + }); + + test("keeps fuller interim when Soniox later emits a shorter finalized window", async () => { + const { session, events, provider } = await makeProvider(); + + const fullText = + "Two app fan out test, local captions and local merge should both receive this final transcript."; + const regressedText = + "Two app fan out test, local cap both receive this final transcript."; + + session.result([ + { text: fullText, confidence: 0.9, is_final: false, speaker: "1" }, + ]); + session.result([ + { text: regressedText, confidence: 0.9, is_final: true, speaker: "1" }, + ]); + session.endpoint(); + await wait(5); + + expect(events.some((e) => e.text === regressedText)).toBe(false); + expect(events.at(-1)).toMatchObject({ + text: fullText, + isFinal: true, + }); + + await provider.close(); + }); + + test("does not reuse the first utterance id across provider instances with the same scope", async () => { + const sessionA = new FakeSession(); + const eventsA: TranscriptEvent[] = []; + const providerA = await createSonioxProvider({ + scope: "user_test", + language: "auto", + client: fakeClient(sessionA) as never, + onTranscript: (e) => eventsA.push(e), + }); + + const sessionB = new FakeSession(); + const eventsB: TranscriptEvent[] = []; + const providerB = await createSonioxProvider({ + scope: "user_test", + language: "auto", + client: fakeClient(sessionB) as never, + onTranscript: (e) => eventsB.push(e), + }); + + sessionA.result([ + { text: "first provider", confidence: 0.9, is_final: false, speaker: "1" }, + ]); + sessionB.result([ + { text: "second provider", confidence: 0.9, is_final: false, speaker: "1" }, + ]); + + expect(eventsA[0]!.utteranceId).toBeDefined(); + expect(eventsB[0]!.utteranceId).toBeDefined(); + expect(eventsA[0]!.utteranceId).not.toBe(eventsB[0]!.utteranceId); + + await providerA.close(); + await providerB.close(); + }); + + test("close() flushes an in-flight utterance as a single final", async () => { + const { session, events, provider } = await makeProvider(); + + session.result([ + { text: "dangling text", confidence: 0.9, is_final: false, speaker: "3" }, + ]); + + // No endpoint — detach mid-utterance. close() should commit it once. + await provider.close(); + + const finals = events.filter((e) => e.isFinal); + expect(finals.length).toBe(1); + expect(finals[0]!.text).toBe("dangling text"); + }); +}); + +describe("SonioxProvider audio-gap pause/resume", () => { + test("auto-pauses after an idle audio gap and commits buffered interim text", async () => { + await withFastGapConfig(async () => { + const { session, events, provider } = await makeProvider(); + + session.result([ + { text: "pending words", confidence: 0.9, is_final: false, speaker: "1" }, + ]); + const utteranceId = events.at(-1)!.utteranceId; + + await wait(50); + + expect(session.pauseCount).toBe(1); + const finals = events.filter((e) => e.isFinal); + expect(finals.length).toBe(1); + expect(finals[0]!.text).toBe("pending words"); + expect(finals[0]!.utteranceId).toBe(utteranceId); + + await provider.close(); + }); + }); + + test("resumes before sending the first audio chunk after an idle pause", async () => { + await withFastGapConfig(async () => { + const { session, provider } = await makeProvider(); + + await wait(50); + expect(session.pauseCount).toBe(1); + + provider.writeAudio(new Int16Array([1, 2, 3, 4])); + + expect(session.resumeCount).toBe(1); + expect(session.sendAudioCount).toBe(1); + + await provider.close(); + }); + }); + + test("does not auto-pause repeatedly while already paused", async () => { + await withFastGapConfig(async () => { + const { session, provider } = await makeProvider(); + + await wait(80); + + expect(session.pauseCount).toBe(1); + + await provider.close(); + }); + }); +}); + +/** + * Self-heal: the "captions freeze after a hostile network drop" wedge. + * + * The underlying Soniox session can die WITHOUT our close() (network blip, + * Soniox idle timeout). The provider object stays in the worker's per-user + * provider map, keyed by subscription identity, and the worker's reconcile is + * idempotent by that key — so it never recreates the provider. Without + * self-heal, audio keeps flowing into the dead session and transcripts stop + * until a full app restart forces a real detach. These tests assert the + * provider reconnects its own session in place and resumes emitting. + */ +describe("SonioxProvider self-heal reconnect", () => { + test("resumes transcripts after an unexpected upstream disconnect", async () => { + const { client, sessions } = multiSessionClient(); + const events: TranscriptEvent[] = []; + const provider = await createSonioxProvider({ + scope: "user_heal", + language: "auto", + client: client as never, + onTranscript: (e) => events.push(e), + }); + + const first = sessions[0]!; + // Transcripts flow on the original session. + first.result([{ text: "hello", confidence: 0.9, is_final: false, speaker: "1" }]); + expect(events.at(-1)!.text).toBe("hello"); + + // The upstream session dies unexpectedly (the hostile-drop wedge). + first.disconnect(); + + // The provider should build + connect a replacement session. + await wait(50); + expect(sessions.length).toBe(2); + const second = sessions[1]!; + expect(second.connectCount).toBe(1); + + // Audio that arrives after the heal must reach the NEW session, and its + // transcripts must reach the consumer — captions resume, no restart needed. + provider.writeAudio(new Int16Array([1, 2, 3, 4])); + expect(second.sendAudioCount).toBe(1); + second.result([{ text: "world", confidence: 0.9, is_final: false, speaker: "1" }]); + expect(events.at(-1)!.text).toBe("world"); + + await provider.close(); + }); + + test("retries with backoff when a reconnect attempt fails, then succeeds", async () => { + // Mint sessions where the FIRST replacement's connect() rejects once, so the + // self-heal loop must back off and try again before it gets a live session. + const sessions: FakeSession[] = []; + let nextFailCount = 0; + const client = { + realtime: { + stt: () => { + const s = new FakeSession(); + s.failNextConnects = nextFailCount; + nextFailCount = 0; + sessions.push(s); + return s; + }, + }, + }; + const errors: Error[] = []; + const provider = await createSonioxProvider({ + scope: "user_retry", + language: "auto", + client: client as never, + onTranscript: () => {}, + onError: (e) => errors.push(e), + }); + + const first = sessions[0]!; + // Arm the next-built session to fail its first connect, then drop the live + // one. Heal builds replacement #1 (connect rejects) → backs off → builds + // replacement #2 (connect ok). + nextFailCount = 1; + first.disconnect(); + + await wait(80); + + // At least two replacements were built (the failed one + the live one), and + // self-heal did NOT give up (no error surfaced). + expect(sessions.length).toBeGreaterThanOrEqual(3); + expect(errors.length).toBe(0); + + // The final session is live and takes audio. + const last = sessions.at(-1)!; + provider.writeAudio(new Int16Array([1, 2])); + expect(last.sendAudioCount).toBe(1); + + await provider.close(); + }); + + test("does NOT reconnect on an expected close()", async () => { + const { client, sessions } = multiSessionClient(); + const provider = await createSonioxProvider({ + scope: "user_close", + language: "auto", + client: client as never, + onTranscript: () => {}, + }); + + // close() finishes the session, which fires a `disconnected` on the real + // SDK. That expected disconnect must NOT spin up a replacement session. + await provider.close(); + sessions[0]!.disconnect(); // late teardown event, post-close + await wait(30); + + expect(sessions.length).toBe(1); + }); + + test("drops audio frames while a reconnect is in flight", async () => { + const { client, sessions } = multiSessionClient(); + const provider = await createSonioxProvider({ + scope: "user_gap", + language: "auto", + client: client as never, + onTranscript: () => {}, + // Slow the heal so we can observe the in-flight window. + onError: () => {}, + }); + + const first = sessions[0]!; + first.disconnect(); + // Immediately after the drop, before the replacement connects, frames are + // dropped (no live session to take them) — no throw, no send on the dead one. + const beforeSends = first.sendAudioCount; + provider.writeAudio(new Int16Array([9, 9])); + expect(first.sendAudioCount).toBe(beforeSends); + + await wait(50); + await provider.close(); + }); + }); diff --git a/cloud-v2/packages/runtime/src/services/audio/providers/soniox.ts b/cloud-v2/packages/runtime/src/services/audio/providers/soniox.ts new file mode 100644 index 0000000000000000000000000000000000000000..68a23a310250986bf1d62826adae86b188ae5040 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/providers/soniox.ts @@ -0,0 +1,1062 @@ +/** + * @fileoverview SonioxProvider — real Soniox streaming transcription. + * + * Wraps `@soniox/node`'s `RealtimeSttSession` behind the cloud-v2 + * `TranscriptionProvider` interface. One Soniox session per active + * subscription (per user). Sends PCM as it arrives, emits transcripts + * back via the provider callback. + * + * Configuration: + * - Requires `SONIOX_API_KEY` env var. + * - Model defaults to `"stt-rt-v5"`; override via `SONIOX_MODEL`. + * - Audio format hardcoded to s16le, 16kHz, mono (matches our LC3 output). + * + * What this does NOT include (deferred from v1's SonioxSdkStream port): + * - Endpoint debounce / merge (mid-utterance endpoint suppression) + * - Token compaction handling beyond what the SDK does + * + * Those land as we hit them in real-traffic testing. The minimum here is + * enough to produce real transcripts from real audio; refinements come from + * observing actual usage. + * + * Spec: docs/issues/003-audio/design.md. + */ + +import { + SonioxNodeClient, + type RealtimeResult, + type RealtimeSttSession, + type SttSessionConfig, +} from "@soniox/node"; +import { randomUUID } from "node:crypto"; + +import type { + ProviderOptions, + TranscriptionProvider, + TranscriptEvent, +} from "./provider"; +import { createLogger } from "@mentra/cloud-shared"; +import type { AudioPosition, TranscriptionToken } from "@mentra/cloud-protocol"; +import { AudioTimeline } from "./audioTimeline"; + +const logger = createLogger("runtime").child({ module: "soniox" }); + +const SONIOX_MODEL = process.env.SONIOX_MODEL ?? "stt-rt-v5"; + +/** Preserve timing through the adapter's existing overlap merge; never guess alignment. */ +function mergeTimedTokens( + text: string, + left: TranscriptionToken[], + right: TranscriptionToken[], +): TranscriptionToken[] { + const a = left + .map((t) => t.text) + .join("") + .trim(); + const b = right + .map((t) => t.text) + .join("") + .trim(); + if (text === b) return right; + if (text === a) return left; + // The existing text merger can overlap inside a provider token. Remove + // duplicated characters without inventing a later timestamp for that token. + // Its retained suffix keeps the original start and crossing tokens remain + // excluded by the phone subscription cutoff. + const slice = (tokens: TranscriptionToken[], start: number, end: number) => { + let offset = 0; + return tokens.flatMap((token) => { + const from = Math.max(0, start - offset); + const to = Math.min(token.text.length, end - offset); + offset += token.text.length; + return to > from ? [{...token, text: token.text.slice(from, to)}] : []; + }); + }; + const rawLeft = left.map((token) => token.text).join(""); + const rawRight = right.map((token) => token.text).join(""); + const suffix = text.slice(a.length); + if (text.startsWith(a) && b.endsWith(suffix)) { + const prefixTokens = slice(left, rawLeft.indexOf(a), rawLeft.indexOf(a) + a.length); + const suffixStart = rawRight.indexOf(b) + b.length - suffix.length; + return [...prefixTokens, ...slice(right, suffixStart, suffixStart + suffix.length)]; + } + return []; +} +function audioGapConfig(): { checkIntervalMs: number; thresholdMs: number } { + return { + checkIntervalMs: Number(process.env.SONIOX_GAP_CHECK_INTERVAL_MS ?? 1_000), + thresholdMs: Number(process.env.SONIOX_AUDIO_GAP_THRESHOLD_MS ?? 2_000), + }; +} + +function endpointDebounceMs(): number { + return Number(process.env.SONIOX_ENDPOINT_DEBOUNCE_MS ?? 500); +} + +const MIN_ENDPOINT_OVERLAP_CHARS = 3; +const MIN_REGRESSION_DROP_CHARS = 12; +const MIN_REGRESSION_PREFIX_CHARS = 12; + +/** + * Self-heal backoff for an unexpected Soniox session drop. + * + * The underlying Soniox WebSocket can die WITHOUT our `close()` being called: + * a network blip, a Soniox-side idle timeout, or a transient upstream error. + * When that happens the provider object is still held (alive) in the worker's + * per-user provider map, keyed by subscription identity — and the worker's + * reconcile is idempotent by that key, so it will NEVER recreate the provider. + * Audio keeps flowing into a dead session and transcripts silently stop. + * + * This is exactly the "captions freeze after a hostile network drop" wedge: a + * clean pod-roll recovers (it DETACHes the user → the provider map is cleared → + * a fresh ATTACH recreates providers), but a same-pod reconnect keeps the same + * worker + the same (now-dead) provider, so only a full app restart recovers. + * + * The fix is for the provider to reconnect its OWN Soniox session in place on an + * unexpected drop, so its identity in the worker map stays valid and transcripts + * resume without any teardown/recreate. Bounded retries with capped backoff; we + * give up (and surface onError) only after exhausting them. + */ +/** + * Read the self-heal backoff tunables. Read per-provider (not at module load) + * so tests can shrink the delays via env before constructing a provider; in + * production these are stable for the process lifetime. + */ +function reconnectConfig(): { baseMs: number; maxMs: number; maxAttempts: number } { + return { + baseMs: Number(process.env.SONIOX_RECONNECT_BASE_MS ?? 500), + maxMs: Number(process.env.SONIOX_RECONNECT_MAX_MS ?? 8_000), + maxAttempts: Number(process.env.SONIOX_RECONNECT_MAX_ATTEMPTS ?? 10), + }; +} + +export interface CreateSonioxProviderOptions extends ProviderOptions { + /** Provide the Soniox client to reuse a single client across multiple streams. */ + client?: SonioxNodeClient; + /** + * If set, configure Soniox one-way translation. Result tokens with + * `translation_status: "translation"` are emitted; original tokens are + * dropped. If unset, the provider behaves as a transcription stream + * (all tokens emitted as source-language text). + */ + targetLanguage?: string; +} + +/** + * Build Soniox `language_hints` from the subscription. A specific language is + * its own hint (region stripped: "en-US" -> "en"). For "auto" we pass the + * miniapp's detection hints, each reduced to Soniox's bare-code format and + * deduped; unknown/empty yields undefined (no hints). Passing a BCP-47 tag or + * an unrecognized code makes Soniox reject the session ("Invalid language + * hint"), so everything is normalized here (issue 021). + */ +export function sonioxLanguageHints( + language: string | undefined, + hints: string[] | undefined, +): string[] | undefined { + const toBareCode = (code: string) => code.split("-")[0].toLowerCase(); + if (language && language !== "auto") { + return [toBareCode(language)]; + } + if (!hints || hints.length === 0) return undefined; + const bare = [...new Set(hints.map(toBareCode).filter(Boolean))]; + return bare.length > 0 ? bare : undefined; +} + +/** + * Soniox one-way translation target. Like `language_hints`, Soniox's + * `translation.target_language` takes a bare ISO 639-1 code — a BCP-47 tag + * ("es-ES") is rejected with "Invalid language in translation.target_language" + * and kills the session, so strip the region (mirrors v1's SonioxSdkStream, + * which used `targetLanguage.split("-")[0]`). Subscription keys and result + * routing keep the full tag; only the provider config is reduced (issue 021). + */ +export function sonioxTranslationTarget(target: string): string { + return target.split("-")[0].toLowerCase(); +} + +/** Shared client per worker. Soniox SDK is happy with one client for many streams. */ +let sharedClient: SonioxNodeClient | null = null; +function getClient(): SonioxNodeClient { + if (sharedClient) return sharedClient; + const apiKey = process.env.SONIOX_API_KEY; + if (!apiKey) { + throw new Error( + "SONIOX_API_KEY is not set — required to use the soniox provider. Run Cloud V2 through Doppler with access to the cloud-v2/dev config.", + ); + } + sharedClient = new SonioxNodeClient({ api_key: apiKey }); + return sharedClient; +} + +export async function createSonioxProvider( + opts: CreateSonioxProviderOptions, +): Promise { + const client = opts.client ?? getClient(); + const gapConfig = audioGapConfig(); + const endpointDebounce = endpointDebounceMs(); + + // Build session config. For language="auto" we enable detection; for a + // specific code we pass it as hint with detection still on. (Letting + // Soniox identify even when hinted is robust to user accent / code-switch.) + // + // Endpoint detection + diarization mirror v1's SonioxSdkStream: + // `enable_endpoint_detection` makes Soniox emit an `` (surfaced here as + // the `endpoint` event) at natural utterance boundaries, which is our ONLY + // signal to commit a single FINAL per utterance (besides stream close). + // `enable_speaker_diarization` tags tokens with a `speaker` id used purely for + // the "Speaker N" label; a speaker change does NOT close an utterance, because + // Soniox re-diarizes its rolling window and the per-token speaker flickers + // mid-utterance (see handleResult for the full rationale). + // `max_endpoint_delay_ms` is the v2 SDK's analogue of v1's + // `max_non_final_tokens_duration_ms` (both bound how long Soniox waits before + // finalizing after speech ends); v1 used 2000ms. + const sessionConfig: SttSessionConfig = { + audio_format: "pcm_s16le", + sample_rate: 16_000, + num_channels: 1, + model: SONIOX_MODEL, + enable_language_identification: true, + enable_endpoint_detection: true, + enable_speaker_diarization: true, + max_endpoint_delay_ms: 2_000, + // Soniox hints take bare ISO 639-1 codes ("en"), but subscriptions carry + // BCP-47 tags ("en-US") — strip the region like v1's SonioxSdkStream did, + // or the hint is unrecognized and does nothing. For a specific language the + // language itself is the hint; for "auto" we pass the miniapp's detection + // hints (already bare codes) so language identification is biased without + // being pinned. + language_hints: sonioxLanguageHints(opts.language, opts.languageHints), + context: { + terms: ["Mentra", "Hey Mentra"], + text: "Mentra, Hey Mentra (an AI assistant)", + }, + // For translation subs, configure Soniox's one-way translation. Result + // tokens then carry `translation_status: "original" | "translation"` + // and we filter to the translation half. + translation: opts.targetLanguage + ? { type: "one_way", target_language: sonioxTranslationTarget(opts.targetLanguage) } + : undefined, + } as SttSessionConfig; + const isTranslation = !!opts.targetLanguage; + + // The live Soniox session. Mutable because we replace it on a self-heal + // reconnect (the old one is dead; a fresh `client.realtime.stt(...)` takes its + // place) while keeping THIS provider object — and therefore its identity in + // the worker's per-user provider map — stable. + let session: RealtimeSttSession = client.realtime.stt(sessionConfig); + + // True once `close()` has run. Gates the self-heal path so an expected + // teardown (our own `session.finish()` → `disconnected`) does not trigger a + // reconnect, and so a frame written after close is dropped, not sent. + let closed = false; + + // True while a self-heal reconnect is in flight. Audio written during this + // window is dropped (there is no live upstream session to take it); the rest + // of the pipeline already tolerates dropped frames during a reconnect. + let reconnecting = false; + let reconnectAttempts = 0; + let gapCheckInterval: ReturnType | null = null; + let lastAudioWriteTime = Date.now(); + let pausedForGap = false; + + // === Per-utterance state (ports v1's SonioxTranscriptionProvider) === + // + // Soniox emits a rolling token window where finalized tokens accumulate then + // may be compacted (pruned). To avoid the interim text shrinking under us we + // capture finalized text into `stablePrefix` and prepend it to non-final + // tokens on each result. All of this state is scoped to ONE utterance and is + // reset by `startNewUtterance` at each boundary. + let stablePrefix = ""; + const audioTimeline = new AudioTimeline(); + let providerGeneration = 0; + let confirmedTokens = new Map(); + let lastTokens: TranscriptionToken[] = []; + let pendingTokens: TranscriptionToken[] = []; + let pendingTokenGeneration = 0; + let lastEmittedTokens: TranscriptionToken[] = []; + let frameTimelineVersion: 1 | undefined; + let activeFrameTimelineVersion: 1 | undefined; + let pendingFrameTimelineVersion: 1 | undefined; + const emitTranscript = (event: TranscriptEvent): void => { + opts.onTranscript({ + ...event, + frameTimelineVersion: event.frameTimelineVersion ?? + (event.tokens?.some((token) => token.audioPosition) ? 1 : undefined), + }); + }; + let prevFinalLen = 0; + // Last interim string we emitted for this utterance. Doubles as the text we + // commit when an utterance closes (endpoint / speaker change), and as a + // dedupe guard so we don't re-emit an unchanged interim. + let lastSentInterim = ""; + + // Translation subs only: parallel accumulator for the ORIGINAL-language + // tokens of the same utterance (same rolling-window semantics as above), so + // results can carry `originalText` for combined original+translated captions. + // Also tracks the detected SOURCE language — translation-status tokens carry + // the TARGET language, so the source must come from the original tokens. + let originalStablePrefix = ""; + let originalPrevFinalLen = 0; + let lastOriginalText = ""; + let currentSourceLanguage: string | undefined = undefined; + + // Utterance correlation: interim + final events for one speech segment share + // a `utteranceId`, so the client (local-captions' `updateByUtteranceId`) + // keeps a single card and updates it in place, committing on the final. + let currentUtteranceId: string | null = null; + let currentSpeakerId: string | undefined = undefined; + let currentLanguage: string | undefined = undefined; + + // Soniox endpoint is a soft signal. It can fire while the SDK still carries + // the same rolling-window text into the next result, which previously caused + // a duplicate new utterance/card. Hold the candidate final briefly, and if + // following results overlap, keep extending the original utterance instead. + let pendingFinalText = ""; + let pendingFinalUtteranceId: string | null = null; + let pendingFinalSpeakerId: string | undefined = undefined; + let pendingFinalLanguage: string | undefined = undefined; + let pendingFinalOriginalText = ""; + let pendingFinalSourceLanguage: string | undefined = undefined; + let pendingFinalStartMs: number | undefined = undefined; + let pendingFinalEndMs: number | undefined = undefined; + let pendingFinalTimer: ReturnType | null = null; + + // Monotonic id minting: a provider-instance nonce prevents collisions when the + // cloud process/provider restarts with the same scope and sequence number. + // `opts.scope` (user + sub identity) keeps ids readable per subscription. + let utteranceSeq = 0; + const providerInstanceId = randomUUID(); + const mintUtteranceId = (): string => { + utteranceSeq += 1; + return `utt_${opts.scope}_${providerInstanceId}_${utteranceSeq}`; + }; + + const startNewUtterance = (speakerId?: string, language?: string): void => { + activeFrameTimelineVersion = frameTimelineVersion; + currentUtteranceId = mintUtteranceId(); + confirmedTokens = new Map(); + lastTokens = []; + lastEmittedTokens = []; + currentSpeakerId = speakerId; + currentLanguage = language; + stablePrefix = ""; + prevFinalLen = 0; + lastSentInterim = ""; + originalStablePrefix = ""; + originalPrevFinalLen = 0; + lastOriginalText = ""; + currentSourceLanguage = undefined; + }; + + const resetActiveUtterance = (): void => { + activeFrameTimelineVersion = undefined; + confirmedTokens = new Map(); + lastTokens = []; + lastEmittedTokens = []; + stablePrefix = ""; + prevFinalLen = 0; + lastSentInterim = ""; + originalStablePrefix = ""; + originalPrevFinalLen = 0; + lastOriginalText = ""; + currentSourceLanguage = undefined; + currentUtteranceId = null; + currentSpeakerId = undefined; + currentLanguage = undefined; + }; + + const emitFinalEvent = (event: { + text: string; + utteranceId?: string; + speakerId?: string; + language?: string; + originalText?: string; + sourceLanguage?: string; + startMs?: number; + endMs?: number; + tokens?: TranscriptionToken[]; + frameTimelineVersion?: 1; + }): void => { + emitTranscript({ + text: event.text, + isFinal: true, + utteranceId: event.utteranceId, + speakerId: event.speakerId, + language: event.language, + originalText: event.originalText || undefined, + sourceLanguage: event.sourceLanguage, + startMs: event.startMs, + endMs: event.endMs, + tokens: event.tokens?.map((token) => ({ ...token, isFinal: true })), + frameTimelineVersion: event.frameTimelineVersion, + }); + }; + + const clearPendingFinal = (): void => { + if (pendingFinalTimer) { + clearTimeout(pendingFinalTimer); + pendingFinalTimer = null; + } + pendingFinalText = ""; + pendingTokens = []; + pendingFrameTimelineVersion = undefined; + pendingFinalUtteranceId = null; + pendingFinalSpeakerId = undefined; + pendingFinalLanguage = undefined; + pendingFinalOriginalText = ""; + pendingFinalSourceLanguage = undefined; + pendingFinalStartMs = undefined; + pendingFinalEndMs = undefined; + }; + + const tryMergeOverlap = (a: string, b: string): string | null => { + const left = a.trim(); + const right = b.trim(); + if (!left || !right) return null; + if (left === right || left.startsWith(right)) return left; + if (right.startsWith(left)) return left + right.slice(left.length); + + const maxOverlap = Math.min(left.length, right.length); + for (let len = maxOverlap; len >= MIN_ENDPOINT_OVERLAP_CHARS; len -= 1) { + if (left.endsWith(right.slice(0, len))) { + return left + right.slice(len); + } + } + return null; + }; + + const isLikelyWindowRegression = (next: string, previous: string): boolean => { + const normalizedNext = next.trim(); + const normalizedPrevious = previous.trim(); + if (!normalizedNext || !normalizedPrevious) return false; + const drop = normalizedPrevious.length - normalizedNext.length; + if (drop < MIN_REGRESSION_DROP_CHARS) return false; + + let sharedPrefix = 0; + const maxPrefix = Math.min( + normalizedNext.length, + normalizedPrevious.length, + ); + while ( + sharedPrefix < maxPrefix && + normalizedNext[sharedPrefix] === normalizedPrevious[sharedPrefix] + ) { + sharedPrefix += 1; + } + + return ( + sharedPrefix >= + Math.min(MIN_REGRESSION_PREFIX_CHARS, normalizedNext.length) + ); + }; + + const commitPendingFinal = (): void => { + if (!pendingFinalText) { + clearPendingFinal(); + return; + } + + const committedText = pendingFinalText; + const committedUtteranceId = pendingFinalUtteranceId; + emitFinalEvent({ + text: committedText, + utteranceId: committedUtteranceId ?? undefined, + speakerId: pendingFinalSpeakerId, + language: pendingFinalLanguage, + originalText: pendingFinalOriginalText, + sourceLanguage: pendingFinalSourceLanguage, + startMs: pendingFinalStartMs, + endMs: pendingFinalEndMs, + tokens: pendingTokens, + frameTimelineVersion: pendingFrameTimelineVersion, + }); + if ( + committedUtteranceId && + currentUtteranceId === committedUtteranceId && + lastSentInterim.trim() === committedText + ) { + resetActiveUtterance(); + } + clearPendingFinal(); + }; + + const schedulePendingFinalCommit = (): void => { + if (pendingFinalTimer) clearTimeout(pendingFinalTimer); + pendingFinalTimer = setTimeout(() => { + commitPendingFinal(); + }, endpointDebounce); + }; + + const setPendingFinalFromActive = (text: string): void => { + pendingFinalText = text; + pendingTokens = lastEmittedTokens; + pendingTokenGeneration = providerGeneration; + pendingFrameTimelineVersion = activeFrameTimelineVersion; + pendingFinalUtteranceId = currentUtteranceId; + pendingFinalSpeakerId = currentSpeakerId; + pendingFinalLanguage = currentLanguage; + pendingFinalOriginalText = lastOriginalText; + pendingFinalSourceLanguage = currentSourceLanguage; + }; + + /** + * Commit the current utterance as a single FINAL and reset for the next one. + * Called only at a real utterance boundary: the Soniox `endpoint` event and + * stream `close()`. NOT on per-token speaker flicker (see handleResult). No-op + * if there is nothing buffered, so back-to-back boundaries don't emit empty + * finals. + */ + const emitFinal = (startMs?: number, endMs?: number): void => { + const text = lastSentInterim.trim(); + if (!text) { + // Nothing to commit; still close the utterance so the next token batch + // starts fresh. + resetActiveUtterance(); + return; + } + emitFinalEvent({ + text, + utteranceId: currentUtteranceId ?? undefined, + speakerId: currentSpeakerId, + language: currentLanguage, + originalText: lastOriginalText || undefined, + sourceLanguage: currentSourceLanguage, + startMs, + endMs, + tokens: lastEmittedTokens, + frameTimelineVersion: activeFrameTimelineVersion, + }); + // Reset for the next utterance. A fresh id is minted lazily when the next + // token arrives (see handleResult). + resetActiveUtterance(); + }; + + const handleResult = (result: RealtimeResult) => { + const allTokens = result.tokens ?? []; + + // For translation subs, split the window: translation-status tokens are + // the emitted `text` (target language); original-status tokens feed the + // parallel `originalText` accumulator and the detected SOURCE language. + // For transcription subs, keep everything (translation_status will be + // 'none' since we didn't request translation). + // + // SAME-LANGUAGE PASSTHROUGH (issue 021 / OS-1762): when the spoken + // language already equals the translation target, Soniox skips translation + // entirely and emits plain transcription tokens with NO translation_status + // (verified empirically 2026-07-21: EN speech -> target en yields only + // untagged tokens; EN -> es yields original/translation pairs). Keep those + // untagged tokens as emitted text so target-language speech surfaces as a + // transcription instead of silently vanishing. Because the SAME session + // makes both the detection and the translation decision, this cannot + // double-emit: an utterance either has translation tokens (cross-language) + // or untagged tokens (same-language), never both halves for one segment. + const tokens = isTranslation + ? allTokens.filter( + (t) => + (t as { translation_status?: string }).translation_status !== + "original", + ) + : allTokens; + const originalTokens = isTranslation + ? allTokens.filter( + (t) => + (t as { translation_status?: string }).translation_status === + "original", + ) + : []; + + let interimText = ""; + let language: string | undefined; + let startMs: number | undefined; + let endMs: number | undefined; + let currentFinalText = ""; + + for (const t of tokens) { + // First token of the stream (or first after a commit): open an utterance. + // + // IMPORTANT: we deliberately do NOT split the utterance when a token's + // `speaker` label differs from `currentSpeakerId`. Soniox delivers a + // ROLLING WINDOW that it RE-DIARIZES across results, so a given token's + // `speaker` can flicker/flip between rounds within one real utterance. + // The previous implementation called `emitFinal` + `startNewUtterance` on + // every such per-token change, which fired spuriously many times within a + // single utterance — committing a FINAL and minting a NEW utteranceId per + // partial. On the captions client that produced a pile-up of growing, + // cumulative cards (one per partial, uncorrelatable), worse with + // diarization. We instead finalize ONLY on the real utterance boundary: + // the Soniox `endpoint` event (`handleEndpoint`) and on `close()`. + // + // This mirrors the retired V1 Soniox stream behavior, whose `handleResult` + // used the LAST token's speaker for attribution and + // documents: "Speaker changes within the window do NOT rotate the + // utteranceId." Speaker is still tracked below for the "Speaker N" label; + // it just doesn't trigger a finalize/restart. + if (!currentUtteranceId) { + startNewUtterance(t.speaker, t.language ?? opts.language); + } + + // Track the latest token's speaker so the emitted interim/final carries + // the current (dominant) speaker for the label — without splitting. + if (t.speaker) currentSpeakerId = t.speaker; + // Track detected language for output but DON'T split the utterance on a + // language change — Soniox's per-token language can flap mid-utterance. + if (t.language) { + language = t.language; + currentLanguage = t.language; + // Untagged tokens on a translation session are the same-language + // passthrough: their language IS the detected source. (Cross-language + // source tracking comes from the original-token loop below.) + if ( + isTranslation && + (t as { translation_status?: string }).translation_status == null + ) { + currentSourceLanguage = t.language; + } + } + + if (t.is_final) { + currentFinalText += t.text; + if (t.start_ms != null && startMs == null) startMs = t.start_ms; + if (t.end_ms != null) endMs = t.end_ms; + } else { + interimText += t.text; + } + } + + // Original-language tokens (translation subs only): same rolling-window + // accumulation as the main stream, into the parallel buffers. The first + // original token may arrive before any translation token; the utterance is + // opened lazily by either stream above, and `originalText` simply rides + // along on whichever emit happens next. + if (originalTokens.length > 0) { + let originalInterim = ""; + let originalFinal = ""; + for (const t of originalTokens) { + if (!currentUtteranceId) { + startNewUtterance(t.speaker, undefined); + } + if (t.language) currentSourceLanguage = t.language; + if (t.is_final) originalFinal += t.text; + else originalInterim += t.text; + } + if (originalFinal.length > originalPrevFinalLen) { + originalStablePrefix += originalFinal.slice(originalPrevFinalLen); + } + originalPrevFinalLen = originalFinal.length; + const originalComposite = originalStablePrefix + originalInterim; + if (originalComposite.length > 0) lastOriginalText = originalComposite; + } + + // Accumulate finalized text. On window growth, append the delta. On + // shrink (compaction), keep stablePrefix; reset tracker to new length. + if (currentFinalText.length > prevFinalLen) { + stablePrefix += currentFinalText.slice(prevFinalLen); + } + prevFinalLen = currentFinalText.length; + + const timed = tokens.filter( + (t) => t.text !== "" && t.text !== "", + ); + const hasTiming = + !isTranslation && + timed.length > 0 && + timed.every((t) => t.start_ms != null && t.end_ms != null); + if (hasTiming) { + for (const t of timed.filter((t) => t.is_final)) { + const key = `${providerGeneration}:${t.start_ms}:${t.end_ms}:${t.text}`; + confirmedTokens.set(key, { + text: t.text, + startMs: t.start_ms!, + endMs: t.end_ms!, + confidence: t.confidence, + isFinal: true, + speaker: t.speaker, + detectedLanguage: t.language, + audioPosition: + confirmedTokens.get(key)?.audioPosition ?? + (pendingTokenGeneration === providerGeneration + ? pendingTokens.find((token) => token.startMs === t.start_ms && token.endMs === t.end_ms && token.text === t.text)?.audioPosition + : undefined) ?? + audioTimeline.at(t.start_ms!), + }); + } + lastTokens = [ + ...confirmedTokens.values(), + ...timed + .filter((t) => !t.is_final) + .map((t) => ({ + text: t.text, + startMs: t.start_ms!, + endMs: t.end_ms!, + confidence: t.confidence, + isFinal: false, + speaker: t.speaker, + detectedLanguage: t.language, + audioPosition: audioTimeline.at(t.start_ms!), + })), + ]; + } else if (timed.length > 0) { + lastTokens = []; + } + if (result.final_audio_proc_ms > 0) + audioTimeline.prune(result.final_audio_proc_ms); + const compositeText = hasTiming || (!isTranslation && timed.length === 0 && lastTokens.length > 0) + ? lastTokens + .map((t) => t.text) + .join("") + .trim() + : (stablePrefix + interimText).trim(); + if (compositeText.length === 0) return; + + if (pendingFinalText && pendingFinalTimer) { + const pendingBefore = pendingFinalText; + const merged = tryMergeOverlap(pendingFinalText, compositeText); + if (merged !== null) { + currentUtteranceId = pendingFinalUtteranceId ?? currentUtteranceId; + if (currentSpeakerId) pendingFinalSpeakerId = currentSpeakerId; + else currentSpeakerId = pendingFinalSpeakerId; + if (currentLanguage) pendingFinalLanguage = currentLanguage; + else currentLanguage = pendingFinalLanguage; + if (lastOriginalText) { + pendingFinalOriginalText = + tryMergeOverlap(pendingFinalOriginalText, lastOriginalText) ?? + lastOriginalText; + } + if (currentSourceLanguage) { + pendingFinalSourceLanguage = currentSourceLanguage; + } + + pendingFinalText = merged; + pendingTokens = mergeTimedTokens(merged, pendingTokens, lastTokens); + lastTokens = pendingTokens; + lastEmittedTokens = pendingTokens; + if (activeFrameTimelineVersion === 1) pendingFrameTimelineVersion = 1; + lastSentInterim = merged; + + if (merged !== pendingBefore) { + emitTranscript({ + text: merged, + isFinal: false, + utteranceId: currentUtteranceId ?? undefined, + speakerId: currentSpeakerId, + language, + originalText: pendingFinalOriginalText || undefined, + sourceLanguage: pendingFinalSourceLanguage, + startMs, + endMs, + tokens: pendingTokens, + frameTimelineVersion: pendingFrameTimelineVersion, + }); + schedulePendingFinalCommit(); + } + return; + } + + commitPendingFinal(); + } + + // Emit an INTERIM only. We deliberately do NOT emit a final on every round + // that has finalized tokens (v1 lesson: that piles up one card per partial + // on the client). The single final is emitted at the utterance boundary by + // `emitFinal`, driven by the Soniox `endpoint` event (and on `close()`). + if (isLikelyWindowRegression(compositeText, lastSentInterim)) { + return; + } + + if (compositeText !== lastSentInterim) { + emitTranscript({ + text: compositeText, + isFinal: false, + utteranceId: currentUtteranceId ?? undefined, + speakerId: currentSpeakerId, + language, + originalText: lastOriginalText || undefined, + sourceLanguage: currentSourceLanguage, + startMs, + endMs, + tokens: lastTokens, + frameTimelineVersion: activeFrameTimelineVersion, + }); + lastSentInterim = compositeText; + lastEmittedTokens = lastTokens; + } else if (lastTokens.map((token) => token.text).join("").trim() === compositeText) { + lastEmittedTokens = lastTokens; + } + }; + + const handleEndpoint = () => { + // Endpoint fires when Soniox detects an utterance boundary (the `` + // token). It is a soft signal, so defer the FINAL briefly; if Soniox's + // next rolling window overlaps, we merge it back into this utterance. + const candidate = lastSentInterim.trim(); + if (candidate) { + if (pendingFinalText && pendingFinalTimer) { + const merged = tryMergeOverlap(pendingFinalText, candidate); + if (merged !== null) { + pendingFinalText = merged; + pendingTokens = mergeTimedTokens(merged, pendingTokens, lastEmittedTokens); + if (currentSpeakerId) pendingFinalSpeakerId = currentSpeakerId; + if (currentLanguage) pendingFinalLanguage = currentLanguage; + if (lastOriginalText) { + pendingFinalOriginalText = + tryMergeOverlap(pendingFinalOriginalText, lastOriginalText) ?? + lastOriginalText; + } + if (currentSourceLanguage) { + pendingFinalSourceLanguage = currentSourceLanguage; + } + } else { + commitPendingFinal(); + setPendingFinalFromActive(candidate); + } + } else { + setPendingFinalFromActive(candidate); + } + schedulePendingFinalCommit(); + } + resetActiveUtterance(); + }; + + const handleFinalized = () => { + // The SDK fires this after session.pause() or session.finalize(). For our + // audio-gap pause, it is the trusted "speech segment ended" signal. + commitPendingFinal(); + emitFinal(); + }; + + const handleError = (err: Error) => { + stopGapDetection(); + opts.onError?.(err); + // A provider-side error usually precedes (or accompanies) the socket dying. + // Treat it as a trigger for the self-heal path: if the session is no longer + // usable, `scheduleReconnect` brings up a fresh one; if it is still alive, + // the reconnect is a no-op once `connected` re-fires. + scheduleReconnect("error"); + }; + + // The `disconnected` handler is named so the same function is wired onto every + // session instance (original + each reconnect) and can be `off`-ed on close. + const handleDisconnected = (reason: unknown) => { + logger.info(`disconnected scope=${opts.scope} reason=${typeof reason === "string" ? reason : JSON.stringify(reason)}`); + // An UNEXPECTED disconnect (not our own close()) means the upstream session + // is gone. Self-heal in place so the provider keeps producing transcripts + // for the audio that is still arriving. An expected disconnect (closed=true) + // is the normal teardown and must NOT reconnect. + scheduleReconnect("disconnected"); + }; + + const handleConnected = () => { + logger.info( + `connected scope=${opts.scope} lang=${opts.language}${opts.targetLanguage ? ` → ${opts.targetLanguage}` : ""}`, + ); + }; + + const handleFinished = () => { + logger.info(`finished scope=${opts.scope}`); + commitPendingFinal(); + emitFinal(); + }; + + /** + * Wire our handlers onto a Soniox session instance. Visibility events + * (`connected`/`finished`) and the data/lifecycle events (`result`, + * `endpoint`, `error`, `disconnected`). Called for the initial session and + * for every replacement built on a self-heal reconnect. + */ + const wireSession = (s: RealtimeSttSession): void => { + s.on("connected", handleConnected); + s.on("disconnected", handleDisconnected); + s.on("finished", handleFinished); + s.on("result", handleResult); + s.on("endpoint", handleEndpoint); + s.on("finalized", handleFinalized); + s.on("error", handleError); + }; + + /** Detach our handlers from a session instance (on replace or close). */ + const unwireSession = (s: RealtimeSttSession): void => { + try { + s.off("connected", handleConnected); + s.off("disconnected", handleDisconnected); + s.off("finished", handleFinished); + s.off("result", handleResult); + s.off("endpoint", handleEndpoint); + s.off("finalized", handleFinalized); + s.off("error", handleError); + } catch { + /* best-effort */ + } + }; + + const stopGapDetection = (): void => { + if (gapCheckInterval) { + clearInterval(gapCheckInterval); + gapCheckInterval = null; + } + }; + + const startGapDetection = (): void => { + stopGapDetection(); + lastAudioWriteTime = Date.now(); + pausedForGap = false; + + gapCheckInterval = setInterval(() => { + if (closed || reconnecting || pausedForGap) return; + if (Date.now() - lastAudioWriteTime < gapConfig.thresholdMs) return; + + try { + session.pause(); + pausedForGap = true; + logger.info(`auto-paused scope=${opts.scope} after audio gap`); + } catch (err) { + logger.warn({ err }, `auto-pause failed scope=${opts.scope}`); + } + }, gapConfig.checkIntervalMs); + }; + + /** + * Rebuild the underlying Soniox session in place after an unexpected drop. + * + * Reentrancy-guarded by `reconnecting`, so a burst of `disconnected` + `error` + * for the same drop schedules exactly one heal. Each attempt builds a fresh + * session, wires it, and connects; on failure it backs off and retries up to + * `SONIOX_RECONNECT_MAX_ATTEMPTS`, after which it surfaces the failure via + * `onError` and stops (the next provider recreate, e.g. a real detach, is the + * recovery path of last resort). We do NOT flush a final on the dead session's + * in-flight utterance — the rolling-window state is preserved so the resumed + * session continues the same card where possible. + */ + const reconnect = reconnectConfig(); + const scheduleReconnect = (trigger: string): void => { + if (closed || reconnecting) return; + stopGapDetection(); + pausedForGap = false; + reconnecting = true; + + const attempt = async (): Promise => { + while (!closed) { + reconnectAttempts += 1; + if (reconnectAttempts > reconnect.maxAttempts) { + logger.error(`self-heal gave up scope=${opts.scope} after ${reconnect.maxAttempts} attempts (trigger=${trigger})`); + opts.onError?.( + new Error(`soniox session lost and could not reconnect (scope=${opts.scope})`), + ); + reconnecting = false; + return; + } + + const delay = Math.min( + reconnect.maxMs, + reconnect.baseMs * 2 ** (reconnectAttempts - 1), + ); + logger.info(`self-heal reconnect scope=${opts.scope} attempt=${reconnectAttempts} delayMs=${delay} trigger=${trigger}`); + await new Promise((resolve) => setTimeout(resolve, delay)); + if (closed) break; + + // Drop the dead session's handlers so its late events can't drive us. + unwireSession(session); + + const next = client.realtime.stt(sessionConfig); + wireSession(next); + try { + await next.connect(); + // Connected: swap in the fresh session and clear the heal state. + session = next; + providerGeneration += 1; + audioTimeline.reset(); + reconnecting = false; + reconnectAttempts = 0; + startGapDetection(); + logger.info(`self-heal reconnected scope=${opts.scope}`); + return; + } catch (err) { + logger.error( + { err }, + `self-heal connect failed scope=${opts.scope} attempt=${reconnectAttempts}`, + ); + unwireSession(next); + try { + await next.close(); + } catch { + /* best-effort */ + } + // Loop and back off again. + } + } + reconnecting = false; + }; + + void attempt(); + }; + + // Wire the initial session and connect it. + wireSession(session); + try { + await session.connect(); + startGapDetection(); + } catch (err) { + logger.error({ err }, `connect failed scope=${opts.scope}`); + opts.onError?.(err as Error); + throw err; + } + + return { + name: "soniox", + writeAudio(pcm: Int16Array, position?: AudioPosition): void { + // Drop frames while a self-heal reconnect is in flight (or after close): + // there is no live upstream session to take them, and the pipeline already + // tolerates a brief audio gap across a reconnect. + if (closed || reconnecting) return; + // Soniox SDK accepts Uint8Array of raw PCM bytes. + const bytes = new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength); + lastAudioWriteTime = Date.now(); + if (pausedForGap) { + try { + session.resume(); + pausedForGap = false; + resetActiveUtterance(); + logger.info(`resumed scope=${opts.scope} after audio gap`); + } catch (err) { + logger.warn({ err }, `resume failed scope=${opts.scope}`); + } + } + try { + frameTimelineVersion = position ? 1 : undefined; + if (position && currentUtteranceId) activeFrameTimelineVersion = 1; + audioTimeline.add(pcm.length, position); + session.sendAudio(bytes); + } catch (err) { + // A throw here usually means the socket died between checks: surface it + // and kick off self-heal so the next frames have somewhere to land. + opts.onError?.(err as Error); + scheduleReconnect("writeAudio"); + } + }, + async close(): Promise { + // Mark closed FIRST so any disconnect/error fired by our own teardown does + // not spin up a self-heal reconnect. + closed = true; + stopGapDetection(); + // Flush any in-flight utterance as a final so a card that was mid-update + // gets committed instead of being left dangling on detach. + try { + commitPendingFinal(); + emitFinal(); + } catch { + /* best-effort */ + } + try { + await session.finish(); + } catch { + /* best-effort */ + } + try { + unwireSession(session); + await session.close(); + } catch { + /* best-effort */ + } + }, + }; +} diff --git a/cloud-v2/packages/runtime/src/services/audio/result.test.ts b/cloud-v2/packages/runtime/src/services/audio/result.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a68ca228c05a5cc0ef9d2237f5b979f26b784161 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/result.test.ts @@ -0,0 +1,105 @@ +/** + * @fileoverview Tests for transcriptToStreamMessage, pinning the + * resolvedLanguage contract (OS-1746). + * + * The phone routes results to miniapp handlers by exact stream key + * (`transcription:`), so a specific-language subscription + * MUST get its own code echoed back — never the provider's detected code, + * which is a bare ISO 639-1 ("en") while subscriptions carry BCP-47 ("en-US"). + */ +import { describe, test, expect } from "bun:test"; + +import { transcriptToStreamMessage } from "./result"; +import type { TranscriptMessage } from "./workers/worker"; + +function transcriptMessage(overrides: Partial): TranscriptMessage { + return { + type: "TRANSCRIPT", + kind: "transcription", + mentraUserId: "user@example.com", + text: "hello", + isFinal: true, + language: undefined, + source: "soniox", + subscription: { kind: "transcription", language: { mode: "auto" } }, + ...overrides, + } as TranscriptMessage; +} + +describe("transcriptToStreamMessage resolvedLanguage", () => { + test("preserves token timing and phone position for internal runtime projection", () => { + const tokens = [ + { + text: "word", + startMs: 2, + endMs: 3, + confidence: 1, + isFinal: true, + audioPosition: { sessionTag: 9, offsetMs: 100 }, + }, + ]; + const msg = transcriptToStreamMessage(transcriptMessage({ tokens, frameTimelineVersion: 1 })); + if (msg.type !== "stream.transcript") + throw new Error("expected transcript"); + expect(msg.payload.tokens).toEqual(tokens); + expect(msg.payload.frameTimelineVersion).toBe(1); + }); + test("specific subscription echoes its own code even when the provider detected a different tag", () => { + const msg = transcriptToStreamMessage( + transcriptMessage({ + subscription: { + kind: "transcription", + language: { mode: "specific", code: "en-US" }, + }, + language: "en", // Soniox detected code (bare ISO 639-1) + }), + ); + expect(msg.type).toBe("stream.transcript"); + if (msg.type !== "stream.transcript") return; + expect(msg.payload.resolvedLanguage).toBe("en-US"); + expect(msg.payload.languageDetected).toBe(false); + }); + + test("auto subscription resolves to the detected language", () => { + const msg = transcriptToStreamMessage( + transcriptMessage({ + subscription: { kind: "transcription", language: { mode: "auto" } }, + language: "es", + }), + ); + if (msg.type !== "stream.transcript") throw new Error("expected transcript"); + expect(msg.payload.resolvedLanguage).toBe("es"); + expect(msg.payload.languageDetected).toBe(true); + }); + + test("auto subscription with no detection falls back to auto", () => { + const msg = transcriptToStreamMessage( + transcriptMessage({ + subscription: { kind: "transcription", language: { mode: "auto" } }, + language: undefined, + }), + ); + if (msg.type !== "stream.transcript") throw new Error("expected transcript"); + expect(msg.payload.resolvedLanguage).toBe("auto"); + expect(msg.payload.languageDetected).toBe(true); + }); + + test("translation with specific source echoes the source code", () => { + const msg = transcriptToStreamMessage( + transcriptMessage({ + kind: "translation", + subscription: { + kind: "translation", + source: { mode: "specific", code: "zh-CN" }, + target: "en-US", + }, + sourceLanguage: "zh", + } as Partial), + ); + expect(msg.type).toBe("stream.translation"); + if (msg.type !== "stream.translation") return; + expect(msg.payload.source.language).toBe("zh-CN"); + expect(msg.payload.source.detected).toBe(false); + expect(msg.payload.target.language).toBe("en-US"); + }); +}); diff --git a/cloud-v2/packages/runtime/src/services/audio/result.ts b/cloud-v2/packages/runtime/src/services/audio/result.ts new file mode 100644 index 0000000000000000000000000000000000000000..73a7e6cbda484718439125bda8b3ae1e62292f6c --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/result.ts @@ -0,0 +1,110 @@ +/** + * @fileoverview Map a worker-emitted transcript into a v2 wire message. + * + * The worker (a Bun Worker thread) speaks a small IPC shape, `TranscriptMessage`, + * carrying the text plus the subscription that produced it. The client speaks + * the v2 protocol: `stream.transcript` (transcription) and `stream.translation` + * (translation), each a `TranscriptionData` / `TranslationData` payload wrapped + * in the standard envelope. + * + * This module is the one place that translation happens, so the worker stays + * free of protocol types and the WS layer just forwards whatever this returns. + * + * Protocol: src/protocol/{audio,messages,envelope}.ts. + */ + +import { PROTOCOL_MAJOR, type Envelope } from "@mentra/cloud-protocol/envelope"; +import type { + LanguageSource, + TranscriptionData, + TranscriptionSubscription, + TranslationData, + TranslationSubscription, +} from "@mentra/cloud-protocol/audio"; +import type { TranscriptMessage } from "./workers/worker"; + +/** The two push messages a transcript can become. */ +export type StreamMessage = + | (Envelope & { type: "stream.transcript" }) + | (Envelope & { type: "stream.translation" }); + +/** A specified language resolves to its code; an "auto" source resolves to the + * language the provider actually detected, falling back to "auto" if it never + * reported one. + * + * For specific mode the subscription's code MUST win over the provider's + * detected language: the phone routes results to miniapp handlers by exact + * stream key (`transcription:`), and providers report bare + * ISO 639-1 codes ("en") while subscriptions carry BCP-47 tags ("en-US"). + * Echoing the detected code broke every specific-language subscription — + * results went out keyed `transcription:en` and the `transcription:en-US` + * handler never fired (OS-1746). */ +function resolvedLanguage( + source: LanguageSource, + detected: string | undefined, +): { language: string; detected: boolean } { + if (source.mode === "specific") { + return { language: source.code, detected: false }; + } + return { language: detected ?? "auto", detected: true }; +} + +/** + * Convert a worker transcript into its v2 envelope. The discriminant is the + * subscription kind, not the loose `kind` string, so the payload type is + * sound. + */ +export function transcriptToStreamMessage(t: TranscriptMessage): StreamMessage { + const timestamp = Date.now(); + + if (t.subscription.kind === "translation") { + const sub: TranslationSubscription = t.subscription; + const src = resolvedLanguage(sub.source, t.sourceLanguage); + const payload: TranslationData = { + userId: t.mentraUserId, + subscription: sub, + text: t.text, + isFinal: t.isFinal, + originalText: t.originalText, + utteranceId: t.utteranceId, + speakerId: t.speakerId, + startMs: t.startMs ?? 0, + endMs: t.endMs ?? 0, + source: { language: src.language, detected: src.detected }, + target: { language: sub.target }, + provider: t.source, + timestamp, + }; + return { + v: PROTOCOL_MAJOR, + type: "stream.translation", + timestamp, + payload, + }; + } + + const sub: TranscriptionSubscription = t.subscription; + const lang = resolvedLanguage(sub.language, t.language); + const payload: TranscriptionData = { + userId: t.mentraUserId, + subscription: sub, + text: t.text, + isFinal: t.isFinal, + utteranceId: t.utteranceId, + speakerId: t.speakerId, + startMs: t.startMs ?? 0, + endMs: t.endMs ?? 0, + resolvedLanguage: lang.language, + languageDetected: lang.detected, + tokens: t.tokens ?? [], + frameTimelineVersion: t.frameTimelineVersion, + provider: t.source, + timestamp, + }; + return { + v: PROTOCOL_MAJOR, + type: "stream.transcript", + timestamp, + payload, + }; +} diff --git a/cloud-v2/packages/runtime/src/services/audio/workers/identity.fixture.ts b/cloud-v2/packages/runtime/src/services/audio/workers/identity.fixture.ts new file mode 100644 index 0000000000000000000000000000000000000000..fd8b85d25a61787396e3bd3b61905f73be20ebb7 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/workers/identity.fixture.ts @@ -0,0 +1,14 @@ +/** + * Test-only worker entry: reports the identity it resolves, using the same + * code path as worker.ts (resolveWorkerIdentity over workerData + env), without + * needing Redis. + */ +import { workerData } from "node:worker_threads"; +import { resolveWorkerIdentity } from "./identity"; + +const identity = resolveWorkerIdentity(workerData, { + // Static reads, exactly as worker.ts does. + WORKER_ID: process.env.WORKER_ID, + POD_ID: process.env.POD_ID, +}); +(globalThis as unknown as { postMessage(message: unknown): void }).postMessage(identity); diff --git a/cloud-v2/packages/runtime/src/services/audio/workers/identity.test.ts b/cloud-v2/packages/runtime/src/services/audio/workers/identity.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..262a7ddf0dd63e09e055a8b5b8928f010f520891 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/workers/identity.test.ts @@ -0,0 +1,75 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { resolveWorkerIdentity, type WorkerIdentity } from "./identity"; +import { buildWorkerOptions } from "./pool"; + +describe("resolveWorkerIdentity", () => { + test("workerData wins over env", () => { + expect( + resolveWorkerIdentity({ workerId: "w3", podId: "pod-a" }, { WORKER_ID: "x", POD_ID: "y" }), + ).toEqual({ workerId: "w3", podId: "pod-a", consumerName: "pod-a:w3" }); + }); + + test("falls back to env when workerData is absent (main thread)", () => { + expect(resolveWorkerIdentity(null, { WORKER_ID: "w9", POD_ID: "pod-z" })).toEqual({ + workerId: "w9", + podId: "pod-z", + consumerName: "pod-z:w9", + }); + }); + + test("falls back to defaults, ignoring empty or non-string values", () => { + expect(resolveWorkerIdentity({ workerId: "", podId: 5 }, {})).toEqual({ + workerId: "worker", + podId: "pod", + consumerName: "pod:worker", + }); + }); +}); + +describe("worker started with buildWorkerOptions", () => { + const workers: Worker[] = []; + const saved = { WORKER_ID: process.env.WORKER_ID, POD_ID: process.env.POD_ID }; + + afterEach(() => { + for (const w of workers.splice(0)) w.terminate(); + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }); + + function reportedIdentity(workerId: string, podId: string): Promise { + const worker = new Worker( + new URL("./identity.fixture.ts", import.meta.url), + buildWorkerOptions(workerId, podId), + ); + workers.push(worker); + return new Promise((resolve, reject) => { + worker.onmessage = (e: MessageEvent) => resolve(e.data); + worker.onerror = (e: ErrorEvent) => reject(new Error(e.message)); + }); + } + + test("reports its own worker and pod ids", async () => { + expect(await reportedIdentity("w1", "pod-a")).toEqual({ + workerId: "w1", + podId: "pod-a", + consumerName: "pod-a:w1", + }); + }); + + test("distinct workers resolve distinct consumer names", async () => { + const ids = await Promise.all([reportedIdentity("w0", "pod-a"), reportedIdentity("w1", "pod-a")]); + expect(ids.map((i) => i.consumerName)).toEqual(["pod-a:w0", "pod-a:w1"]); + }); + + test("parent env already holding WORKER_ID / POD_ID does not override the pool's ids", async () => { + process.env.WORKER_ID = "parent-worker"; + process.env.POD_ID = "parent-pod"; + expect(await reportedIdentity("w2", "pod-b")).toEqual({ + workerId: "w2", + podId: "pod-b", + consumerName: "pod-b:w2", + }); + }); +}); diff --git a/cloud-v2/packages/runtime/src/services/audio/workers/identity.ts b/cloud-v2/packages/runtime/src/services/audio/workers/identity.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b478a74147d8747ca577e16cd218dcb914aee3f --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/workers/identity.ts @@ -0,0 +1,44 @@ +/** + * @fileoverview Audio worker identity (worker id, pod id, Redis consumer name). + * + * The pool hands identity to each worker thread through `workerData`, not the + * `env` option of `new Worker`. Bun's `env` option is unreliable for this: + * `process.env` inside a worker keeps the parent's value for any key the parent + * already has, so a pod-level `POD_ID` (or a stray `WORKER_ID`) silently wins + * over the value the pool passed. `workerData` is structured-cloned verbatim. + * + * The identity feeds the Redis consumer name (`:`) used for + * XREADGROUP / XAUTOCLAIM, so each worker must resolve a distinct one. + */ + +export interface WorkerBootData { + workerId: string; + podId: string; +} + +export interface WorkerIdentity extends WorkerBootData { + /** Redis consumer-group consumer name: `:`. */ + consumerName: string; +} + +const DEFAULT_WORKER_ID = "worker"; +const DEFAULT_POD_ID = "pod"; + +function nonEmptyString(value: unknown): string | undefined { + return typeof value === "string" && value.length > 0 ? value : undefined; +} + +/** + * Resolve identity from `workerData` first (set by the pool), then from the + * environment (a worker started outside the pool, or on the main thread where + * `workerData` is null), then from defaults. + */ +export function resolveWorkerIdentity( + data: unknown, + env: Record, +): WorkerIdentity { + const boot = (data && typeof data === "object" ? data : {}) as Partial; + const workerId = nonEmptyString(boot.workerId) ?? nonEmptyString(env.WORKER_ID) ?? DEFAULT_WORKER_ID; + const podId = nonEmptyString(boot.podId) ?? nonEmptyString(env.POD_ID) ?? DEFAULT_POD_ID; + return { workerId, podId, consumerName: `${podId}:${workerId}` }; +} diff --git a/cloud-v2/packages/runtime/src/services/audio/workers/lc3.ts b/cloud-v2/packages/runtime/src/services/audio/workers/lc3.ts new file mode 100644 index 0000000000000000000000000000000000000000..3bc3a567d9e4716cd0a33c37e0a3c1c2e2761a6a --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/workers/lc3.ts @@ -0,0 +1,179 @@ +/** + * @fileoverview LC3 audio decoder, per-user instance. + * + * Wraps the WASM-compiled liblc3 reference codec (Bluetooth SIG) for use in + * audio workers. Ported from v1 cloud's `lc3.service.ts`, narrowed to + * decode-only (cloud-v2 doesn't re-encode audio for the glasses path). + * + * Fixed parameters: + * - Frame duration: 10ms + * - Sample rate: 16kHz + * - Frame samples: 160 per decoded frame (lc3_frame_samples query) + * - Output: Int16 mono PCM + * + * Per-instance LC3 decoder state — one instance per user (per worker). + * The compiled WASM module is shared across instances within a process via + * a module-level cache. + */ + +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +const FRAME_DURATION_US = 10_000; +const SAMPLE_RATE_HZ = 16_000; +const FRAME_BUFFER_BYTES = 1024; // generous upper bound — real frames are ≤60B +const PCM_FORMAT_S16 = 0; // liblc3 PCM format code for signed 16-bit + +/** Supported LC3 frame sizes in bytes. Each maps to a bitrate at 16kHz/10ms. */ +export const SUPPORTED_FRAME_BYTES = new Set([20, 40, 60]); + +interface Lc3Exports { + memory: WebAssembly.Memory; + lc3_frame_samples(durationUs: number, sampleRate: number): number; + lc3_decoder_size(durationUs: number, sampleRate: number): number; + lc3_setup_decoder( + durationUs: number, + sampleRate: number, + srPcm: number, + decoderPtr: number, + ): void; + lc3_decode( + decoderPtr: number, + framePtr: number, + frameBytes: number, + format: number, + samplePtr: number, + stride: number, + ): number; +} + +/** WASM module compiled once per process, shared across decoder instances. */ +let cachedWasmModule: WebAssembly.Module | null = null; + +async function getWasmModule(): Promise { + if (cachedWasmModule) return cachedWasmModule; + const wasmPath = join(import.meta.dir, "liblc3.wasm"); + const wasmBytes = readFileSync(wasmPath); + cachedWasmModule = await WebAssembly.compile(new Uint8Array(wasmBytes)); + return cachedWasmModule; +} + +export class LC3Decoder { + private exports!: Lc3Exports; + private decoderPtr = 0; + private samplePtr = 0; + private framePtr = 0; + private frameSamples = 0; + private framesView!: Uint8Array; + private samplesView!: Int16Array; + + private constructor(public readonly frameBytes: number) { + if (!SUPPORTED_FRAME_BYTES.has(frameBytes)) { + throw new Error( + `LC3Decoder: unsupported frameBytes ${frameBytes} (must be 20, 40, or 60)`, + ); + } + } + + /** + * Create + initialize a decoder. Async because WASM compile/instantiate + * is async. Default `frameBytes` = 20 (16kbps) matches v1's default. + */ + static async create(frameBytes = 20): Promise { + const d = new LC3Decoder(frameBytes); + await d.init(); + return d; + } + + private async init(): Promise { + const wasmModule = await getWasmModule(); + const instance = await WebAssembly.instantiate(wasmModule, {}); + this.exports = instance.exports as unknown as Lc3Exports; + + this.frameSamples = this.exports.lc3_frame_samples( + FRAME_DURATION_US, + SAMPLE_RATE_HZ, + ); + const decoderSize = this.exports.lc3_decoder_size( + FRAME_DURATION_US, + SAMPLE_RATE_HZ, + ); + + // Layout in WASM memory: [decoder_state | sample_buffer | frame_buffer]. + const memory = this.exports.memory; + const basePtr = memory.buffer.byteLength; + const allocSize = + decoderSize + this.frameSamples * 2 + FRAME_BUFFER_BYTES; + + const pagesNeeded = Math.ceil((basePtr + allocSize) / (64 * 1024)); + const currentPages = memory.buffer.byteLength / (64 * 1024); + if (pagesNeeded > currentPages) { + memory.grow(pagesNeeded - currentPages); + } + + this.decoderPtr = basePtr; + this.samplePtr = this.decoderPtr + decoderSize; + this.framePtr = this.samplePtr + this.frameSamples * 2; + + this.exports.lc3_setup_decoder( + FRAME_DURATION_US, + SAMPLE_RATE_HZ, + PCM_FORMAT_S16, + this.decoderPtr, + ); + + // Persistent views into WASM memory — these point at our allocated + // regions so we can read/write samples and frames without re-slicing. + this.framesView = new Uint8Array( + memory.buffer, + this.framePtr, + FRAME_BUFFER_BYTES, + ); + this.samplesView = new Int16Array( + memory.buffer, + this.samplePtr, + this.frameSamples, + ); + } + + /** + * Decode an LC3 payload containing one or more whole frames. Returns null + * if the input is empty or smaller than one frame. Bad frames within a + * multi-frame payload yield silence for that frame; we never throw. + */ + decode(lc3Bytes: Uint8Array): Int16Array | null { + if (lc3Bytes.byteLength === 0) return null; + + const numFrames = Math.floor(lc3Bytes.byteLength / this.frameBytes); + if (numFrames === 0) return null; + + const out = new Int16Array(numFrames * this.frameSamples); + + for (let i = 0; i < numFrames; i++) { + try { + this.framesView.set( + lc3Bytes.subarray(i * this.frameBytes, (i + 1) * this.frameBytes), + ); + this.exports.lc3_decode( + this.decoderPtr, + this.framePtr, + this.frameBytes, + PCM_FORMAT_S16, + this.samplePtr, + 1, // stride + ); + out.set(this.samplesView, i * this.frameSamples); + } catch { + // Per-frame failure → silence. Continue with the next frame. + out.fill(0, i * this.frameSamples, (i + 1) * this.frameSamples); + } + } + + return out; + } + + /** Samples produced per frame (160 at 10ms / 16kHz). */ + get samplesPerFrame(): number { + return this.frameSamples; + } +} diff --git a/cloud-v2/packages/runtime/src/services/audio/workers/pool.ts b/cloud-v2/packages/runtime/src/services/audio/workers/pool.ts new file mode 100644 index 0000000000000000000000000000000000000000..f29886d28d609eb378484b57b1ed1d421fefd0b7 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/workers/pool.ts @@ -0,0 +1,349 @@ +/** + * @fileoverview Worker pool — spawns N Bun Workers per pod, assigns users + * by least-loaded, forwards inbound transcripts to the user's WebSocket. + * + * Why workers own their stream reads (instead of main thread routing): + * - At 200–1000 users/pod target, main-thread per-entry routing becomes + * the bottleneck (one event loop dispatching tens of thousands of + * entries/sec). Workers reading directly scales linearly with worker + * count. + * - Worker death stays local: ioredis cleans up when the thread exits; + * main thread reassigns the dead worker's users and the new worker + * XAUTOCLAIMs any unacked PEL entries. + * + * Assignment policy: + * - **Least-loaded** by session count (not hash). Each session is roughly + * equivalent workload at session-time, and reconnects typically cross + * pod boundaries anyway, so hash's "sticky on reconnect" property + * doesn't survive the failure case it'd most matter for. Least-loaded + * avoids the hash-collision-stacks-two-heavy-users-on-one-worker class + * of problems with no real cost. + * + * IPC surface (worker side: `./worker.ts`): + * - main → worker: `ATTACH_USER`, `DETACH_USER`, `UPDATE_SUBSCRIPTIONS`, + * `SET_CODEC`, `SHUTDOWN` + * - worker → main: `WORKER_READY`, `TRANSCRIPT_STUB`, `TRANSCRIPT`, + * `UDP_LIVENESS_ACK` + */ + +import { createLogger } from "@mentra/cloud-shared"; +import type { WorkerBootData } from "./identity"; +import type { + AudioCodec, + SetCodecMessage, + TranscriptMessage, + TranscriptStubMessage, + UdpLivenessAckMessage, + WorkerInMessage, + WorkerOutMessage, +} from "./worker"; + +const logger = createLogger("audio").child({ service: "worker-pool" }); + +const WORKER_URL = new URL("./worker.ts", import.meta.url); + +interface WorkerSlot { + id: string; + worker: Worker; + sessionCount: number; + ready: boolean; + /** Users this worker owns; recomputed if it dies and we reassign. */ + ownedUsers: Set; + /** ATTACH_USER messages queued while waiting for WORKER_READY. */ + pendingAttaches: string[]; + /** + * Users with a pending reconcile nudge (UPDATE_SUBSCRIPTIONS) queued while + * waiting for WORKER_READY. A Set, not a list of snapshots: the nudge carries + * no subs (the worker reads the subscription key), so duplicate nudges + * collapse to one. + */ + pendingSubscriptions: Set; + /** SET_CODEC messages queued while waiting for WORKER_READY. */ + pendingCodecs: Map; +} + +interface WorkerPoolState { + podId: string; + workers: WorkerSlot[]; + /** mentraUserId → WorkerSlot. So DETACH/release knows which worker holds them. */ + userToWorker: Map; + /** + * Callback set by session.service: route worker-emitted messages to the + * user's WS. Receives real transcripts, routing stubs, and control acks. + */ + transcriptHandler: + | ((msg: TranscriptStubMessage | TranscriptMessage | UdpLivenessAckMessage) => void) + | null; + /** Cleared by stopWorkerPool to suppress respawn during shutdown. */ + shuttingDown: boolean; +} + +let pool: WorkerPoolState | null = null; + +export interface StartWorkerPoolOptions { + podId: string; + /** Number of workers to spawn. Default: 2 if not set (tests can pass 1–4). */ + count?: number; +} + +export function startWorkerPool(opts: StartWorkerPoolOptions): void { + if (pool) { + logger.warn("startWorkerPool called twice; ignoring"); + return; + } + const count = opts.count ?? 2; + pool = { + podId: opts.podId, + workers: [], + userToWorker: new Map(), + transcriptHandler: null, + shuttingDown: false, + }; + for (let i = 0; i < count; i++) { + pool.workers.push(spawnWorkerSlot(`w${i}`)); + } + logger.info({ count }, "worker pool started"); +} + +export async function stopWorkerPool(): Promise { + if (!pool) return; + pool.shuttingDown = true; + const slots = pool.workers; + pool = null; + // Tell each worker to drain Redis + exit, then terminate after a grace + // period if they don't ack. + await Promise.all( + slots.map(async (slot) => { + try { + slot.worker.postMessage({ type: "SHUTDOWN" } satisfies WorkerInMessage); + } catch { + /* worker may already be gone */ + } + // Give it 500ms to close Redis cleanly; then terminate. + await Bun.sleep(500); + slot.worker.terminate(); + }), + ); +} + +/** + * Register the callback that routes worker → main messages onward to the + * user's WebSocket. Called once by `session.service` at boot. + */ +export function onTranscript( + handler: (msg: TranscriptStubMessage | TranscriptMessage | UdpLivenessAckMessage) => void, +): void { + if (!pool) throw new Error("worker pool not started"); + pool.transcriptHandler = handler; +} + +/** + * Assign a user to the least-loaded worker. Idempotent for the SAME user + * (returns the existing slot if already assigned — useful for the + * `already-ours` ownership case where the same user might re-attach + * during a reconnect race). + */ +export function assignUser(mentraUserId: string): void { + if (!pool) throw new Error("worker pool not started"); + const existing = pool.userToWorker.get(mentraUserId); + if (existing) return; + const slot = pickLeastLoaded(pool); + slot.sessionCount++; + slot.ownedUsers.add(mentraUserId); + pool.userToWorker.set(mentraUserId, slot); + if (slot.ready) { + slot.worker.postMessage({ + type: "ATTACH_USER", + mentraUserId, + } satisfies WorkerInMessage); + } else { + // Worker hasn't finished its Redis-ready bootstrap. Queue the attach; + // we drain it once WORKER_READY arrives. + slot.pendingAttaches.push(mentraUserId); + } + logger.debug( + { mentraUserId, workerId: slot.id, sessionCount: slot.sessionCount }, + "user assigned to worker", + ); +} + +/** + * Nudge the worker holding `mentraUserId` to reconcile its subscriptions from + * the Redis subscription key (the source of truth). Called by the main thread + * after it seeds the key at `connection.init`. Cross-pod REST writes reach the + * owning worker through the control stream instead; this IPC path is only for + * the local same-pod seed. No-op if the user isn't assigned to a worker here. + * + * Idempotent: the worker re-reads the key and diffs against its current state, + * so reissuing the nudge is harmless. + */ +export function reconcileSubscriptions(mentraUserId: string): void { + if (!pool) return; + const slot = pool.userToWorker.get(mentraUserId); + if (!slot) return; + const msg: WorkerInMessage = { + type: "UPDATE_SUBSCRIPTIONS", + mentraUserId, + }; + if (slot.ready) { + slot.worker.postMessage(msg); + } else { + slot.pendingSubscriptions.add(mentraUserId); + } +} + +/** + * Set the audio codec for `mentraUserId` on whichever worker holds them. + * Called once per session from the connection.init handler, before audio + * flows. No-op if the user isn't assigned to a worker on this pod. + */ +export function setUserCodec( + mentraUserId: string, + codec: AudioCodec, + frameSizeBytes?: SetCodecMessage["frameSizeBytes"], +): void { + if (!pool) return; + const slot = pool.userToWorker.get(mentraUserId); + if (!slot) return; + const msg: WorkerInMessage = { type: "SET_CODEC", mentraUserId, codec, frameSizeBytes }; + if (slot.ready) { + slot.worker.postMessage(msg); + } else { + slot.pendingCodecs.set(mentraUserId, msg); + } +} + +export function releaseUser(mentraUserId: string): void { + if (!pool) return; + const slot = pool.userToWorker.get(mentraUserId); + if (!slot) return; + slot.sessionCount = Math.max(0, slot.sessionCount - 1); + slot.ownedUsers.delete(mentraUserId); + pool.userToWorker.delete(mentraUserId); + try { + slot.worker.postMessage({ + type: "DETACH_USER", + mentraUserId, + } satisfies WorkerInMessage); + } catch { + /* worker already dead — its replacement won't have this user */ + } + logger.debug( + { mentraUserId, workerId: slot.id, sessionCount: slot.sessionCount }, + "user released from worker", + ); +} + +export function getPoolStats(): { + workerCount: number; + perWorker: Array<{ id: string; sessionCount: number; ready: boolean }>; +} { + if (!pool) return { workerCount: 0, perWorker: [] }; + return { + workerCount: pool.workers.length, + perWorker: pool.workers.map((w) => ({ + id: w.id, + sessionCount: w.sessionCount, + ready: w.ready, + })), + }; +} + +// === Internals === + +function pickLeastLoaded(p: WorkerPoolState): WorkerSlot { + let best = p.workers[0]!; + for (let i = 1; i < p.workers.length; i++) { + if (p.workers[i]!.sessionCount < best.sessionCount) best = p.workers[i]!; + } + return best; +} + +/** + * Options for `new Worker`. Identity travels in `workerData` (reliable), not + * the `env` option, which Bun does not apply to keys the parent already has. + * Exported for tests. + */ +export function buildWorkerOptions(workerId: string, podId: string): WorkerOptions { + // Type cast keeps lib.dom WebWorker types from complaining about the + // Bun-specific `workerData` option. + return { + type: "module", + workerData: { workerId, podId } satisfies WorkerBootData, + } as WorkerOptions; +} + +function spawnWorkerSlot(id: string): WorkerSlot { + const worker = new Worker(WORKER_URL, buildWorkerOptions(id, pool?.podId ?? process.env.POD_ID ?? "pod")); + + const slot: WorkerSlot = { + id, + worker, + sessionCount: 0, + ready: false, + ownedUsers: new Set(), + pendingAttaches: [], + pendingSubscriptions: new Set(), + pendingCodecs: new Map(), + }; + + worker.onmessage = (e: MessageEvent) => { + const msg = e.data; + if (msg.type === "WORKER_READY") { + slot.ready = true; + logger.info({ workerId: id, podId: msg.podId, consumerName: msg.consumerName, pendingAttaches: slot.pendingAttaches.length }, "worker ready"); + // Drain queued attaches and any subscriptions that arrived before ready. + for (const userId of slot.pendingAttaches) { + worker.postMessage({ type: "ATTACH_USER", mentraUserId: userId } satisfies WorkerInMessage); + } + slot.pendingAttaches.length = 0; + for (const msg of slot.pendingCodecs.values()) { + worker.postMessage(msg); + } + slot.pendingCodecs.clear(); + for (const userId of slot.pendingSubscriptions) { + worker.postMessage({ + type: "UPDATE_SUBSCRIPTIONS", + mentraUserId: userId, + } satisfies WorkerInMessage); + } + slot.pendingSubscriptions.clear(); + return; + } + if (msg.type === "TRANSCRIPT_STUB" || msg.type === "TRANSCRIPT" || msg.type === "UDP_LIVENESS_ACK") { + pool?.transcriptHandler?.(msg); + return; + } + }; + + worker.onerror = (ev: ErrorEvent) => { + logger.error({ workerId: id, message: ev.message }, "worker error event"); + }; + + // Worker death: Bun fires no standard "exit" event — `terminate()` / + // crash propagates as the worker becoming unable to postMessage. We + // wrap with a check on next message attempt; for explicit detection, + // a stub heartbeat would help. For now (stub stage), restart on + // catastrophic ws.onerror is good enough. + return slot; +} + +/** + * Test hook — terminate a worker by index (or all) and respawn. Used by + * the multi-pod failover tests; not for production use. + */ +export function _killWorkerForTest(index: number): void { + if (!pool) return; + const slot = pool.workers[index]; + if (!slot) return; + slot.worker.terminate(); + // Reassign its users to other workers. + const orphans = [...slot.ownedUsers]; + pool.workers[index] = spawnWorkerSlot(slot.id); + // The new worker comes up empty; reassign orphans via assignUser + // (which now picks the least-loaded, naturally including the fresh one). + for (const userId of orphans) { + pool.userToWorker.delete(userId); + assignUser(userId); + } +} diff --git a/cloud-v2/packages/runtime/src/services/audio/workers/worker.ts b/cloud-v2/packages/runtime/src/services/audio/workers/worker.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b5a7f29e5143977d02f13c78d05961f06df14a6 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/audio/workers/worker.ts @@ -0,0 +1,925 @@ +/** + * @fileoverview Audio worker — per-CPU thread that owns a slice of users. + * + * What this worker does: + * 1. Maintains its own ioredis streams client. + * 2. Receives `ATTACH_USER` / `DETACH_USER` postMessages from the main + * thread when ownership changes. + * 3. Runs an XREADGROUP loop for the streams of its currently-assigned + * users; for each entry it decodes the audio (LC3 to PCM, or passes + * raw PCM through), feeds it to that user's transcription/translation + * providers, ACKs the entry, and emits results back to the main thread. + * 4. Runs an XAUTOCLAIM loop for failover replay — entries stuck in a + * dead consumer's PEL get picked up here. + * + * Two kinds of message go back to the main thread: + * - TRANSCRIPT: real provider output (text), one per result event. + * - TRANSCRIPT_STUB: one per stream entry, regardless of subscriptions. + * It reports "audio reached a worker and decoded to N PCM bytes" and is + * what the routing/failover tests assert against without needing a + * provider in the loop. + * + * Spec: cloud-v2/docs/issues/002-cloud-runtime/design.md ("Workers handle + * their own stream reads.") + */ + +import {Redis} from "ioredis" +import {workerData} from "node:worker_threads" +import type {TranscriptionToken} from "@mentra/cloud-protocol" +import {createLogger} from "@mentra/cloud-shared" +import {AUDIO_STREAM_GROUP, audioStreamKey} from "../../session/stream" +import {CONTROL_STREAM_GROUP, controlStreamKey} from "../../session/control-stream" +import type {SubscriptionRecord} from "../../session/subscriptions-store" +import {resolveWorkerIdentity} from "./identity" +import {LC3Decoder} from "./lc3" +import {createMockProvider} from "../providers/mock" +import {createSonioxProvider} from "../providers/soniox" +import type {TranscriptionProvider, TranscriptEvent} from "../providers/provider" +import { + subscriptionKey, + type AudioSubscription, + type LanguageSource, + type TranscriptionSubscription, +} from "../../session/subscriptions" + +const logger = createLogger("runtime").child({module: "audio-worker"}) + +// === Worker IPC types === + +export interface AttachUserMessage { + type: "ATTACH_USER" + mentraUserId: string +} +export interface DetachUserMessage { + type: "DETACH_USER" + mentraUserId: string +} +/** + * Tell the worker to reconcile a user's subscriptions. This is a NUDGE, not a + * payload: the worker re-reads the `{user:X}:subscriptions` Redis key (the + * source of truth) and reconciles its provider set from that. The main thread + * sends this after seeding the key at `connection.init`; the same reconcile + * also fires when the worker reads a control-stream entry. Keeping the subs out + * of the message is deliberate: there is exactly one source of truth (the key), + * so no path can hand the worker a snapshot that disagrees with it. + */ +export interface UpdateSubscriptionsMessage { + type: "UPDATE_SUBSCRIPTIONS" + mentraUserId: string +} +/** Audio codec for a user's stream. Set from the client's connection.init. */ +export type AudioCodec = "lc3" | "pcm" +export type Lc3FrameSizeBytes = 20 | 40 | 60 +export interface SetCodecMessage { + type: "SET_CODEC" + mentraUserId: string + codec: AudioCodec + frameSizeBytes?: Lc3FrameSizeBytes +} +export interface ShutdownMessage { + type: "SHUTDOWN" +} +export type WorkerInMessage = + | AttachUserMessage + | DetachUserMessage + | UpdateSubscriptionsMessage + | SetCodecMessage + | ShutdownMessage + +/** + * Emitted per Redis Stream entry to signal "audio reached a worker and was + * decoded." Useful for testing the routing layer without a provider in the + * loop. Real transcript text comes via TranscriptMessage below. + */ +export interface TranscriptStubMessage { + type: "TRANSCRIPT_STUB" + mentraUserId: string + seq: number + /** Length of the raw LC3 payload bytes (before decode). */ + payloadLen: number + /** Length of the decoded PCM (Int16 mono) in bytes. 0 if decode failed. */ + pcmBytesLen: number + audioSessionId: string + /** Where this entry came from — "live" = new XREADGROUP, "replay" = XAUTOCLAIM */ + origin: "live" | "replay" +} + +/** + * Emitted by transcription/translation providers. `kind` discriminates: + * - "transcription": text is in the source language + * - "translation": text is in the TARGET language; `sourceLanguage` is set + * Same shape for both so clients can route via a single handler. + */ +export interface TranscriptMessage { + frameTimelineVersion?: 1 + tokens?: TranscriptionToken[] + type: "TRANSCRIPT" + kind: "transcription" | "translation" + mentraUserId: string + text: string + isFinal: boolean + /** + * Stable id correlating interim + final results for one utterance. The + * client updates a single card in place across interims and commits it on + * the final. Undefined for providers that don't track utterances. + */ + utteranceId?: string + /** Speaker id if the provider reports diarization. */ + speakerId?: string + /** Language of the emitted text. */ + language?: string + /** + * For translation: the source-audio language — the provider's DETECTED + * language when it reports one, else the subscription's (may be `"auto"`). + */ + sourceLanguage?: string + /** For translation: source-language text of the same window, if available. */ + originalText?: string + /** Audio timeline window in milliseconds. */ + startMs?: number + endMs?: number + /** Provider that produced this — `"mock"`, `"soniox"`, etc. */ + source: string + /** + * The subscription that produced this transcript. Carried through so the + * main thread can build the v2 `stream.transcript` / `stream.translation` + * result (which echoes the subscription back to the client) without + * re-deriving it from the language fields. + */ + subscription: AudioSubscription +} + +export interface WorkerReadyMessage { + type: "WORKER_READY" + /** Identity this worker resolved at boot (see identity.ts). */ + workerId: string + podId: string + consumerName: string +} + +export interface UdpLivenessAckMessage { + type: "UDP_LIVENESS_ACK" + mentraUserId: string + sessionTag: number + audioSessionId: string + probeId: string + receivedAt: number +} + +export type WorkerOutMessage = TranscriptStubMessage | TranscriptMessage | UdpLivenessAckMessage | WorkerReadyMessage + +// === Worker state === + +const ownedUsers = new Set() +/** Per-user LC3 decoder. Created on ATTACH_USER, disposed on DETACH_USER. */ +const decoders = new Map() +/** + * Per-user transcription providers, keyed by subscription identity. A user + * can have multiple active subscriptions; we keep one provider instance per + * unique transcription sub. + * + * For translation subs, we currently track the sub but don't open a + * provider — translation lands in a follow-up iteration. + */ +const userProviders = new Map>() +const userProviderCreates = new Map>>() +/** Most recently received subscription list per user, for reconciliation. */ +const userSubs = new Map() +/** + * Per-user audio codec. "lc3" (default) decodes each stream entry through the + * LC3 decoder; "pcm" treats the payload as raw Int16 mono PCM and feeds it to + * providers without decoding. Set from the client's connection.init. + */ +const userCodecs = new Map() +const userLc3FrameSizes = new Map() +let running = true + +/** + * Which transcription provider to use. Defaults to the real Soniox provider, so + * production is real unless told otherwise. Tests can override this when they + * exercise routing / scaling / failover without depending on transcription. + */ +const PROVIDER_KIND = process.env.AUDIO_PROVIDER ?? "soniox" + +const REDIS_URL = process.env.REDIS_URL ?? "redis://127.0.0.1:6379" +// Identity comes from `workerData` (set by pool.ts); see identity.ts for why +// the `env` option of `new Worker` is not used. +const IDENTITY = resolveWorkerIdentity(workerData, { + WORKER_ID: process.env.WORKER_ID, + POD_ID: process.env.POD_ID, +}) +/** + * Consumer name combines pod + worker so the consumer-group view in Redis + * shows distinct entries per worker. Useful for ops + lets XAUTOCLAIM + * reassign entries from a dead worker to a peer on the same pod. + */ +const CONSUMER_NAME = IDENTITY.consumerName + +const XREAD_COUNT_PER_STREAM = 100 +const XREAD_IDLE_SLEEP_MS = 50 +/** Both control and audio reads poll per-user (one stream per command) to stay + * Redis Cluster-safe; this is the idle backoff when no control stream had + * entries this pass. */ +const CONTROL_IDLE_SLEEP_MS = 100 +const XAUTOCLAIM_COUNT = 500 +const XAUTOCLAIM_MIN_IDLE_MS = 0 +const XAUTOCLAIM_LOOP_INTERVAL_MS = 2_000 + +// Note: we DO want offline queue here, unlike the audio-ingress XADD path. +// Worker clients do control operations (xgroup, xack, xautoclaim, xreadgroup); +// briefly queueing those while the socket finishes connecting is harmless. +// The "don't silently buffer audio for a dead Redis" rationale that drives +// enableOfflineQueue:false in redis.connection.ts only applies to the +// main-thread XADD path. +const streamsClient = new Redis(REDIS_URL, { + maxRetriesPerRequest: 3, +}) + +const mainClient = new Redis(REDIS_URL, { + maxRetriesPerRequest: 3, +}) + +// Dedicated client for the control-stream read so control polling + XACKs +// don't serialize behind the audio read's per-user XREADGROUPs (and vice versa). +const controlClient = new Redis(REDIS_URL, { + maxRetriesPerRequest: 3, +}) + +// === Receive assignments from main thread === + +declare const self: Worker + +/** + * Users whose consumer group has been ensured. We only XREADGROUP for users + * in this set — the unfiltered `ownedUsers` set gets users added the moment + * ATTACH_USER arrives, but the group-create is async; gating the read loop + * on this set avoids the NOGROUP race. + */ +const readyUsers = new Set() + +/** Users whose control-stream consumer group has been ensured. */ +const controlReadyUsers = new Set() + +async function handleAttach(mentraUserId: string): Promise { + ownedUsers.add(mentraUserId) + // Decoder is needed for any audio activity; create it eagerly so the very + // first packet has somewhere to land. Providers are NOT created until the + // subscription set names one (or never, if the session only wants raw audio + // routing). + if (!decoders.has(mentraUserId)) { + try { + decoders.set(mentraUserId, await LC3Decoder.create(userLc3FrameSizes.get(mentraUserId) ?? 20)) + } catch (err) { + logger.error({err}, "LC3Decoder.create failed") + } + } + const ok = await ensureConsumerGroup(mentraUserId) + // Control-stream group too, so subscription-change nudges for this user land + // in our consumer once we own them. Independent of the audio group result; + // we still want to read control even if the audio stream isn't ready yet. + await ensureControlConsumerGroup(mentraUserId) + if (ok && ownedUsers.has(mentraUserId)) { + readyUsers.add(mentraUserId) + } + // Reconcile from the subscription key on attach/ownership-acquire. A takeover + // worker inherits the live subscription set from the key, so providers come + // back up without waiting for the next REST write. The key is the source of + // truth; a missing key means "no subscriptions yet" (empty set). + await reconcileFromKey(mentraUserId) +} + +/** + * Read the user's authoritative subscription set from the Redis key and + * reconcile providers against it. The key is the single source of truth; this + * runs on attach, on a control-stream nudge, and on the main thread's + * post-seed nudge. A missing key reconciles to an empty set. + */ +async function reconcileFromKey(mentraUserId: string): Promise { + let subs: AudioSubscription[] = [] + try { + const raw = await mainClient.get(subscriptionsKey(mentraUserId)) + if (raw) { + const record = JSON.parse(raw) as SubscriptionRecord + subs = record.subscriptions ?? [] + } + } catch (err) { + logger.error({err}, "reconcileFromKey read failed") + return + } + await reconcileProviders(mentraUserId, subs) +} + +/** Subscription key, mirrored from `subscriptions-store.ts` (hash-tagged per user). */ +function subscriptionsKey(mentraUserId: string): string { + return `{user:${mentraUserId}}:subscriptions` +} + +/** + * Reconcile a user's active providers against a fresh subscription list. + * Closes providers whose subscriptions disappeared; opens providers for + * new subs. Idempotent for unchanged subs (no recreation). + */ +async function reconcileProviders(mentraUserId: string, subs: AudioSubscription[]): Promise { + userSubs.set(mentraUserId, subs) + + const existing = userProviders.get(mentraUserId) ?? new Map() + userProviders.set(mentraUserId, existing) + const creating = userProviderCreates.get(mentraUserId) ?? new Map>() + userProviderCreates.set(mentraUserId, creating) + + // Compute desired set: one entry per subscription, transcription AND + // translation. They share the provider interface; output messages + // carry a `kind` discriminator so the client knows which is which. + const desired = new Map() + for (const sub of subs) { + desired.set(subscriptionKey(sub), sub) + } + + // Close providers whose subs are gone. + for (const [key, provider] of existing) { + if (!desired.has(key)) { + existing.delete(key) + provider.close().catch((err) => { + logger.error({err}, "provider close failed") + }) + } + } + + // Open providers for new subs. + for (const [key, sub] of desired) { + if (existing.has(key)) continue + const pending = creating.get(key) + if (pending) { + try { + const provider = await pending + if (shouldKeepProvider(mentraUserId, key) && !existing.has(key)) { + existing.set(key, provider) + } else if (!existing.has(key)) { + provider.close().catch((err) => { + logger.error({err}, "provider close failed") + }) + } + } catch (err) { + logger.error({err}, "provider create failed") + } + continue + } + + const creation = createProvider(mentraUserId, sub) + creating.set(key, creation) + try { + const provider = await creation + if (shouldKeepProvider(mentraUserId, key) && !existing.has(key)) { + existing.set(key, provider) + } else { + provider.close().catch((err) => { + logger.error({err}, "provider close failed") + }) + } + } catch (err) { + logger.error({err}, "provider create failed") + } finally { + if (creating.get(key) === creation) creating.delete(key) + if (creating.size === 0) userProviderCreates.delete(mentraUserId) + } + } +} + +function shouldKeepProvider(mentraUserId: string, key: string): boolean { + if (!ownedUsers.has(mentraUserId)) return false + if (!userProviders.has(mentraUserId)) return false + const subs = userSubs.get(mentraUserId) ?? [] + return subs.some((sub) => subscriptionKey(sub) === key) +} + +function langCode(lang: LanguageSource): string { + return lang.mode === "specific" ? lang.code : "auto" +} + +async function createProvider(mentraUserId: string, sub: AudioSubscription): Promise { + const isTranslation = sub.kind === "translation" + const sourceLanguage = isTranslation ? langCode(sub.source) : undefined + const target = isTranslation ? sub.target : undefined + // Provider scope = user + sub identity, for log clarity and as the mock's + // text-content prefix so multiple subs from the same user produce distinct + // transcripts. + const scope = isTranslation + ? `${mentraUserId}:${sourceLanguage}>${target}` + : `${mentraUserId}:${langCode((sub as TranscriptionSubscription).language)}` + const providerLanguage = isTranslation ? (target as string) : langCode((sub as TranscriptionSubscription).language) + // Detection hints only exist on an auto-mode transcription source; carry them + // to the provider so `configure({languageHints})` actually biases Soniox + // (issue 021). A specific language ignores them — the language is the hint. + const languageHints = + !isTranslation && sub.kind === "transcription" && sub.language.mode === "auto" + ? sub.language.hints + : undefined + + const onTranscript = (event: TranscriptEvent) => { + const out: TranscriptMessage = { + type: "TRANSCRIPT", + kind: sub.kind, + mentraUserId, + text: event.text, + isFinal: event.isFinal, + utteranceId: event.utteranceId, + speakerId: event.speakerId, + // For transcription: text is in the source/auto language. + // For translation: text is in the target language. + language: event.language ?? providerLanguage, + // Detected source language wins over the subscription's static value + // (often "auto"), so clients can show what was actually spoken. + sourceLanguage: event.sourceLanguage ?? sourceLanguage, + originalText: event.originalText, + startMs: event.startMs, + endMs: event.endMs, + tokens: event.tokens, + frameTimelineVersion: event.frameTimelineVersion, + source: PROVIDER_KIND, + subscription: sub, + } + self.postMessage(out) + } + const onError = (err: Error) => { + logger.error({err, mentraUserId}, `provider(${PROVIDER_KIND}) error`) + } + + switch (PROVIDER_KIND) { + case "mock": + return createMockProvider({ + scope, + language: providerLanguage, + onTranscript, + onError, + }) + case "soniox": + return createSonioxProvider({ + scope, + // Soniox: source language config in either case. For translation + // subs we additionally pass `targetLanguage` — Soniox does the + // translation in-session and we filter result tokens accordingly. + language: isTranslation ? (sourceLanguage as string) : langCode((sub as TranscriptionSubscription).language), + languageHints, + targetLanguage: isTranslation ? (target as string) : undefined, + onTranscript, + onError, + }) + default: + throw new Error(`unknown AUDIO_PROVIDER: ${PROVIDER_KIND}`) + } +} + +self.onmessage = (e: MessageEvent) => { + const msg = e.data + switch (msg.type) { + case "ATTACH_USER": + void handleAttach(msg.mentraUserId) + break + case "SET_CODEC": + userCodecs.set(msg.mentraUserId, msg.codec) + if (msg.frameSizeBytes) { + userLc3FrameSizes.set(msg.mentraUserId, msg.frameSizeBytes) + const existing = decoders.get(msg.mentraUserId) + if (existing && existing.frameBytes !== msg.frameSizeBytes) { + void LC3Decoder.create(msg.frameSizeBytes) + .then((decoder) => { + decoders.set(msg.mentraUserId, decoder) + }) + .catch((err) => { + logger.error({err}, "LC3Decoder.create failed") + }) + } + } + break + case "DETACH_USER": { + ownedUsers.delete(msg.mentraUserId) + readyUsers.delete(msg.mentraUserId) + controlReadyUsers.delete(msg.mentraUserId) + decoders.delete(msg.mentraUserId) + userLc3FrameSizes.delete(msg.mentraUserId) + userSubs.delete(msg.mentraUserId) + userCodecs.delete(msg.mentraUserId) + userProviderCreates.delete(msg.mentraUserId) + const providers = userProviders.get(msg.mentraUserId) + if (providers) { + userProviders.delete(msg.mentraUserId) + for (const provider of providers.values()) { + provider.close().catch((err) => { + logger.error({err}, "provider close failed") + }) + } + } + break + } + case "UPDATE_SUBSCRIPTIONS": + // Nudge: re-read the subscription key and reconcile. The message carries + // no subs on purpose; the key is the source of truth. + void reconcileFromKey(msg.mentraUserId) + break + case "SHUTDOWN": + running = false + void shutdown() + break + } +} + +async function ensureConsumerGroup(mentraUserId: string): Promise { + try { + // Group start = `0` (beginning of stream) rather than `$` (end of stream + // = new entries only). Reason: UDP ingress may have XADDed packets to + // the stream BEFORE the worker finished creating the group (the assign + // happens at WS-open time, but UDP packets can arrive within + // milliseconds of connection.ack reaching the client). `$` would + // silently skip those entries. `0` delivers everything that's in the + // stream — `MAXLEN ~ 1000` keeps the backlog bounded so this isn't + // unbounded replay. + await mainClient.xgroup("CREATE", audioStreamKey(mentraUserId), AUDIO_STREAM_GROUP, "0", "MKSTREAM") + return true + } catch (err) { + const msg = (err as Error).message ?? "" + // BUSYGROUP = "already exists" — that's success for our purposes. + if (msg.includes("BUSYGROUP")) return true + logger.error({err}, "xgroup create failed") + return false + } +} + +async function ensureControlConsumerGroup(mentraUserId: string): Promise { + try { + // Start at `0` rather than `$`: UDP liveness ACKs can be published by a + // non-owner pod milliseconds after connection.ack, before the owner worker + // has finished creating this group. Starting at `$` would skip that ACK + // forever. Control streams are bounded and nudges are idempotent, so + // replaying a tiny backlog is safer than missing a liveness result. + await controlClient.xgroup("CREATE", controlStreamKey(mentraUserId), CONTROL_STREAM_GROUP, "0", "MKSTREAM") + controlReadyUsers.add(mentraUserId) + return true + } catch (err) { + const msg = (err as Error).message ?? "" + if (msg.includes("BUSYGROUP")) { + controlReadyUsers.add(mentraUserId) + return true + } + logger.error({err}, "control xgroup create failed") + return false + } +} + +// === Main loops === + +/** + * Read the control stream for owned users and reconcile on each nudge. Separate + * from the audio loop (and on its own Redis client) so subscription changes are + * never stuck behind the blocking audio read, and the audio hot path never has + * to branch on control entries. + */ +async function controlReadLoop(): Promise { + while (running) { + const users = [...controlReadyUsers] + if (users.length === 0) { + await Bun.sleep(100) + continue + } + + let sawEntries = false + for (const userId of users) { + try { + // One stream per command: Redis Cluster requires all keys in a command + // to share a hash slot, and each user's control stream hashes to that + // user. A per-user read avoids CROSSSLOT (mirrors freshReadLoop). + const result = (await controlClient.xreadgroup( + "GROUP", + CONTROL_STREAM_GROUP, + CONSUMER_NAME, + "COUNT", + 100, + "STREAMS", + controlStreamKey(userId), + ">", + )) as Array<[string, Array<[string, string[]]>]> | null + + if (!result) continue + sawEntries = true + + for (const [streamKey, entries] of result) { + const mentraUserId = controlUserFromKey(streamKey) + let shouldReconcile = false + + for (const [, fields] of entries) { + const map = fieldArrayToMap(fields) + switch (map.kind) { + case "subscriptions-changed": + // Reconcile once per batch, not once per entry: every subscription + // entry is the same "re-read the key" nudge. + shouldReconcile = true + break + case "udp-liveness-ack": + logger.debug( + { + mentraUserId, + sessionTag: map.sessionTag, + probeId: map.probeId, + }, + "udp liveness ack control received", + ) + self.postMessage({ + type: "UDP_LIVENESS_ACK", + mentraUserId, + sessionTag: Number(map.sessionTag ?? 0), + audioSessionId: map.audioSessionId ?? "", + probeId: map.probeId ?? "", + receivedAt: Number(map.receivedAt ?? Date.now()), + } satisfies UdpLivenessAckMessage) + break + } + } + + if (shouldReconcile) await reconcileFromKey(mentraUserId) + + for (const [entryId] of entries) { + try { + await controlClient.xack(streamKey, CONTROL_STREAM_GROUP, entryId) + } catch (err) { + logger.error({err}, "control xack failed") + } + } + } + } catch (err) { + const msg = (err as Error).message ?? "" + if (msg.includes("NOGROUP")) { + await ensureControlConsumerGroup(userId) + continue + } + logger.error({err}, "control xreadgroup failed") + await Bun.sleep(500) + } + } + if (!sawEntries) await Bun.sleep(CONTROL_IDLE_SLEEP_MS) + } +} + +/** Recover the user id from a `{user:X}:control` stream key. */ +function controlUserFromKey(streamKey: string): string { + return streamKey.replace(/^\{user:/, "").replace(/\}:control$/, "") +} + +async function freshReadLoop(): Promise { + while (running) { + // Only stream-read for users whose consumer group has been verified to + // exist. A user that JUST ATTACHed but hasn't finished XGROUP CREATE + // yet skips this iteration; they're picked up once group-ensure resolves. + const users = [...readyUsers] + if (users.length === 0) { + await Bun.sleep(100) + continue + } + + let sawEntries = false + for (const userId of users) { + try { + // One stream per command: Redis Cluster requires all keys in a command + // to share a hash slot, and each user's audio stream intentionally + // hashes to that user. A per-user read avoids CROSSSLOT while keeping + // the worker's ownership set unchanged. + const result = (await streamsClient.xreadgroup( + "GROUP", + AUDIO_STREAM_GROUP, + CONSUMER_NAME, + "COUNT", + XREAD_COUNT_PER_STREAM, + "STREAMS", + audioStreamKey(userId), + ">", + )) as Array<[string, Array<[string, string[]]>]> | null + + if (result) { + sawEntries = true + await processBatch(result, "live") + } + } catch (err) { + const msg = (err as Error).message ?? "" + // NOGROUP can happen if a stream got DEL'd out from under us (tests + // wipe Redis between cases; production this would only happen if + // someone manually nuked a stream key). Re-ensure this user's group; + // the next iteration picks up cleanly. + if (msg.includes("NOGROUP")) { + await ensureConsumerGroup(userId) + continue + } + logger.error({err}, "xreadgroup failed") + await Bun.sleep(500) + } + } + if (!sawEntries) await Bun.sleep(XREAD_IDLE_SLEEP_MS) + } +} + +async function autoclaimLoop(): Promise { + while (running) { + for (const userId of readyUsers) { + try { + await drainAutoclaim(userId) + } catch (err) { + logger.error({err}, "autoclaim failed") + } + } + await Bun.sleep(XAUTOCLAIM_LOOP_INTERVAL_MS) + } +} + +async function drainAutoclaim(userId: string): Promise { + let cursor = "0-0" + while (running) { + let result: [string, Array<[string, string[]]>, string[]] | null = null + try { + // XAUTOCLAIM COUNT N + // Returns [next-cursor, [[id, [field, value, ...]], ...]] + result = (await mainClient.xautoclaim( + audioStreamKey(userId), + AUDIO_STREAM_GROUP, + CONSUMER_NAME, + XAUTOCLAIM_MIN_IDLE_MS, + cursor, + "COUNT", + XAUTOCLAIM_COUNT, + )) as [string, Array<[string, string[]]>, string[]] + } catch (err) { + const msg = (err as Error).message ?? "" + // Stream got dropped; re-ensure and bail. Next loop iteration retries. + if (msg.includes("NOGROUP")) { + await ensureConsumerGroup(userId) + return + } + throw err + } + + if (!result) return + const [nextCursor, entries] = result + + if (entries.length === 0) return + await processBatch([[audioStreamKey(userId), entries]], "replay") + + if (nextCursor === "0-0") return // Redis convention: done. + cursor = nextCursor + } +} + +async function processBatch( + result: Array<[string, Array<[string, string[]]>]>, + origin: "live" | "replay", +): Promise { + for (const [streamKey, entries] of result) { + // Stream keys are `{user:X}:audio` (hash-tagged so a user's keys share a + // cluster shard — see audioStreamKey). The old `audio:X` parse silently + // produced a mangled user id, so decoder/provider lookups missed and every + // frame was dropped on the floor (providers saw "No audio received"). + const keyMatch = /^\{user:(.+)\}:audio$/.exec(streamKey) + const mentraUserId = keyMatch ? keyMatch[1]! : streamKey.replace(/^audio:/, "") + const decoder = decoders.get(mentraUserId) + const codec = userCodecs.get(mentraUserId) ?? "lc3" + + for (const [entryId, fields] of entries) { + const map = fieldArrayToMap(fields) + const seq = Number(map.seq ?? 0) + const audioSessionId = map.audioSessionId ?? "" + + // Recover the binary payload from the base64 we encoded on XADD. + const payloadBytes = typeof map.payload === "string" ? Buffer.from(map.payload, "base64") : Buffer.alloc(0) + const payloadLen = payloadBytes.byteLength + + // Turn the payload into Int16 mono PCM, then feed it to each subscribed + // provider for this user. For "lc3" we decode; for "pcm" the payload + // already IS PCM, so we wrap it as Int16 directly (no encoder needed on + // the sending side — handy for tests and raw-PCM clients). + // + // If the user has no subscriptions, the PCM is computed (so the + // TRANSCRIPT_STUB byte count is accurate) but no provider fires — the + // correct behavior for a session that hasn't asked to be transcribed. + let pcm: Int16Array | null = null + if (payloadLen > 0) { + if (codec === "pcm") { + // Align to Int16 (drop a trailing odd byte if present). + const usableSamples = Math.floor(payloadLen / 2) + pcm = new Int16Array(payloadBytes.buffer, payloadBytes.byteOffset, usableSamples) + } else if (decoder) { + pcm = decoder.decode(new Uint8Array(payloadBytes.buffer, payloadBytes.byteOffset, payloadLen)) + } + } + + let pcmBytesLen = 0 + if (pcm) { + pcmBytesLen = pcm.byteLength + const providers = userProviders.get(mentraUserId) + if (providers) { + for (const provider of providers.values()) { + try { + const offsetMs = map.offsetMs === "" || map.offsetMs == null ? NaN : Number(map.offsetMs) + const sessionTag = Number(map.sessionTag) + provider.writeAudio( + pcm, + Number.isFinite(offsetMs) && offsetMs >= 0 && Number.isInteger(sessionTag) + ? {sessionTag, offsetMs} + : undefined, + ) + } catch (err) { + logger.error({err}, "provider.writeAudio failed") + } + } + } + } + + // One log per ~5s of audio (every 128th entry) so the feed path is + // observable without flooding: payload size, codec, decode result, and + // how many providers the PCM actually reached. + if (seq % 128 === 0) { + logger.info( + { + mentraUserId, + seq, + payloadBytes: payloadLen, + codec, + hasDecoder: decoders.has(mentraUserId), + pcmBytes: pcmBytesLen, + providers: userProviders.get(mentraUserId)?.size ?? 0, + }, + "feed", + ) + } + + const out: TranscriptStubMessage = { + type: "TRANSCRIPT_STUB", + mentraUserId, + seq, + payloadLen, + pcmBytesLen, + audioSessionId, + origin, + } + self.postMessage(out) + + // ACK so Redis can stop tracking this in our consumer's PEL. + try { + await streamsClient.xack(streamKey, AUDIO_STREAM_GROUP, entryId) + } catch (err) { + logger.error({err}, "xack failed") + } + } + } +} + +function fieldArrayToMap(fields: string[]): Record { + const out: Record = {} + for (let i = 0; i < fields.length; i += 2) { + out[fields[i]!] = fields[i + 1]! + } + return out +} + +// === Lifecycle === + +async function shutdown(): Promise { + try { + await Promise.all([ + streamsClient.quit().catch(() => undefined), + mainClient.quit().catch(() => undefined), + controlClient.quit().catch(() => undefined), + ]) + } catch { + /* ignore */ + } +} + +// Boot: wait for BOTH Redis clients to be `ready` before announcing +// WORKER_READY. ioredis with `enableOfflineQueue: false` rejects commands +// during the connecting phase, so any ATTACH_USER that arrives before the +// clients are up would hit "Stream isn't writeable." +async function bootstrap(): Promise { + await Promise.all([waitForReady(streamsClient), waitForReady(mainClient), waitForReady(controlClient)]) + self.postMessage({ + type: "WORKER_READY", + workerId: IDENTITY.workerId, + podId: IDENTITY.podId, + consumerName: IDENTITY.consumerName, + } satisfies WorkerReadyMessage) + void freshReadLoop() + void autoclaimLoop() + void controlReadLoop() +} + +function waitForReady(client: Redis): Promise { + if (client.status === "ready") return Promise.resolve() + return new Promise((resolve, reject) => { + const onReady = () => { + client.off("error", onError) + resolve() + } + const onError = (err: Error) => { + client.off("ready", onReady) + reject(err) + } + client.once("ready", onReady) + client.once("error", onError) + }) +} + +void bootstrap() diff --git a/cloud-v2/packages/runtime/src/services/camera/camera.service.ts b/cloud-v2/packages/runtime/src/services/camera/camera.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..99bb2071270536c6710035feb2a478e97a3808f9 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/camera/camera.service.ts @@ -0,0 +1,177 @@ +/** + * @fileoverview Camera service: managed photo + managed stream. + * + * Sits on top of the storage service. A managed photo is a request-then-push + * flow: presign an upload + read URL, record the pending request, and push + * `photo.ready` when the upload lands. Completion arrives one of two ways: + * - local provider: the runtime serves the upload, so its PUT handler calls + * `completeUpload` directly (instant, no polling). + * - r2/s3 provider: the object-created event reaches the storage webhook, + * which calls `completeUpload`. + * The device (glasses) does the actual capture + upload to the presigned URL. + * + * Managed stream is provisioned synchronously (stub coordinates today; a real + * Cloudflare Stream provider lands later) and has no push. + * + * Pending requests live in Redis keyed by requestId, so a completion event that + * lands on any pod can resolve the user to push to. The push itself currently + * targets the user's WS on this pod; cross-pod push routing lands with the same + * work the audio path needs. + * + * Spec: docs/issues/002-cloud-runtime/camera/spec.md. + */ + +import { ulid } from "ulid"; +import { createLogger } from "@mentra/cloud-shared"; +import { getRedis } from "../../clients/redis.client"; +import { getStorageProvider } from "../storage/storage.service"; +import { + provisionStream, + stopStream as stopManagedStream, + streamStatus as getManagedStreamStatus, +} from "../stream/stream.service"; +import { forwardToUserSessions } from "../../net/ws"; +import { PROTOCOL_MAJOR } from "@mentra/cloud-protocol/envelope"; +import type { + StreamOptions, + ManagedStream, + StreamStatusResult, +} from "@mentra/cloud-protocol/camera"; + +const logger = createLogger("audio").child({ service: "camera.service" }); + +const PHOTO_CONTENT_TYPE = "image/jpeg"; +/** Pending photo requests TTL: long enough for an upload, then abandoned. */ +const PHOTO_REQUEST_TTL_SEC = 300; + +interface PendingPhoto { + mentraUserId: string; + key: string; + readUrl: string; +} + +function photoKey(requestId: string): string { + return `photos/${requestId}`; +} +function requestIdFromKey(key: string): string | null { + return key.startsWith("photos/") ? key.slice("photos/".length) : null; +} +function pendingRedisKey(requestId: string): string { + return `photo-request:${requestId}`; +} + +export interface PhotoRequestResult { + requestId: string; + uploadUrl: string; + readUrl: string; +} + +/** + * Create a managed-photo request: presign the upload + read URLs and record the + * pending request. Returns the URLs the device uses; the caller gets + * `photo.ready` over its WS on completion. + */ +export async function requestPhoto( + mentraUserId: string, + origin: string, +): Promise { + const provider = getStorageProvider(); + const requestId = `photo_${ulid()}`; + const key = photoKey(requestId); + + const upload = await provider.presignUpload(key, { + contentType: PHOTO_CONTENT_TYPE, + origin, + }); + const readUrl = await provider.presignDownload(key, { origin }); + + const pending: PendingPhoto = { mentraUserId, key, readUrl }; + await getRedis().set( + pendingRedisKey(requestId), + JSON.stringify(pending), + "EX", + PHOTO_REQUEST_TTL_SEC, + ); + + logger.info({ mentraUserId, requestId, provider: provider.name }, "managed photo requested"); + + // The device (glasses) uploads the captured image to `uploadUrl` out of band. + // Completion arrives via the local upload handler (local provider) or the + // storage-events webhook (r2/s3); both call `completeUpload`. + return { requestId, uploadUrl: upload.url, readUrl }; +} + +/** + * Mark a photo upload complete and push `photo.ready` to the requester. Called + * by the local provider's upload handler and by the storage event webhook. + * Idempotent: a duplicate event finds no pending entry and is a no-op. + */ +export async function completeUpload(key: string): Promise { + const requestId = requestIdFromKey(key); + if (!requestId) return; + const pending = await takePending(requestId); + if (!pending) return; + + forwardToUserSessions(pending.mentraUserId, { + v: PROTOCOL_MAJOR, + type: "photo.ready", + timestamp: Date.now(), + payload: { requestId, readUrl: pending.readUrl }, + }); + logger.info({ mentraUserId: pending.mentraUserId, requestId }, "managed photo ready"); +} + +/** Mark a photo request failed and push `photo.error`. */ +export async function failUpload(requestId: string, reason: string): Promise { + const pending = await takePending(requestId); + if (!pending) return; + forwardToUserSessions(pending.mentraUserId, { + v: PROTOCOL_MAJOR, + type: "photo.error", + timestamp: Date.now(), + payload: { requestId, reason }, + }); + logger.warn({ mentraUserId: pending.mentraUserId, requestId, reason }, "managed photo failed"); +} + +/** Read and remove a pending request, so it settles exactly once. */ +async function takePending(requestId: string): Promise { + const redis = getRedis(); + const raw = await redis.get(pendingRedisKey(requestId)); + if (!raw) return null; + await redis.del(pendingRedisKey(requestId)); + try { + return JSON.parse(raw) as PendingPhoto; + } catch { + return null; + } +} + +/** + * Provision a managed stream on the configured stream provider (Cloudflare + * Stream). Fully answered by this response (no push). Throws if no stream + * provider is configured, rather than returning fake coordinates. + */ +export async function startStream( + mentraUserId: string, + opts: StreamOptions, +): Promise { + const stream = await provisionStream(mentraUserId, opts); + logger.info({ mentraUserId, streamId: stream.streamId }, "managed stream provisioned"); + return stream; +} + +/** The provider's view of a managed stream's ingest (is the push arriving?). */ +export async function streamStatus( + mentraUserId: string, + streamId: string, +): Promise { + void mentraUserId; + return await getManagedStreamStatus(streamId); +} + +/** Stop a managed stream. */ +export async function stopStream(mentraUserId: string, streamId: string): Promise { + await stopManagedStream(streamId); + logger.info({ mentraUserId, streamId }, "managed stream stopped"); +} diff --git a/cloud-v2/packages/runtime/src/services/maps/maps.service.test.ts b/cloud-v2/packages/runtime/src/services/maps/maps.service.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ee58242f4f9ebf3c8982a73f4ff242136fb7a69 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/maps/maps.service.test.ts @@ -0,0 +1,302 @@ +/** + * @fileoverview Tests for the maps service: cache behavior + provider dispatch. + * + * These exercise the REAL Mapbox provider (createMapboxProvider) against a + * stubbed `globalThis.fetch`, so we cover the full path — service -> promise + * cache -> provider -> normalization — without a network or a real token. The + * fetch stub also counts calls, which is how we assert the cache's headline + * behaviors: a hit serves without a second upstream call, and concurrent + * identical calls coalesce onto ONE call (in-flight dedup). + * + * Env + cache state is module-global (provider singleton, two caches), so each + * test restores `MAPBOX_ACCESS_TOKEN`, resets the provider, clears the caches, + * and restores the original fetch in afterEach. + */ +import { describe, test, expect, afterEach } from "bun:test"; + +import { + directions, + reverseGeocode, + placeAutocomplete, + placeDetails, + resetMapsProvider, + clearMapsCaches, +} from "./maps.service"; + +const realFetch = globalThis.fetch; +const savedToken = process.env.MAPBOX_ACCESS_TOKEN; + +/** + * Install a fake `fetch` that returns `body` (JSON) for every call and counts + * how many times it was invoked. Returns the counter so a test can assert the + * cache suppressed/coalesced upstream calls. + */ +function stubFetch(body: unknown, status = 200): { calls: () => number } { + let count = 0; + globalThis.fetch = (async () => { + count += 1; + return new Response(JSON.stringify(body), { status }); + }) as unknown as typeof fetch; + return { calls: () => count }; +} + +/** A minimal Mapbox Directions response with one route + one step. */ +function mapboxDirectionsBody() { + return { + routes: [ + { + // polyline6 for a couple of points near SF; exact geometry is not + // asserted, only that decoding produces points. + geometry: "yapwFhhbjV???", + distance: 1234, + duration: 567, + legs: [ + { + steps: [ + { + distance: 1234, + name: "Fell St", + maneuver: { type: "depart", modifier: "left", instruction: "Head out" }, + geometry: "yapwFhhbjV", + }, + ], + }, + ], + }, + ], + }; +} + +/** + * A minimal Mapbox reverse-geocode response carrying a street name + full + * address. When `road` is null, returns no features (the off-grid case). + */ +function mapboxGeocodeBody(road: string | null, fullAddress?: string) { + return { + features: road + ? [ + { + properties: { + name: road, + full_address: fullAddress ?? `123 ${road}, San Francisco, California`, + context: { street: { name: road } }, + }, + }, + ] + : [], + }; +} + +const REQ = { + origin: { lat: 37.7749, lng: -122.4194 }, + stops: [{ lat: 37.7858, lng: -122.4064 }], + mode: "walking" as const, +}; + +afterEach(() => { + globalThis.fetch = realFetch; + if (savedToken === undefined) { + delete process.env.MAPBOX_ACCESS_TOKEN; + } else { + process.env.MAPBOX_ACCESS_TOKEN = savedToken; + } + resetMapsProvider(); + clearMapsCaches(); +}); + +describe("maps.service directions", () => { + test("returns normalized routes from the provider", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + stubFetch(mapboxDirectionsBody()); + + const result = await directions(REQ); + + expect(result.routes).toHaveLength(1); + expect(result.routes[0].totalDistanceMeters).toBe(1234); + expect(result.routes[0].totalDurationSeconds).toBe(567); + // The neutral step carries the road name + mapped maneuver, not Mapbox shapes. + expect(result.routes[0].steps?.[0].road).toBe("Fell St"); + expect(result.routes[0].steps?.[0].maneuver).toBe("DEPART"); + }); + + test("a second identical request is served from cache (no second fetch)", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + const fetchStub = stubFetch(mapboxDirectionsBody()); + + await directions(REQ); + await directions(REQ); + + expect(fetchStub.calls()).toBe(1); + }); + + test("concurrent identical requests coalesce onto one upstream call (in-flight dedup)", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + const fetchStub = stubFetch(mapboxDirectionsBody()); + + // Fire many at once, before the first resolves, so they hit the in-flight + // promise rather than a settled cache entry. + const results = await Promise.all( + Array.from({ length: 50 }, () => directions(REQ)), + ); + + expect(results).toHaveLength(50); + expect(fetchStub.calls()).toBe(1); + }); + + test("a different request is a cache miss (separate fetch)", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + const fetchStub = stubFetch(mapboxDirectionsBody()); + + await directions(REQ); + await directions({ ...REQ, mode: "driving" }); + + expect(fetchStub.calls()).toBe(2); + }); + + test("an upstream failure is NOT cached: the next call retries upstream", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + // First a 500 (provider throws), then a success. + let call = 0; + globalThis.fetch = (async () => { + call += 1; + if (call === 1) return new Response("upstream boom", { status: 500 }); + return new Response(JSON.stringify(mapboxDirectionsBody()), { status: 200 }); + }) as unknown as typeof fetch; + + await expect(directions(REQ)).rejects.toThrow(); + // The failure must have been evicted, so this re-hits upstream and succeeds. + const ok = await directions(REQ); + expect(ok.routes).toHaveLength(1); + expect(call).toBe(2); + }); + + test("throws a clear error when MAPBOX_ACCESS_TOKEN is unset", async () => { + delete process.env.MAPBOX_ACCESS_TOKEN; + stubFetch(mapboxDirectionsBody()); + + await expect(directions(REQ)).rejects.toThrow(/MAPBOX_ACCESS_TOKEN/); + }); +}); + +describe("maps.service reverseGeocode", () => { + test("returns the resolved road name + full address", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + stubFetch(mapboxGeocodeBody("Market St", "1 Market St, San Francisco, California 94105")); + + const result = await reverseGeocode({ lat: 37.7749, lng: -122.4194 }); + + expect(result.road).toBe("Market St"); + expect(result.address).toBe("1 Market St, San Francisco, California 94105"); + }); + + test("returns { road: null, address: null } when nothing is found nearby", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + stubFetch(mapboxGeocodeBody(null)); + + const result = await reverseGeocode({ lat: 0, lng: 0 }); + + expect(result.road).toBeNull(); + expect(result.address).toBeNull(); + }); + + test("coordinates within ~1 m share a cache entry (one fetch)", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + const fetchStub = stubFetch(mapboxGeocodeBody("Market St")); + + // Same 5-decimal grid cell (~1 m) -> one cache key -> one upstream call. + await reverseGeocode({ lat: 37.774901, lng: -122.419401 }); + await reverseGeocode({ lat: 37.774902, lng: -122.419402 }); + + expect(fetchStub.calls()).toBe(1); + }); +}); + +/** A minimal Mapbox Search Box /suggest response. */ +function mapboxSuggestBody(name: string) { + return { + suggestions: [ + { mapbox_id: "abc123", name, place_formatted: `${name}, San Francisco` }, + // A suggestion without a mapbox_id must be dropped (un-retrievable). + { name: "no id place", place_formatted: "somewhere" }, + ], + }; +} + +/** A minimal Mapbox Search Box /retrieve FeatureCollection. */ +function mapboxRetrieveBody() { + return { + features: [ + { + geometry: { coordinates: [-122.4194, 37.7749] }, + properties: { + mapbox_id: "abc123", + name: "Blue Bottle Coffee", + full_address: "66 Mint St, San Francisco, California 94103", + }, + }, + ], + }; +} + +describe("maps.service placeAutocomplete", () => { + test("returns normalized suggestions, dropping ones with no id", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + stubFetch(mapboxSuggestBody("Blue Bottle Coffee")); + + const result = await placeAutocomplete("blue bottle", undefined, "sess-1"); + + expect(result.suggestions).toHaveLength(1); + expect(result.suggestions[0]).toEqual({ + placeId: "abc123", + mainText: "Blue Bottle Coffee", + secondaryText: "Blue Bottle Coffee, San Francisco", + }); + }); + + test("an empty query short-circuits with no upstream call", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + const fetchStub = stubFetch(mapboxSuggestBody("x")); + + const result = await placeAutocomplete(" ", undefined, "sess-1"); + + expect(result.suggestions).toEqual([]); + expect(fetchStub.calls()).toBe(0); + }); + + test("identical (query, session) coalesces onto one upstream call", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + const fetchStub = stubFetch(mapboxSuggestBody("Blue Bottle Coffee")); + + await placeAutocomplete("blue bottle", undefined, "sess-1"); + await placeAutocomplete("Blue Bottle", undefined, "sess-1"); // case-insensitive key + + expect(fetchStub.calls()).toBe(1); + }); +}); + +describe("maps.service placeDetails", () => { + test("resolves a suggestion to coordinates + address", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + stubFetch(mapboxRetrieveBody()); + + const place = await placeDetails("abc123", "sess-1"); + + expect(place).toEqual({ + placeId: "abc123", + name: "Blue Bottle Coffee", + address: "66 Mint St, San Francisco, California 94103", + lat: 37.7749, + lng: -122.4194, + }); + }); + + test("is not cached: a second identical call re-hits upstream", async () => { + process.env.MAPBOX_ACCESS_TOKEN = "pk.test"; + const fetchStub = stubFetch(mapboxRetrieveBody()); + + await placeDetails("abc123", "sess-1"); + await placeDetails("abc123", "sess-1"); + + expect(fetchStub.calls()).toBe(2); + }); +}); diff --git a/cloud-v2/packages/runtime/src/services/maps/maps.service.ts b/cloud-v2/packages/runtime/src/services/maps/maps.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..87333b04b04d0bdc8d4501ba505e049940cc5049 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/maps/maps.service.ts @@ -0,0 +1,250 @@ +/** + * @fileoverview Runtime maps service: geocoding + directions, provider-agnostic. + * + * The API layer owns HTTP/validation; this service owns provider CHOICE and the + * thin domain calls. It only ever touches the `MapsProvider` interface, so it is + * unaware of whether Mapbox or Google is behind it — that is the whole point of + * the abstraction. + * + * Provider is chosen by `MAPS_PROVIDER` (default "mapbox"), mirroring + * `STORAGE_PROVIDER` / `STREAM_PROVIDER`. The provider is built once per process + * and cached; `resetMapsProvider()` clears it for tests / config switches. + * + * Mapbox is the only provider today. The selection switch is intentionally kept + * so adding another vendor (Google, etc.) is a one-file change: implement the + * `MapsProvider` interface in a new `.provider.ts`, add a `case` here, + * and set `MAPS_PROVIDER=`. Nothing else in the service, API, protocol, + * or client changes. + * + * Caching — the real protection against accidental client render loops (the v1 + * cloud was burned by an un-cached geocoding endpoint; this restores that). Both + * caches store the in-flight PROMISE, so concurrent identical requests share one + * upstream call (in-flight dedup), not just sequential ones. We cache the + * NEUTRAL result (Route[] / {road}) above the provider, so the cache is + * provider-agnostic. Failures are never cached, so one upstream blip can't pin an + * error. Ported from the retired V1 navigation service. + * + * See docs/issues/002-cloud-runtime/maps/spec.md. + */ +import type { + DirectionsRequest, + DirectionsResult, + LatLng, + PlaceAutocompleteResult, + PlaceDetailsResult, + PlaceSuggestion, + ReverseGeocodeResult, + Route, +} from "@mentra/cloud-protocol/maps"; +import { createMapboxProvider } from "./providers/mapbox.provider"; +import type { MapsProvider } from "./providers/provider"; + +let provider: MapsProvider | null = null; + +/** The configured maps provider (built once per process). */ +export function getMapsProvider(): MapsProvider { + if (provider) return provider; + const kind = process.env.MAPS_PROVIDER ?? "mapbox"; + switch (kind) { + case "mapbox": + provider = createMapboxProvider(); + break; + default: + // Add a `case ""` above (and a `.provider.ts`) to support + // another maps provider. + throw new Error(`unknown MAPS_PROVIDER: ${kind}`); + } + return provider; +} + +/** Test/boot hook: reset the cached provider (for example to switch config). */ +export function resetMapsProvider(): void { + provider = null; +} + +// --------------------------------------------------------------------------- +// Promise cache (TTL + in-flight dedup, FIFO-bounded) +// --------------------------------------------------------------------------- + +// Routes embed traffic-aware durations, so the cache only needs to outlive a +// render-loop burst, not a reroute cycle. +const ROUTE_CACHE_TTL_MS = 30_000; +const ROUTE_CACHE_MAX_ENTRIES = 500; + +// Road names are effectively static; the mobile road-name resolver re-probes the +// same step midpoints on every route recompute, so long TTLs pay off. +const GEOCODE_CACHE_TTL_MS = 24 * 60 * 60_000; +const GEOCODE_CACHE_MAX_ENTRIES = 5_000; + +// Autocomplete is type-ahead: the same prefix recurs constantly as the user +// backspaces/retypes, but results go stale fast and are session-scoped. A short +// TTL coalesces the burst (and in-flight-dedups concurrent keystrokes) without +// serving yesterday's suggestions. `placeDetails` is a one-shot pick — not +// cached (a retrieve closes the billing session; replaying it buys nothing). +const AUTOCOMPLETE_CACHE_TTL_MS = 60_000; +const AUTOCOMPLETE_CACHE_MAX_ENTRIES = 1_000; + +interface CacheEntry { + // When a SETTLED entry expires. While the upstream call is still in flight + // this is `Infinity`, so a concurrent caller always reuses the pending promise + // (in-flight dedup) instead of firing a second billed request — even if the + // nominal TTL has elapsed. The real TTL clock starts only when the value + // resolves (see `cachedUpstream`). + expiresAt: number; + promise: Promise; +} + +const routeCache = new Map>(); +const geocodeCache = new Map>(); +const autocompleteCache = new Map>(); + +/** Test hook: drop all cached entries. */ +export function clearMapsCaches(): void { + routeCache.clear(); + geocodeCache.clear(); + autocompleteCache.clear(); +} + +/** + * Return the cached promise for `key`, or create one via `fn`. The promise is + * stored BEFORE it settles, so concurrent identical calls coalesce onto one + * upstream request (in-flight dedup) — and they keep coalescing for the whole + * lifetime of that request, not just until its nominal TTL elapses (the entry's + * TTL clock starts on RESOLUTION). A promise that REJECTS is evicted on settle, + * so a failure is never served from cache (and the rejection still propagates to + * every waiter, matching `fn`'s own throw-on-failure contract). + */ +function cachedUpstream( + cache: Map>, + key: string, + ttlMs: number, + maxEntries: number, + fn: () => Promise, +): Promise { + const existing = cache.get(key); + if (existing && existing.expiresAt > Date.now()) { + return existing.promise; + } + + // Insert with `expiresAt: Infinity` so that while this call is in flight, + // concurrent identical calls reuse it regardless of TTL (an upstream that + // stalls past the TTL must not spawn a second billed request). On SUCCESS we + // stamp the real expiry, measured from resolution. On FAILURE we evict so one + // upstream blip can't pin an error. Both branches guard on object identity so + // a concurrent FIFO eviction / refresh can't clobber a newer entry. + const entry: CacheEntry = { + expiresAt: Infinity, + promise: undefined as unknown as Promise, + }; + entry.promise = fn().then( + (value) => { + if (cache.get(key) === entry) { + entry.expiresAt = Date.now() + ttlMs; + } + return value; + }, + (err: unknown) => { + if (cache.get(key) === entry) { + cache.delete(key); + } + throw err; + }, + ); + + cache.set(key, entry); + + // FIFO bound (Map preserves insertion order). At these caps and TTLs a true + // LRU buys nothing. + while (cache.size > maxEntries) { + const oldest = cache.keys().next().value; + if (oldest === undefined) break; + cache.delete(oldest); + } + + return entry.promise; +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/** Compute routes for a directions request. Primary route first, alternates after. */ +export async function directions(req: DirectionsRequest): Promise { + // Key on the normalized request. Render loops / retries resend identical + // inputs; a stable field order keeps those hits (semantically-equal-but- + // reordered inputs simply miss, which is safe). + const key = JSON.stringify({ + origin: req.origin, + stops: req.stops, + mode: req.mode ?? null, + avoid: req.avoid ?? null, + alternatives: req.alternatives ?? null, + }); + const routes = await cachedUpstream( + routeCache, + key, + ROUTE_CACHE_TTL_MS, + ROUTE_CACHE_MAX_ENTRIES, + () => getMapsProvider().directions(req), + ); + return { routes }; +} + +/** + * Resolve a coordinate to a short road name + full formatted address (each null + * when none found nearby). Both are derived from one upstream lookup and cached + * together under the same key. + */ +export async function reverseGeocode(coord: LatLng): Promise { + // ~1 m grid: step midpoints recur exactly on recompute, and probes within a + // meter of each other are the same road by any standard. + const key = `${coord.lat.toFixed(5)},${coord.lng.toFixed(5)}`; + return cachedUpstream( + geocodeCache, + key, + GEOCODE_CACHE_TTL_MS, + GEOCODE_CACHE_MAX_ENTRIES, + () => getMapsProvider().reverseGeocode(coord), + ); +} + +/** + * Type-ahead place search. Cached briefly per (query, near, session) so a burst + * of keystrokes / backspaces over the same prefix coalesces onto one upstream + * call. An empty query short-circuits to no suggestions without a cache entry or + * an upstream call. + */ +export async function placeAutocomplete( + query: string, + near: LatLng | undefined, + sessionToken: string, +): Promise { + if (!query.trim()) return { suggestions: [] }; + // Session token is part of the key: results are session-scoped, and two users + // typing the same prefix must not share a suggestion list / billing session. + const key = JSON.stringify({ + q: query.trim().toLowerCase(), + near: near ? { lat: near.lat.toFixed(3), lng: near.lng.toFixed(3) } : null, + session: sessionToken, + }); + const suggestions = await cachedUpstream( + autocompleteCache, + key, + AUTOCOMPLETE_CACHE_TTL_MS, + AUTOCOMPLETE_CACHE_MAX_ENTRIES, + () => getMapsProvider().placeAutocomplete(query, near, sessionToken), + ); + return { suggestions }; +} + +/** + * Resolve a suggestion (`placeId` + the autocomplete's `sessionToken`) to a full + * place with coordinates. Not cached: a pick is one-shot and the retrieve closes + * the provider's billing session. + */ +export async function placeDetails( + placeId: string, + sessionToken: string, +): Promise { + return getMapsProvider().placeDetails(placeId, sessionToken); +} diff --git a/cloud-v2/packages/runtime/src/services/maps/providers/mapbox.provider.ts b/cloud-v2/packages/runtime/src/services/maps/providers/mapbox.provider.ts new file mode 100644 index 0000000000000000000000000000000000000000..cafdd7208dbfb663a76c3246b840082cb8195b54 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/maps/providers/mapbox.provider.ts @@ -0,0 +1,391 @@ +/** + * @fileoverview Mapbox maps provider. + * + * The ONLY Mapbox-aware code in the runtime. Everything vendor-specific lives + * here: the `api.mapbox.com` endpoints, the access token, polyline6 decoding, + * and the Mapbox maneuver/profile/exclude vocabulary -> our neutral vocabulary. + * It returns the protocol-neutral `Route[]` / `{road}` so callers never see a + * Mapbox shape. + * + * Mirrors the request shapes the mobile host already used against Mapbox + * (mobile/src/services/NavigationService.ts): Directions v5 with + * geometries=polyline6, overview=full, steps=true, banner_instructions=true; + * Geocoding v6 reverse with types=address,street. + */ +import { createLogger } from "@mentra/cloud-shared"; +import type { + DirectionsRequest, + LatLng, + ManeuverKind, + PlaceDetailsResult, + PlaceSuggestion, + Route, + RouteStep, + RouteAvoidances, + TravelMode, +} from "@mentra/cloud-protocol/maps"; +import type { MapsProvider } from "./provider"; + +const logger = createLogger("maps").child({ service: "mapbox.maps.provider" }); + +const DIRECTIONS_BASE = "https://api.mapbox.com/directions/v5/mapbox"; +const GEOCODE_REVERSE_URL = "https://api.mapbox.com/search/geocode/v6/reverse"; +const SEARCHBOX_SUGGEST_URL = "https://api.mapbox.com/search/searchbox/v1/suggest"; +const SEARCHBOX_RETRIEVE_URL = "https://api.mapbox.com/search/searchbox/v1/retrieve"; + +/** Read + validate the token at call time (not module load) so tests/boot can set it late. */ +function getToken(): string { + const token = process.env.MAPBOX_ACCESS_TOKEN; + if (!token) { + throw new Error( + "MAPBOX_ACCESS_TOKEN is not set (required for the Mapbox maps provider)", + ); + } + return token; +} + +/** Our TravelMode -> Mapbox Directions profile. */ +function mapboxProfile(mode: TravelMode | undefined): string { + switch (mode) { + case "walking": + return "walking"; + case "cycling": + return "cycling"; + case "two_wheeler": + // Mapbox has no two-wheeler profile; driving is the closest match. + return "driving"; + case "driving": + default: + return "driving-traffic"; + } +} + +/** Our avoidance flags -> Mapbox `exclude` param value, or null when none apply. */ +function mapboxExclude(avoid: RouteAvoidances | undefined): string | null { + if (!avoid) return null; + const ex: string[] = []; + if (avoid.tolls) ex.push("toll"); + if (avoid.ferries) ex.push("ferry"); + if (avoid.highways) ex.push("motorway"); + return ex.length > 0 ? ex.join(",") : null; +} + +/** Mapbox maneuver `type` + `modifier` -> our neutral ManeuverKind. */ +function mapboxManeuverToKind( + type: string | undefined, + modifier: string | undefined, +): ManeuverKind | undefined { + switch (type) { + case "depart": + return "DEPART"; + case "arrive": + return "ARRIVE"; + case "new name": + return "NAME_CHANGE"; + case "continue": + return "CONTINUE"; + default: + break; + } + switch (modifier) { + case "uturn": + return "U_TURN"; + case "sharp left": + return "SHARP_LEFT"; + case "left": + return "TURN_LEFT"; + case "slight left": + return "SLIGHT_LEFT"; + case "straight": + return "STRAIGHT"; + case "slight right": + return "SLIGHT_RIGHT"; + case "right": + return "TURN_RIGHT"; + case "sharp right": + return "SHARP_RIGHT"; + default: + return undefined; + } +} + +/** Decode a Mapbox precision-6 polyline into [lng,lat]-ordered LatLng points. */ +function decodePolyline6(encoded: string): LatLng[] { + const points: LatLng[] = []; + let index = 0; + let lat = 0; + let lng = 0; + const factor = 1e6; + + while (index < encoded.length) { + let result = 1; + let shift = 0; + let b: number; + do { + b = encoded.charCodeAt(index++) - 63 - 1; + result += b << shift; + shift += 5; + } while (b >= 0x1f); + lat += result & 1 ? ~(result >> 1) : result >> 1; + + result = 1; + shift = 0; + do { + b = encoded.charCodeAt(index++) - 63 - 1; + result += b << shift; + shift += 5; + } while (b >= 0x1f); + lng += result & 1 ? ~(result >> 1) : result >> 1; + + points.push({ lat: lat / factor, lng: lng / factor }); + } + return points; +} + +/** Pull a road name out of a Mapbox Directions step, preferring the named ref. */ +function stepRoad(step: MapboxStep): string | null { + if (typeof step.name === "string" && step.name.trim().length > 0) { + return step.name; + } + if (typeof step.ref === "string" && step.ref.trim().length > 0) { + return step.ref; + } + return null; +} + +// --- Minimal shapes of the Mapbox responses we read ------------------------- +// Deliberately narrow: only the fields this provider consumes, so a Mapbox +// response shape change surfaces here rather than leaking outward. + +interface MapboxManeuver { + type?: string; + modifier?: string; + instruction?: string; +} +interface MapboxStep { + distance?: number; + name?: string; + ref?: string; + maneuver?: MapboxManeuver; + geometry?: string; +} +interface MapboxLeg { + steps?: MapboxStep[]; +} +interface MapboxRoute { + geometry?: string; + distance?: number; + duration?: number; + legs?: MapboxLeg[]; +} +interface MapboxDirectionsResponse { + routes?: MapboxRoute[]; +} + +/** Normalize one Mapbox route into our neutral Route. */ +function toNeutralRoute(mb: MapboxRoute): Route { + const points = mb.geometry ? decodePolyline6(mb.geometry) : []; + const tail = points[points.length - 1]; + + const flatSteps: MapboxStep[] = (mb.legs ?? []).flatMap((leg) => leg.steps ?? []); + const steps: RouteStep[] = flatSteps.map((s, i) => { + const start = s.geometry ? decodePolyline6(s.geometry)[0] : undefined; + const next = flatSteps[i + 1]; + const nextStart = next?.geometry ? decodePolyline6(next.geometry)[0] : undefined; + const lat = start?.lat ?? tail?.lat ?? 0; + const lng = start?.lng ?? tail?.lng ?? 0; + return { + lat, + lng, + endLat: nextStart?.lat ?? tail?.lat ?? lat, + endLng: nextStart?.lng ?? tail?.lng ?? lng, + distanceMeters: s.distance ?? 0, + maneuver: mapboxManeuverToKind(s.maneuver?.type, s.maneuver?.modifier), + instruction: s.maneuver?.instruction, + road: stepRoad(s), + }; + }); + + return { + points, + totalDistanceMeters: mb.distance ?? 0, + totalDurationSeconds: mb.duration ?? 0, + steps: steps.length > 0 ? steps : undefined, + }; +} + +export function createMapboxProvider(): MapsProvider { + return { + name: "mapbox", + + async directions(req: DirectionsRequest): Promise { + const token = getToken(); + const profile = mapboxProfile(req.mode); + // Mapbox wants `lng,lat;lng,lat;...` with origin first, then each stop. + const coords = [req.origin, ...req.stops] + .map((c) => `${c.lng},${c.lat}`) + .join(";"); + + const params = new URLSearchParams({ + access_token: token, + geometries: "polyline6", + overview: "full", + steps: "true", + banner_instructions: "true", + alternatives: String((req.alternatives ?? 1) > 1), + }); + const exclude = mapboxExclude(req.avoid); + if (exclude) params.set("exclude", exclude); + + // Walking-only: bias Mapbox's routing toward walkways/footpaths so the + // route follows the SIDEWALK rather than the road centerline — but ONLY + // where OSM has the sidewalk mapped as a separate footway. Where it isn't + // mapped, Mapbox has nothing to bias toward and returns the road as + // before (no fake offset). `walkway_bias` is a walking-profile-only param; + // Mapbox rejects it on driving/cycling, so it's gated on the profile. + if (profile === "walking") { + params.set("walkway_bias", "1"); + } + + const url = `${DIRECTIONS_BASE}/${profile}/${coords}?${params.toString()}`; + const res = await fetch(url); + if (!res.ok) { + const body = await res.text().catch(() => ""); + logger.error({ status: res.status, body }, "mapbox directions request failed"); + throw new Error(`mapbox directions failed: ${res.status}`); + } + const data = (await res.json()) as MapboxDirectionsResponse; + return (data.routes ?? []).map(toNeutralRoute); + }, + + async reverseGeocode( + coord: LatLng, + ): Promise<{ road: string | null; address: string | null }> { + const token = getToken(); + const params = new URLSearchParams({ + access_token: token, + longitude: String(coord.lng), + latitude: String(coord.lat), + // `address` first so the top feature carries the house number (and thus + // `full_address`); `street`/`place` keep us returning SOMETHING for a + // coord with no exact street address. + types: "address,street,place", + limit: "1", + }); + const url = `${GEOCODE_REVERSE_URL}?${params.toString()}`; + const res = await fetch(url); + if (!res.ok) { + const body = await res.text().catch(() => ""); + logger.error({ status: res.status, body }, "mapbox reverse geocode failed"); + throw new Error(`mapbox reverse geocode failed: ${res.status}`); + } + const data = (await res.json()) as { + features?: Array<{ + properties?: { + name?: string; + full_address?: string; + place_formatted?: string; + context?: { street?: { name?: string } }; + }; + }>; + }; + const feature = data.features?.[0]?.properties; + // Short road name for the pivot fallback… + const road = feature?.context?.street?.name ?? feature?.name ?? null; + // …and the full formatted address for dropped-pin / POI labels. Prefer + // `full_address` (carries the house number), fall back to `name` then + // `place_formatted`. + const address = + feature?.full_address ?? feature?.name ?? feature?.place_formatted ?? null; + return { road: road ?? null, address: address ?? null }; + }, + + async placeAutocomplete( + query: string, + near: LatLng | undefined, + sessionToken: string, + ): Promise { + // An empty query is a no-op, not an upstream call — Search Box would 422. + if (!query.trim()) return []; + const token = getToken(); + const params = new URLSearchParams({ + q: query, + access_token: token, + session_token: sessionToken, + // POIs + addresses + places — the things a user navigates to. + types: "poi,address,place,street", + limit: "10", + }); + // Bias toward the user's location when we have it (Mapbox wants lng,lat). + if (near) params.set("proximity", `${near.lng},${near.lat}`); + + const url = `${SEARCHBOX_SUGGEST_URL}?${params.toString()}`; + const res = await fetch(url); + if (!res.ok) { + const body = await res.text().catch(() => ""); + logger.error({ status: res.status, body }, "mapbox searchbox suggest failed"); + throw new Error(`mapbox place autocomplete failed: ${res.status}`); + } + const data = (await res.json()) as { + suggestions?: Array<{ + mapbox_id?: string; + name?: string; + place_formatted?: string; + full_address?: string; + }>; + }; + return (data.suggestions ?? []) + // Only suggestions we can later retrieve (need a mapbox_id) are useful. + .filter((s): s is { mapbox_id: string } & typeof s => !!s.mapbox_id) + .map((s) => ({ + placeId: s.mapbox_id, + mainText: s.name ?? "", + secondaryText: s.place_formatted ?? s.full_address ?? "", + })); + }, + + async placeDetails( + placeId: string, + sessionToken: string, + ): Promise { + const token = getToken(); + const params = new URLSearchParams({ + access_token: token, + session_token: sessionToken, + }); + const url = `${SEARCHBOX_RETRIEVE_URL}/${encodeURIComponent(placeId)}?${params.toString()}`; + const res = await fetch(url); + if (!res.ok) { + const body = await res.text().catch(() => ""); + logger.error({ status: res.status, body }, "mapbox searchbox retrieve failed"); + throw new Error(`mapbox place details failed: ${res.status}`); + } + // Retrieve returns a GeoJSON FeatureCollection; the picked place is the + // first feature. Coordinates are [lng, lat]. + const data = (await res.json()) as { + features?: Array<{ + geometry?: { coordinates?: [number, number] }; + properties?: { + mapbox_id?: string; + name?: string; + full_address?: string; + place_formatted?: string; + }; + }>; + }; + const feature = data.features?.[0]; + const coords = feature?.geometry?.coordinates; + if (!coords || coords.length < 2) { + throw new Error("mapbox place details: no coordinates in response"); + } + const props = feature?.properties; + return { + placeId: props?.mapbox_id ?? placeId, + name: props?.name ?? "", + address: props?.full_address ?? props?.place_formatted ?? "", + lat: coords[1], + lng: coords[0], + }; + }, + }; +} diff --git a/cloud-v2/packages/runtime/src/services/maps/providers/provider.ts b/cloud-v2/packages/runtime/src/services/maps/providers/provider.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa977989bc7f0de570a5974bc76d8f501592187a --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/maps/providers/provider.ts @@ -0,0 +1,64 @@ +/** + * @fileoverview The maps provider contract. + * + * This interface is the line where a vendor's dialect becomes our one neutral + * vocabulary. It speaks ONLY in the protocol-neutral types from + * `protocol/maps` (LatLng, Route, TravelMode, ...) — never a vendor's JSON + * shape. Each implementation owns its own HTTP endpoints, auth token, response + * decoding, and maneuver/profile mapping, and returns these neutral types. + * + * Mapbox (mapbox.provider) is the only implementation today. Adding a vendor + * (Google, etc.) is therefore: write one `createProvider()` that + * satisfies this interface, then teach `maps.service` to select it by env var. + * Nothing else in the service, API, protocol, or client changes. + * + * Following the codebase convention (StorageProvider, StreamProvider), providers + * are built by a factory function and expose a `readonly name` for diagnostics. + */ +import type { + DirectionsRequest, + LatLng, + PlaceDetailsResult, + PlaceSuggestion, + Route, +} from "@mentra/cloud-protocol/maps"; + +export interface MapsProvider { + /** Diagnostic label, e.g. "mapbox". */ + readonly name: string; + + /** + * Compute one or more routes from `origin` through `stops`. Returns the + * primary route first, alternates after. Throws on a provider/transport + * failure; an empty `[]` means the provider found no route. + */ + directions(req: DirectionsRequest): Promise; + + /** + * Resolve a coordinate to a short road name (`road`) and a full formatted + * street address (`address`). Either field is null when nothing of that kind + * was found near the coordinate (a successful empty answer); throws only on an + * actual provider/transport failure. + */ + reverseGeocode(coord: LatLng): Promise<{ road: string | null; address: string | null }>; + + /** + * Type-ahead place search. Returns lightweight suggestions for `query`, + * optionally biased toward `near`. `sessionToken` groups this with the + * following `placeDetails` call into one billed search session. Resolves `[]` + * for an empty/whitespace query; throws only on a provider/transport failure. + */ + placeAutocomplete( + query: string, + near: LatLng | undefined, + sessionToken: string, + ): Promise; + + /** + * Resolve a suggestion's `placeId` (from `placeAutocomplete`) to a full place + * with coordinates. `sessionToken` must match the autocomplete that produced + * the id so the provider closes the billing session. Throws on a + * provider/transport failure or an unresolvable id. + */ + placeDetails(placeId: string, sessionToken: string): Promise; +} diff --git a/cloud-v2/packages/runtime/src/services/meetings/acs-teams.service.test.ts b/cloud-v2/packages/runtime/src/services/meetings/acs-teams.service.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..91e3ea8f6e46ec6db4dab138585453401a892a7f --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/meetings/acs-teams.service.test.ts @@ -0,0 +1,396 @@ +import {afterEach, beforeEach, describe, expect, test} from "bun:test" + +import { + ACS_GUEST_STATE_MAX_ENTRIES, + getAcsGuestStateSizeForTests, + mintAcsGuestToken, + resetAcsTeamsAuthCache, + setAcsIdentityClientForTests, + bindTeamsSubject, + exchangeAcsTeamsUserToken, + type AcsIdentityClient, +} from "./acs-teams.service" + +describe("ACS Teams opaque subject tokens", () => { + const names = ["ENTRA_TENANT_ID", "ENTRA_CLIENT_ID", "ACS_CONNECTION_STRING"] as const + let saved: (string | undefined)[] + const expected = {tenantId: "tenant-1", objectId: "employee-1"} + beforeEach(() => { + saved = names.map((name) => process.env[name]) + process.env.ENTRA_TENANT_ID = expected.tenantId + process.env.ENTRA_CLIENT_ID = "mobile-client" + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + }) + afterEach(() => { + names.forEach((name, i) => { + if (saved[i] === undefined) delete process.env[name] + else process.env[name] = saved[i] + }) + resetAcsTeamsAuthCache() + }) + + test("lets Microsoft validate opaque tokens against the trusted user and application", async () => { + const opaque = "opaque-microsoft-token-not-a-jwt" + setAcsIdentityClientForTests({ + async createUserAndToken() { + throw new Error("must not mint a guest") + }, + async getTokenForTeamsUser(input) { + expect(input).toEqual({teamsUserAadToken: opaque, userObjectId: expected.objectId, clientId: "mobile-client"}) + return {token: "teams-credential", expiresOn: new Date("2030-01-01")} + }, + }) + expect(await exchangeAcsTeamsUserToken(bindTeamsSubject(opaque, expected))).toMatchObject({ + identityMode: "teams-user", + }) + }) + + test("rejects a foreign Runtime tenant before contacting Microsoft", () => { + expect(() => bindTeamsSubject("opaque", {...expected, tenantId: "other"})).toThrow("Runtime identity") + expect(() => bindTeamsSubject("opaque", {...expected, objectId: ""})).toThrow("Runtime identity") + }) + + test.each([400, 401, 403, 429, 500])( + "preserves Microsoft rejection %s without leaking its request", + async (statusCode) => { + setAcsIdentityClientForTests({ + async createUserAndToken() { + throw new Error("must not mint a guest") + }, + async getTokenForTeamsUser() { + throw Object.assign(new Error("secret-token"), {statusCode, request: {body: "secret-token"}}) + }, + }) + try { + await exchangeAcsTeamsUserToken(bindTeamsSubject("opaque", expected)) + throw new Error("expected failure") + } catch (error) { + expect(String(error)).not.toContain("secret-token") + expect(String(error)).toContain( + statusCode < 429 ? "could not verify" : statusCode === 429 ? "busy" : "unavailable", + ) + } + }, + ) +}) + +describe("ACS guest credentials", () => { + const previousConnectionString = process.env.ACS_CONNECTION_STRING + + afterEach(() => { + resetAcsTeamsAuthCache() + if (previousConnectionString === undefined) delete process.env.ACS_CONNECTION_STRING + else process.env.ACS_CONNECTION_STRING = previousConnectionString + }) + + test("creates one guest identity and reuses its fresh token for the authenticated user", async () => { + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + let creates = 0 + const expiresOn = new Date(Date.now() + 60 * 60 * 1000) + setAcsIdentityClientForTests({ + async createUserAndToken(scopes, options) { + creates += 1 + expect(scopes).toEqual(["voip"]) + expect(options.tokenExpiresInMinutes).toBe(120) + return { + token: "guest-token", + expiresOn, + user: {communicationUserId: "guest-user"}, + } + }, + async getTokenForTeamsUser() { + throw new Error("not used") + }, + } satisfies AcsIdentityClient) + + const first = await mintAcsGuestToken("tenant:user") + const second = await mintAcsGuestToken("tenant:user") + + expect(first).toEqual({ + token: "guest-token", + expiresOn: expiresOn.toISOString(), + identityMode: "guest", + acsUserId: "guest-user", + }) + expect(second).toEqual(first) + expect(creates).toBe(1) + }) + + test("shares one ACS request across concurrent guest-token callers", async () => { + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + let creates = 0 + let releaseCreate: (() => void) | undefined + const createMayFinish = new Promise((resolve) => { + releaseCreate = resolve + }) + setAcsIdentityClientForTests({ + async createUserAndToken() { + creates += 1 + await createMayFinish + return { + token: "shared-token", + expiresOn: new Date(Date.now() + 60 * 60 * 1000), + user: {communicationUserId: "shared-user"}, + } + }, + async getTokenForTeamsUser() { + throw new Error("not used") + }, + } satisfies AcsIdentityClient) + + const requests = Array.from({length: 20}, () => mintAcsGuestToken("tenant:concurrent-user")) + for (let attempt = 0; attempt < 10 && creates === 0; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } + expect(creates).toBe(1) + releaseCreate?.() + + const credentials = await Promise.all(requests) + expect(new Set(credentials.map(({token}) => token))).toEqual(new Set(["shared-token"])) + expect(creates).toBe(1) + }) + + test("preserves an existing ACS identity across transient refresh failures", async () => { + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + let creates = 0 + let refreshes = 0 + setAcsIdentityClientForTests({ + async createUserAndToken() { + creates += 1 + return { + token: "expired-token", + expiresOn: new Date(0), + user: {communicationUserId: "stable-user"}, + } + }, + async getToken(user) { + expect(user.communicationUserId).toBe("stable-user") + refreshes += 1 + if (refreshes === 1) throw {status: 401, code: "Denied"} + return { + token: "refreshed-token", + expiresOn: new Date(Date.now() + 60 * 60 * 1000), + } + }, + async getTokenForTeamsUser() { + throw new Error("not used") + }, + } satisfies AcsIdentityClient) + + await mintAcsGuestToken("tenant:stable-user") + await expect(mintAcsGuestToken("tenant:stable-user")).rejects.toMatchObject({status: 502}) + const refreshed = await mintAcsGuestToken("tenant:stable-user") + + expect(refreshed).toMatchObject({ + token: "refreshed-token", + acsUserId: "stable-user", + }) + expect(creates).toBe(1) + expect(refreshes).toBe(2) + }) + + test("replaces an ACS identity after IdentityNotFound from the provider", async () => { + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + let creates = 0 + setAcsIdentityClientForTests({ + async createUserAndToken() { + creates += 1 + return { + token: `guest-token-${creates}`, + expiresOn: creates === 1 ? new Date(0) : new Date(Date.now() + 60 * 60 * 1000), + user: {communicationUserId: `guest-user-${creates}`}, + } + }, + async getToken() { + throw {status: 401, code: "IdentityNotFound"} + }, + async getTokenForTeamsUser() { + throw new Error("not used") + }, + } satisfies AcsIdentityClient) + + await mintAcsGuestToken("tenant:missing-user") + await expect(mintAcsGuestToken("tenant:missing-user")).rejects.toMatchObject({status: 502}) + const replacement = await mintAcsGuestToken("tenant:missing-user") + + expect(replacement.acsUserId).toBe("guest-user-2") + expect(creates).toBe(2) + }) + + test("limits repeated guest-token mints for one authenticated user", async () => { + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + let tokenNumber = 0 + const expiredCredential = () => ({ + token: `guest-token-${++tokenNumber}`, + expiresOn: new Date(0), + }) + setAcsIdentityClientForTests({ + async createUserAndToken() { + return { + ...expiredCredential(), + user: {communicationUserId: "guest-user"}, + } + }, + async getToken() { + return expiredCredential() + }, + async getTokenForTeamsUser() { + throw new Error("not used") + }, + } satisfies AcsIdentityClient) + + for (let attempt = 0; attempt < 12; attempt += 1) { + await mintAcsGuestToken("tenant:rate-limited-user") + } + await expect(mintAcsGuestToken("tenant:rate-limited-user")).rejects.toMatchObject({status: 429}) + }) + + test("bounds guest identity state without evicting live ACS identities", async () => { + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + setAcsIdentityClientForTests({ + async createUserAndToken() { + return { + token: "guest-token", + expiresOn: new Date(Date.now() + 60 * 60 * 1000), + user: {communicationUserId: "guest-user"}, + } + }, + async getTokenForTeamsUser() { + throw new Error("not used") + }, + } satisfies AcsIdentityClient) + + for (let userNumber = 0; userNumber < ACS_GUEST_STATE_MAX_ENTRIES + 2; userNumber += 1) { + if (userNumber < ACS_GUEST_STATE_MAX_ENTRIES) { + await mintAcsGuestToken(`tenant:user-${userNumber}`) + } else { + await expect(mintAcsGuestToken(`tenant:user-${userNumber}`)).rejects.toMatchObject({status: 503}) + } + } + + expect(getAcsGuestStateSizeForTests()).toBe(ACS_GUEST_STATE_MAX_ENTRIES) + }) + + test("deletes an expired idle ACS identity before evicting its state", async () => { + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + const originalNow = Date.now + const deletedUsers: string[] = [] + let now = 1_000_000 + Date.now = () => now + try { + setAcsIdentityClientForTests({ + async createUserAndToken() { + return { + token: "guest-token", + expiresOn: new Date(now + 60 * 60 * 1000), + user: {communicationUserId: "guest-user"}, + } + }, + async deleteUser(user) { + deletedUsers.push(user.communicationUserId) + }, + async getTokenForTeamsUser() { + throw new Error("not used") + }, + } satisfies AcsIdentityClient) + + await mintAcsGuestToken("tenant:idle-user") + now += 4 * 60 * 60 * 1000 + 1 + await mintAcsGuestToken("tenant:new-user") + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(deletedUsers).toEqual(["guest-user"]) + expect(getAcsGuestStateSizeForTests()).toBe(1) + } finally { + Date.now = originalNow + } + }) + + test("evicts idle state when ACS reports the identity is already gone", async () => { + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + const originalNow = Date.now + let now = 1_000_000 + let creates = 0 + Date.now = () => now + try { + setAcsIdentityClientForTests({ + async createUserAndToken() { + creates += 1 + return { + token: `guest-token-${creates}`, + expiresOn: new Date(now + 60 * 60 * 1000), + user: {communicationUserId: `guest-user-${creates}`}, + } + }, + async deleteUser() { + throw {status: 404, code: "IdentityNotFound"} + }, + async getTokenForTeamsUser() { + throw new Error("not used") + }, + } satisfies AcsIdentityClient) + + await mintAcsGuestToken("tenant:gone-user") + now += 4 * 60 * 60 * 1000 + 1 + await mintAcsGuestToken("tenant:new-user") + + const replacement = await mintAcsGuestToken("tenant:gone-user") + expect(replacement.acsUserId).toBe("guest-user-3") + expect(getAcsGuestStateSizeForTests()).toBe(2) + } finally { + Date.now = originalNow + } + }) + + test("does not block unrelated issuance or delete a returning user's active identity", async () => { + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + const originalNow = Date.now + let now = 1_000_000 + let creates = 0 + let releaseDeletion: (() => void) | undefined + const deletionMayFinish = new Promise((resolve) => { + releaseDeletion = resolve + }) + Date.now = () => now + try { + setAcsIdentityClientForTests({ + async createUserAndToken() { + creates += 1 + return { + token: `guest-token-${creates}`, + expiresOn: new Date(now + 60 * 60 * 1000), + user: {communicationUserId: `guest-user-${creates}`}, + } + }, + async deleteUser() { + await deletionMayFinish + }, + async getToken() { + throw new Error("cleanup must finish before a returning user mints") + }, + async getTokenForTeamsUser() { + throw new Error("not used") + }, + } satisfies AcsIdentityClient) + + await mintAcsGuestToken("tenant:idle-user") + now += 4 * 60 * 60 * 1000 + 1 + + const unrelated = await mintAcsGuestToken("tenant:new-user") + expect(unrelated.acsUserId).toBe("guest-user-2") + + let returningFinished = false + const returning = mintAcsGuestToken("tenant:idle-user").then((credential) => { + returningFinished = true + return credential + }) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(returningFinished).toBe(false) + + releaseDeletion?.() + expect((await returning).acsUserId).toBe("guest-user-3") + } finally { + Date.now = originalNow + } + }) +}) diff --git a/cloud-v2/packages/runtime/src/services/meetings/acs-teams.service.ts b/cloud-v2/packages/runtime/src/services/meetings/acs-teams.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ae2a6707682985e6407c49e8b25cd2b298631b3 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/meetings/acs-teams.service.ts @@ -0,0 +1,354 @@ +import {CommunicationIdentityClient, type CommunicationUserToken} from "@azure/communication-identity" + +export const ACS_GUEST_TOKEN_EXPIRES_IN_MINUTES = 120 +export const ACS_GUEST_MINT_LIMIT_PER_WINDOW = 12 +export const ACS_GUEST_MINT_WINDOW_MS = 10 * 60 * 1000 +export const ACS_GUEST_TOKEN_REUSE_MIN_REMAINING_MS = 15 * 60 * 1000 +export const ACS_GUEST_STATE_IDLE_TTL_MS = 4 * 60 * 60 * 1000 +export const ACS_GUEST_STATE_MAX_ENTRIES = 10_000 +const ACS_GUEST_STATE_SWEEP_INTERVAL_MS = 5 * 60 * 1000 +const ACS_GUEST_STATE_SWEEP_BATCH_SIZE = 25 + +export interface AcsIdentityClient { + createUserAndToken( + scopes: string[], + options: {tokenExpiresInMinutes: number}, + ): Promise> + getToken?( + user: {communicationUserId: string}, + scopes: string[], + options: {tokenExpiresInMinutes: number}, + ): Promise> + deleteUser?(user: {communicationUserId: string}): Promise + getTokenForTeamsUser(input: { + teamsUserAadToken: string + clientId: string + userObjectId: string + }): Promise<{token: string; expiresOn: Date}> +} + +export type AcsMeetingCredential = + | { + token: string + expiresOn: string + identityMode: "guest" + acsUserId: string + guestReason?: "teams-license-unavailable" + } + | { + token: string + expiresOn: string + identityMode: "teams-user" + } + +interface GuestMintState { + mints: number[] + acsUserId?: string + cached?: Extract + inFlight?: Promise> + cleanupInFlight?: Promise + lastAccessedAt: number +} + +const guestMintState = new Map() +let lastGuestStateSweepAt = 0 +let testClient: AcsIdentityClient | null = null + +export class TeamsIdentityRejectedError extends Error { + constructor(message: string) { + super(message) + this.name = "TeamsIdentityRejectedError" + } +} + +export class AcsCredentialError extends Error { + constructor( + message: string, + readonly status: 429 | 502 | 503, + ) { + super(message) + this.name = "AcsCredentialError" + } +} + +export interface TeamsSubject { + token: string + tenantId: string + objectId: string +} + +export function assertAcsTeamsConfigured(): void { + if (!process.env.ACS_CONNECTION_STRING?.trim()) throw new Error("meetings service requires ACS_CONNECTION_STRING") +} + +/** + * Bind the opaque Microsoft token to our authenticated Runtime caller. ACS, the + * token's resource server, validates it with the expected userObjectId/clientId. + * Microsoft-owned access tokens are not necessarily readable JWTs: + * https://learn.microsoft.com/entra/identity-platform/access-tokens#token-ownership + */ +export function bindTeamsSubject(token: string, expected: {tenantId: string; objectId: string}): TeamsSubject { + const {tenantId} = teamsUserConfiguration() + if (expected.tenantId !== tenantId || !expected.objectId) + throw new TeamsIdentityRejectedError("Teams token subject does not match Runtime identity") + return {token, tenantId, objectId: expected.objectId} +} + +export async function exchangeAcsTeamsUserToken( + subject: TeamsSubject, +): Promise> { + const {tenantId, clientId} = teamsUserConfiguration() + if (subject.tenantId !== tenantId || !subject.objectId) + throw new TeamsIdentityRejectedError("Teams token subject does not match Runtime identity") + const client = identityClient() + let result + try { + // These trusted identifiers must never come from the request body or a decoded + // access token. Microsoft validates both against its opaque token. + result = await client.getTokenForTeamsUser({ + teamsUserAadToken: subject.token, + clientId, + userObjectId: subject.objectId, + }) + } catch (error) { + if (isTeamsLicenseUnavailable(error)) throw error + const status = error && typeof error === "object" && "statusCode" in error ? error.statusCode : undefined + if (status === 400 || status === 401 || status === 403) + throw new TeamsIdentityRejectedError( + "Microsoft could not verify your Teams account. Sign in again or contact your administrator", + ) + if (status === 429) throw new AcsCredentialError("Microsoft Teams is busy; try again later", 429) + // Azure errors can include the request (and its bearer). Never forward/log them. + throw new AcsCredentialError("Teams identity provider unavailable", 502) + } + return { + token: result.token, + expiresOn: result.expiresOn.toISOString(), + identityMode: "teams-user", + } +} + +/** Only Microsoft's explicit license rejection permits automatic guest joining. */ +export function isTeamsLicenseUnavailable(error: unknown): boolean { + return ( + typeof error === "object" && error !== null && "code" in error && error.code === "UserLicenseNotPresentForbidden" + ) +} + +/** The subject identifiers must come from the authenticated Runtime user. */ +export async function issueAcsTeamsCredential( + subject: TeamsSubject, + authenticatedUserId: string, +): Promise { + try { + return await exchangeAcsTeamsUserToken(subject) + } catch (error) { + if (!isTeamsLicenseUnavailable(error)) throw error + return {...(await mintAcsGuestToken(authenticatedUserId)), guestReason: "teams-license-unavailable"} + } +} + +export async function mintAcsGuestToken( + authenticatedUserId: string, +): Promise> { + const now = Date.now() + const state = await guestStateFor(authenticatedUserId, now) + if (state.cached && Date.parse(state.cached.expiresOn) - now > ACS_GUEST_TOKEN_REUSE_MIN_REMAINING_MS) { + return state.cached + } + if (state.inFlight) return state.inFlight + + const mint = mintGuestTokenForState(state, now) + state.inFlight = mint + try { + return await mint + } finally { + if (state.inFlight === mint) state.inFlight = undefined + state.lastAccessedAt = Date.now() + } +} + +async function mintGuestTokenForState( + state: GuestMintState, + now: number, +): Promise> { + enforceGuestMintLimit(state, now) + + try { + const client = identityClient() + const options = { + tokenExpiresInMinutes: ACS_GUEST_TOKEN_EXPIRES_IN_MINUTES, + } + let credential: Extract + if (state.acsUserId && client.getToken) { + const result = await client.getToken({communicationUserId: state.acsUserId}, ["voip"], options) + credential = { + token: result.token, + expiresOn: result.expiresOn.toISOString(), + identityMode: "guest", + acsUserId: state.acsUserId, + } + } else { + const result = await client.createUserAndToken(["voip"], options) + credential = { + token: result.token, + expiresOn: result.expiresOn.toISOString(), + identityMode: "guest", + acsUserId: result.user.communicationUserId, + } + } + state.acsUserId = credential.acsUserId + state.cached = credential + return credential + } catch (error) { + if (error instanceof AcsCredentialError) throw error + // Only a confirmed missing ACS user invalidates the reusable identity. + // Network, throttling, and provider failures must not rotate the caller to + // a new communication user on the next retry. + if (isMissingAcsUserError(error)) { + state.acsUserId = undefined + state.cached = undefined + } + throw new AcsCredentialError("Teams meeting provider unavailable", 502) + } +} + +export function resetAcsTeamsAuthCache(): void { + guestMintState.clear() + lastGuestStateSweepAt = 0 + testClient = null +} + +/** Test-only observation for the bounded in-process guest state. */ +export function getAcsGuestStateSizeForTests(): number { + return guestMintState.size +} + +/** Test-only seam for exercising both ACS identity operations without Azure. */ +export function setAcsIdentityClientForTests(client: AcsIdentityClient | null): void { + testClient = client + guestMintState.clear() + lastGuestStateSweepAt = 0 +} + +function identityClient(): AcsIdentityClient { + assertAcsTeamsConfigured() + return testClient ?? new CommunicationIdentityClient(process.env.ACS_CONNECTION_STRING!) +} + +function teamsUserConfiguration(): { + tenantId: string + clientId: string +} { + const tenantId = process.env.ENTRA_TENANT_ID?.trim() + const clientId = process.env.ENTRA_CLIENT_ID?.trim() + if (!tenantId || !clientId) { + throw new AcsCredentialError("Microsoft Teams employee identity is not configured", 503) + } + return {tenantId, clientId} +} + +async function guestStateFor(authenticatedUserId: string, now: number): Promise { + let state = guestMintState.get(authenticatedUserId) + if (state) { + if (state.cleanupInFlight) { + await state.cleanupInFlight + return guestStateFor(authenticatedUserId, Date.now()) + } + state.lastAccessedAt = now + return state + } + + pruneGuestMintState(now) + if (guestMintState.size >= ACS_GUEST_STATE_MAX_ENTRIES) { + const cleanup = [...guestMintState.values()].find(({cleanupInFlight}) => cleanupInFlight)?.cleanupInFlight + if (cleanup) { + await cleanup + if (guestMintState.size >= ACS_GUEST_STATE_MAX_ENTRIES) { + throw new AcsCredentialError("Teams credential service is temporarily at capacity", 503) + } + return guestStateFor(authenticatedUserId, Date.now()) + } + throw new AcsCredentialError("Teams credential service is temporarily at capacity", 503) + } + + state = {mints: [], lastAccessedAt: now} + guestMintState.set(authenticatedUserId, state) + return state +} + +function pruneGuestMintState(now: number): void { + if ( + now - lastGuestStateSweepAt >= ACS_GUEST_STATE_SWEEP_INTERVAL_MS || + guestMintState.size >= ACS_GUEST_STATE_MAX_ENTRIES + ) { + lastGuestStateSweepAt = now + let started = 0 + for (const [userId, state] of guestMintState) { + if ( + started < ACS_GUEST_STATE_SWEEP_BATCH_SIZE && + !state.inFlight && + !state.cleanupInFlight && + now - state.lastAccessedAt >= ACS_GUEST_STATE_IDLE_TTL_MS + ) { + startGuestStateCleanup(userId, state) + started += 1 + } + } + } +} + +function startGuestStateCleanup(userId: string, state: GuestMintState): void { + const client = identityClient() + if (state.acsUserId && !client.deleteUser) return + const deletion = state.acsUserId + ? Promise.resolve().then(() => client.deleteUser!({communicationUserId: state.acsUserId!})) + : Promise.resolve() + const cleanup = deletion + .then( + () => true, + (error) => isMissingAcsUserError(error), + ) + .then((identityIsGone) => { + if ( + identityIsGone && + guestMintState.get(userId) === state && + state.cleanupInFlight === cleanup && + !state.inFlight + ) { + guestMintState.delete(userId) + } + }) + .finally(() => { + // Retain the mapping when ACS cleanup fails transiently so we never lose + // track of a persistent identity and create an orphan on the next request. + if (guestMintState.get(userId) === state && state.cleanupInFlight === cleanup) { + state.cleanupInFlight = undefined + } + }) + state.cleanupInFlight = cleanup +} + +function isMissingAcsUserError(error: unknown): boolean { + if (!error || typeof error !== "object") return false + const candidate = error as { + status?: unknown + statusCode?: unknown + code?: unknown + } + return ( + candidate.status === 404 || + candidate.statusCode === 404 || + candidate.code === "ResourceNotFound" || + candidate.code === "UserNotFound" || + candidate.code === "IdentityNotFound" + ) +} + +function enforceGuestMintLimit(state: GuestMintState, now: number): void { + state.mints = state.mints.filter((mintedAt) => now - mintedAt < ACS_GUEST_MINT_WINDOW_MS) + if (state.mints.length >= ACS_GUEST_MINT_LIMIT_PER_WINDOW) { + throw new AcsCredentialError("Too many Teams credential requests. Try again in a few minutes.", 429) + } + state.mints.push(now) +} diff --git a/cloud-v2/packages/runtime/src/services/meetings/meeting-providers.test.ts b/cloud-v2/packages/runtime/src/services/meetings/meeting-providers.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9202356099301fc3e3a9760360d187691c6472cc --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/meetings/meeting-providers.test.ts @@ -0,0 +1,16 @@ +import {describe, expect, test} from "bun:test"; + +import {resolveMeetingProviders} from "./meeting-providers"; + +describe("Runtime meeting providers", () => { + test("selects the ACS Teams implementation explicitly", () => { + expect([...resolveMeetingProviders("acs-teams")]).toEqual(["acs-teams"]); + }); + + test("rejects missing and unknown providers", () => { + expect(() => resolveMeetingProviders("")).toThrow("MEETING_PROVIDERS"); + expect(() => resolveMeetingProviders("zoom")).toThrow( + "unknown providers: zoom", + ); + }); +}); diff --git a/cloud-v2/packages/runtime/src/services/meetings/meeting-providers.ts b/cloud-v2/packages/runtime/src/services/meetings/meeting-providers.ts new file mode 100644 index 0000000000000000000000000000000000000000..54f40b9c0c8e14b18d2dcaaf550eb18c80a2ba46 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/meetings/meeting-providers.ts @@ -0,0 +1,26 @@ +export const MEETING_PROVIDER_NAMES = ["acs-teams"] as const; + +export type MeetingProviderName = (typeof MEETING_PROVIDER_NAMES)[number]; + +export function resolveMeetingProviders( + value = process.env.MEETING_PROVIDERS, +): Set { + const requested = (value ?? "") + .split(",") + .map((entry) => entry.trim()) + .filter(Boolean); + if (requested.length === 0) { + throw new Error( + "meetings service requires at least one MEETING_PROVIDERS value", + ); + } + + const known = new Set(MEETING_PROVIDER_NAMES); + const unknown = requested.filter((entry) => !known.has(entry)); + if (unknown.length > 0) { + throw new Error( + `MEETING_PROVIDERS contains unknown providers: ${unknown.join(", ")}`, + ); + } + return new Set(requested as MeetingProviderName[]); +} diff --git a/cloud-v2/packages/runtime/src/services/meetings/teams-identity-selection.test.ts b/cloud-v2/packages/runtime/src/services/meetings/teams-identity-selection.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..36a25aea3d134866b0fb496b7347c3a44afd4f0c --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/meetings/teams-identity-selection.test.ts @@ -0,0 +1,73 @@ +import {afterEach, beforeEach, describe, expect, test} from "bun:test" +import {issueAcsTeamsCredential, resetAcsTeamsAuthCache, setAcsIdentityClientForTests} from "./acs-teams.service" + +const subject = {token: "verified-subject", tenantId: "tenant", objectId: "employee"} +const saved = { + connection: process.env.ACS_CONNECTION_STRING, + tenant: process.env.ENTRA_TENANT_ID, + client: process.env.ENTRA_CLIENT_ID, +} +let exchangeError: unknown +let guestMints = 0 + +beforeEach(() => { + process.env.ACS_CONNECTION_STRING = "endpoint=https://test.communication.azure.com/;accesskey=test" + process.env.ENTRA_TENANT_ID = "tenant" + process.env.ENTRA_CLIENT_ID = "mobile-client" + guestMints = 0 + exchangeError = undefined + setAcsIdentityClientForTests({ + async getTokenForTeamsUser(input) { + expect(input).toEqual({teamsUserAadToken: subject.token, clientId: "mobile-client", userObjectId: "employee"}) + if (exchangeError) throw exchangeError + return {token: "employee-token", expiresOn: new Date("2030-01-01")} + }, + async createUserAndToken() { + guestMints++ + return {token: "guest-token", expiresOn: new Date("2030-01-01"), user: {communicationUserId: "acs-guest"}} + }, + }) +}) +afterEach(() => { + resetAcsTeamsAuthCache() + for (const [key, value] of Object.entries({ + ACS_CONNECTION_STRING: saved.connection, + ENTRA_TENANT_ID: saved.tenant, + ENTRA_CLIENT_ID: saved.client, + })) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } +}) + +describe("Teams identity selection", () => { + test("uses the licensed employee identity", async () => { + expect(await issueAcsTeamsCredential(subject, "user")).toMatchObject({ + token: "employee-token", + identityMode: "teams-user", + }) + expect(guestMints).toBe(0) + }) + test("automatically joins as a guest only for Microsoft's missing-license code", async () => { + exchangeError = Object.assign(new Error("Teams disabled in user licenses"), { + code: "UserLicenseNotPresentForbidden", + }) + expect(await issueAcsTeamsCredential(subject, "user")).toMatchObject({ + identityMode: "guest", + guestReason: "teams-license-unavailable", + }) + expect(guestMints).toBe(1) + }) + for (const error of [ + {code: "Forbidden"}, + {code: "Unauthorized"}, + {code: "TooManyRequests"}, + new Error("UserLicenseNotPresentForbidden"), + new Error("network unavailable"), + ]) + test(`does not downgrade ${JSON.stringify(error)}`, async () => { + exchangeError = error + await expect(issueAcsTeamsCredential(subject, "user")).rejects.toThrow("unavailable") + expect(guestMints).toBe(0) + }) +}) diff --git a/cloud-v2/packages/runtime/src/services/meetings/teams-meetings.service.test.ts b/cloud-v2/packages/runtime/src/services/meetings/teams-meetings.service.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e79ae0c6cc341e5538e219afe443a97a4fafda2 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/meetings/teams-meetings.service.test.ts @@ -0,0 +1,146 @@ +import {afterEach, beforeEach, describe, expect, test} from "bun:test" +import {resetAcsTeamsAuthCache, setAcsIdentityClientForTests} from "./acs-teams.service" +import {createTeamsMeeting, resetTeamsMeetingStateForTests, retireTeamsMeeting} from "./teams-meetings.service" + +const fetchBefore = globalThis.fetch +const saved = new Map() +let exchangeError: unknown +let graphStatus: number +let requests: Array<{url: string; method?: string; body?: unknown}> +const subject = {tenantId: "tenant", objectId: "employee", token: "verified-teams-token"} +const create = (employee = false, actor = "caller") => + createTeamsMeeting({ + actor, + title: "Daily standup", + durationMinutes: 30, + ...(employee ? {subject} : {}), + }) + +beforeEach(() => { + for (const [key, value] of Object.entries({ + ACS_CONNECTION_STRING: "endpoint=https://test.communication.azure.com/;accesskey=test", + ENTRA_TENANT_ID: "tenant", + ENTRA_CLIENT_ID: "mobile-client", + TEAMS_GRAPH_TENANT_ID: "tenant", + TEAMS_GRAPH_CLIENT_ID: "graph-app", + TEAMS_GRAPH_CLIENT_SECRET: "graph-secret", + TEAMS_GRAPH_ORGANIZER_ID: "fallback-organizer", + })) { + saved.set(key, process.env[key]) + process.env[key] = value + } + exchangeError = undefined + graphStatus = 200 + requests = [] + resetTeamsMeetingStateForTests() + setAcsIdentityClientForTests({ + async getTokenForTeamsUser() { + if (exchangeError) throw exchangeError + return {token: "employee-acs-token", expiresOn: new Date("2030-01-01")} + }, + async createUserAndToken() { + throw new Error("Creation must not mint a guest ACS user") + }, + }) + globalThis.fetch = (async (input, init) => { + const url = String(input) + requests.push({url, method: init?.method, body: typeof init?.body === "string" ? JSON.parse(init.body) : undefined}) + if (url.startsWith("https://login.microsoftonline.com/")) { + expect(init?.body).toBeInstanceOf(URLSearchParams) + expect((init?.body as URLSearchParams).get("scope")).toBe("https://graph.microsoft.com/.default") + return Response.json({access_token: "graph-token", expires_in: 3600}) + } + expect(new Headers(init?.headers).get("authorization")).toBe("Bearer graph-token") + if (graphStatus !== 200) return Response.json({error: {code: "provider-error"}}, {status: graphStatus}) + if (init?.method === "DELETE") return new Response(null, {status: 204}) + return Response.json({id: "meeting/id", joinWebUrl: "https://teams.microsoft.com/meet/123456?p=secret"}) + }) as typeof fetch +}) + +afterEach(() => { + globalThis.fetch = fetchBefore + resetTeamsMeetingStateForTests() + resetAcsTeamsAuthCache() + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + saved.clear() +}) + +describe("Runtime Teams meeting creation", () => { + test("uses the configured organizer without Entra and returns only public meeting data", async () => { + const result = await create() + expect(result).toMatchObject({provider: "acs-teams", identityMode: "guest", guestReason: "no-entra-identity"}) + expect(Object.keys(result).sort()).toEqual(["guestReason", "identityMode", "joinUrl", "meetingRef", "provider"]) + expect(requests.at(-1)?.url).toEndWith("/users/fallback-organizer/onlineMeetings") + expect(requests.at(-1)?.body).toMatchObject({subject: "Daily standup", lobbyBypassSettings: {scope: "everyone"}}) + expect(JSON.stringify(result)).not.toContain("graph-secret") + }) + test("uses the verified licensed employee as organizer", async () => { + expect(await create(true)).toMatchObject({identityMode: "teams-user"}) + expect(requests.at(-1)?.url).toEndWith("/users/employee/onlineMeetings") + }) + test("falls back only for the explicit missing Teams license response", async () => { + exchangeError = {code: "UserLicenseNotPresentForbidden"} + expect(await create(true)).toMatchObject({identityMode: "guest", guestReason: "teams-license-unavailable"}) + expect(requests.at(-1)?.url).toEndWith("/users/fallback-organizer/onlineMeetings") + }) + for (const error of [{code: "Forbidden"}, {code: "Unauthorized"}, {code: "TooManyRequests"}, new Error("network")]) { + test(`does not create with the fallback organizer after ${JSON.stringify(error)}`, async () => { + exchangeError = error + await expect(create(true)).rejects.toThrow("unavailable") + expect(requests).toEqual([]) + }) + } + test("rejects an employee from a different Graph tenant before any provider call", async () => { + process.env.TEAMS_GRAPH_TENANT_ID = "different-tenant" + await expect(create(true)).rejects.toMatchObject({status: 403}) + expect(requests).toEqual([]) + }) + test("does not fall back when Graph denies the employee access policy", async () => { + graphStatus = 403 + await expect(create(true)).rejects.toMatchObject({status: 403}) + expect(requests.filter((r) => r.url.includes("graph.microsoft.com"))).toHaveLength(1) + expect(requests.at(-1)?.url).toEndWith("/users/employee/onlineMeetings") + }) + test("requires a configured fallback organizer only for guest creation", async () => { + delete process.env.TEAMS_GRAPH_ORGANIZER_ID + await expect(create()).rejects.toMatchObject({status: 503}) + expect(requests).toEqual([]) + expect(await create(true)).toMatchObject({identityMode: "teams-user"}) + }) + test("rate limits creation per caller", async () => { + for (let i = 0; i < 12; i++) await create() + await expect(create()).rejects.toMatchObject({status: 429}) + expect(await create(false, "other-caller")).toMatchObject({identityMode: "guest"}) + }) +}) + +describe("Runtime Teams retirement ownership", () => { + test("retires only the meeting encoded in the authenticated caller's receipt", async () => { + const created = await create(true) + await retireTeamsMeeting("caller", created.meetingRef) + expect(requests.at(-1)).toMatchObject({ + method: "DELETE", + url: "https://graph.microsoft.com/v1.0/users/employee/onlineMeetings/meeting%2Fid", + }) + }) + test("rejects another caller, tampering, and changed Graph tenant", async () => { + const created = await create() + const before = requests.length + await expect(retireTeamsMeeting("other-caller", created.meetingRef)).rejects.toMatchObject({status: 403}) + await expect(retireTeamsMeeting("caller", `x${created.meetingRef}`)).rejects.toMatchObject({status: 403}) + await expect( + retireTeamsMeeting("caller", `${created.meetingRef.split(".")[0]}.${"é".repeat(43)}`), + ).rejects.toMatchObject({status: 403}) + process.env.TEAMS_GRAPH_TENANT_ID = "other-tenant" + await expect(retireTeamsMeeting("caller", created.meetingRef)).rejects.toMatchObject({status: 403}) + expect(requests).toHaveLength(before) + }) + test("treats an already deleted meeting as retired", async () => { + const created = await create() + graphStatus = 404 + await expect(retireTeamsMeeting("caller", created.meetingRef)).resolves.toBeUndefined() + }) +}) diff --git a/cloud-v2/packages/runtime/src/services/meetings/teams-meetings.service.ts b/cloud-v2/packages/runtime/src/services/meetings/teams-meetings.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5400a95d7698adff4c890cfe4d41eb321a3af24 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/meetings/teams-meetings.service.ts @@ -0,0 +1,235 @@ +import {createHash, createHmac, timingSafeEqual} from "node:crypto" + +import {exchangeAcsTeamsUserToken, isTeamsLicenseUnavailable, type TeamsSubject} from "./acs-teams.service" + +const GRAPH = "https://graph.microsoft.com/v1.0" +const TIMEOUT_MS = 15_000 +const CREATE_WINDOW_MS = 10 * 60 * 1000 +const createWindows = new Map() +let cachedToken: {key: string; token: string; expiresAt: number} | undefined + +export class TeamsMeetingError extends Error { + constructor( + message: string, + readonly status: 403 | 429 | 502 | 503, + ) { + super(message) + } +} + +interface GraphConfiguration { + tenantId: string + clientId: string + clientSecret: string + organizerId: string +} + +export interface CreatedTeamsMeeting { + provider: "acs-teams" + joinUrl: string + meetingRef: string + identityMode: "teams-user" | "guest" + guestReason?: "no-entra-identity" | "teams-license-unavailable" +} + +function configuration(): GraphConfiguration { + const tenantId = process.env.TEAMS_GRAPH_TENANT_ID?.trim() + const clientId = process.env.TEAMS_GRAPH_CLIENT_ID?.trim() + const clientSecret = process.env.TEAMS_GRAPH_CLIENT_SECRET?.trim() + if (!tenantId || !clientId || !clientSecret) { + throw new TeamsMeetingError("Teams meeting creation is not configured on this Runtime", 503) + } + return {tenantId, clientId, clientSecret, organizerId: process.env.TEAMS_GRAPH_ORGANIZER_ID?.trim() ?? ""} +} + +export async function createTeamsMeeting(input: { + actor: string + subject?: TeamsSubject + title: string + durationMinutes: number +}): Promise { + const config = configuration() + limitCreation(input.actor) + let organizerId = config.organizerId + let identityMode: CreatedTeamsMeeting["identityMode"] = "guest" + let guestReason: CreatedTeamsMeeting["guestReason"] = "no-entra-identity" + if (input.subject) { + if (input.subject.tenantId !== config.tenantId) { + throw new TeamsMeetingError("Teams organizer does not belong to this Runtime's Graph tenant", 403) + } + try { + // Reuse Microsoft's existing license decision, not a subscription-name heuristic. + // This token stays server-side; joining obtains its own fresh credential. + await exchangeAcsTeamsUserToken(input.subject) + organizerId = input.subject.objectId + identityMode = "teams-user" + guestReason = undefined + } catch (error) { + if (!isTeamsLicenseUnavailable(error)) throw error + guestReason = "teams-license-unavailable" + } + } + if (!organizerId) throw new TeamsMeetingError("A fallback Teams organizer is not configured on this Runtime", 503) + + const start = Date.now() + const end = start + input.durationMinutes * 60_000 + const response = await graphRequest(config, `/users/${encodeURIComponent(organizerId)}/onlineMeetings`, { + method: "POST", + body: JSON.stringify({ + startDateTime: new Date(start).toISOString(), + endDateTime: new Date(end).toISOString(), + subject: input.title, + lobbyBypassSettings: {scope: "everyone", isDialInBypassEnabled: true}, + allowedPresenters: "everyone", + joinMeetingIdSettings: {isPasscodeRequired: true}, + }), + }) + const meeting = (await response.json()) as {id?: unknown; joinWebUrl?: unknown} + if (typeof meeting.id !== "string" || !meeting.id || typeof meeting.joinWebUrl !== "string") { + throw new TeamsMeetingError("Microsoft Graph returned an invalid meeting", 502) + } + const url = new URL(meeting.joinWebUrl) + if (url.protocol !== "https:" || !["teams.microsoft.com", "teams.cloud.microsoft"].includes(url.hostname)) { + throw new TeamsMeetingError("Microsoft Graph returned an invalid meeting link", 502) + } + // A signed ownership receipt avoids adding a Runtime database. It authorizes only + // retiring this caller's meeting in this Graph tenant/application, never an arbitrary ID. + const payload = Buffer.from( + JSON.stringify({ + actor: input.actor, + tenantId: config.tenantId, + clientId: config.clientId, + organizerId, + meetingId: meeting.id, + expiresAt: end + 24 * 60 * 60_000, + }), + ).toString("base64url") + return { + provider: "acs-teams", + joinUrl: meeting.joinWebUrl, + meetingRef: `${payload}.${signReference(config, payload)}`, + identityMode, + ...(guestReason ? {guestReason} : {}), + } +} + +/** Retiring a Graph resource does not hang up the participants in an active call. */ +export async function retireTeamsMeeting(actor: string, meetingRef: string): Promise { + const config = configuration() + const [payload, signature, extra] = meetingRef.split(".") + const expected = signReference(config, payload ?? "") + if ( + !payload || + !signature || + extra !== undefined || + !/^[A-Za-z0-9_-]{43}$/.test(signature) || + !timingSafeEqual(Buffer.from(signature), Buffer.from(expected)) + ) { + throw new TeamsMeetingError("Invalid meeting ownership reference", 403) + } + let receipt + try { + receipt = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) + } catch { + throw new TeamsMeetingError("Invalid meeting ownership reference", 403) + } + if ( + !receipt || + typeof receipt !== "object" || + receipt.actor !== actor || + receipt.tenantId !== config.tenantId || + receipt.clientId !== config.clientId || + typeof receipt.expiresAt !== "number" || + receipt.expiresAt <= Date.now() || + typeof receipt.organizerId !== "string" || + typeof receipt.meetingId !== "string" + ) { + throw new TeamsMeetingError("Meeting ownership reference does not belong to this caller or has expired", 403) + } + await graphRequest( + config, + `/users/${encodeURIComponent(receipt.organizerId)}/onlineMeetings/${encodeURIComponent(receipt.meetingId)}`, + {method: "DELETE"}, + ) +} + +function signReference(config: GraphConfiguration, payload: string): string { + return createHmac("sha256", config.clientSecret).update(`mentra-teams-meeting-v1:${payload}`).digest("base64url") +} + +async function graphRequest(config: GraphConfiguration, path: string, init: RequestInit): Promise { + const token = await graphToken(config) + let response: Response + try { + response = await fetch(`${GRAPH}${path}`, { + ...init, + headers: {"Authorization": `Bearer ${token}`, "Content-Type": "application/json"}, + signal: AbortSignal.timeout(TIMEOUT_MS), + }) + } catch { + throw new TeamsMeetingError("Microsoft Graph is unavailable; the meeting operation could not be confirmed", 502) + } + if (response.ok || (init.method === "DELETE" && response.status === 404)) return response + if (response.status === 403) { + throw new TeamsMeetingError( + "Microsoft Graph denied this organizer. Check Teams application access policy and permissions", + 403, + ) + } + if (response.status === 429) throw new TeamsMeetingError("Microsoft Graph is busy; try again later", 429) + throw new TeamsMeetingError("Microsoft Graph could not complete the meeting operation", 502) +} + +async function graphToken(config: GraphConfiguration): Promise { + const key = createHash("sha256").update(JSON.stringify(config)).digest("hex") + if (cachedToken?.key === key && cachedToken.expiresAt > Date.now() + 60_000) return cachedToken.token + try { + const response = await fetch( + `https://login.microsoftonline.com/${encodeURIComponent(config.tenantId)}/oauth2/v2.0/token`, + { + method: "POST", + body: new URLSearchParams({ + client_id: config.clientId, + client_secret: config.clientSecret, + grant_type: "client_credentials", + scope: "https://graph.microsoft.com/.default", + }), + signal: AbortSignal.timeout(TIMEOUT_MS), + }, + ) + if (!response.ok) throw new Error("token rejected") + const value = (await response.json()) as {access_token?: unknown; expires_in?: unknown} + if ( + typeof value.access_token !== "string" || + !value.access_token || + typeof value.expires_in !== "number" || + value.expires_in <= 0 + ) { + throw new Error("invalid token response") + } + cachedToken = {key, token: value.access_token, expiresAt: Date.now() + value.expires_in * 1000} + return value.access_token + } catch { + throw new TeamsMeetingError("Runtime could not authenticate its Microsoft Graph application", 503) + } +} + +function limitCreation(actor: string): void { + const now = Date.now() + for (const [key, state] of createWindows) { + if (now - state.started >= CREATE_WINDOW_MS) createWindows.delete(key) + } + let state = createWindows.get(actor) + if (!state) { + if (createWindows.size >= 10_000) throw new TeamsMeetingError("Meeting creation is temporarily at capacity", 503) + state = {started: now, count: 0} + createWindows.set(actor, state) + } + if (state.count >= 12) throw new TeamsMeetingError("Too many meeting creation requests; try again later", 429) + state.count += 1 +} + +export function resetTeamsMeetingStateForTests(): void { + cachedToken = undefined + createWindows.clear() +} diff --git a/cloud-v2/packages/runtime/src/services/session/control-stream.ts b/cloud-v2/packages/runtime/src/services/session/control-stream.ts new file mode 100644 index 0000000000000000000000000000000000000000..1420ba802d33edd7f9d45395bd2068c5e8850986 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/session/control-stream.ts @@ -0,0 +1,99 @@ +/** + * @fileoverview Per-user control stream (`{user:X}:control`). + * + * The decided routing for subscription changes is "Option 2a": REST, delivered + * to the owning worker through a Redis stream, no pub/sub. We use a DEDICATED + * control stream rather than mixing control entries into the audio stream so + * the audio hot path never has to branch on entry type. The hash tag + * `{user:X}` keeps it on the same shard as the audio stream, ownership key, and + * subscription key. + * + * A control entry is only a NUDGE: it tells the owning worker "the subscription + * key changed, re-read it." The worker reconciles from the subscription key + * (the source of truth), never from the entry payload alone. That is what makes + * a REST write landing on a non-owner pod still correct: the non-owner writes + * the key and XADDs the nudge here; the owner's worker, which already reads this + * stream, picks up the nudge in order and reconciles from the key. + * + * Entries carry a `kind` field so control entry types can ride the same stream. + * Today: + * - `subscriptions-changed`: nudge the owner worker to re-read subscriptions. + * - `udp-liveness-ack`: a non-owner UDP ingress pod received a valid probe + * and asks the owner pod to ack it over the user's WebSocket. + */ + +import { getRedis } from "../../clients/redis.client"; + +/** Per-user control stream key. Hash-tagged to share a shard with the user's other keys. */ +export function controlStreamKey(mentraUserId: string): string { + return `{user:${mentraUserId}}:control`; +} + +/** Consumer group the owning worker joins to read control entries. */ +export const CONTROL_STREAM_GROUP = "control-workers"; + +/** + * Length cap on the control stream. Control entries are rare (a subscription + * change is a human-paced event, not tens-per-second like audio), so a small + * cap is plenty; it exists only to keep the key from growing without bound if + * an owner is briefly absent. + */ +export const CONTROL_STREAM_MAXLEN = 100; + +/** + * XADD a `subscriptions-changed` nudge to the user's control stream. Called by + * the REST handler after it accepts a write to the subscription key. The + * `version` is carried for logging and tracing only; the worker still re-reads + * the key rather than trusting this number. + */ +export async function publishSubscriptionsChanged( + mentraUserId: string, + version: number, +): Promise { + await getRedis().xadd( + controlStreamKey(mentraUserId), + "MAXLEN", + "~", + String(CONTROL_STREAM_MAXLEN), + "*", + "kind", + "subscriptions-changed", + "version", + String(version), + ); +} + +export interface UdpLivenessAckControl { + sessionTag: number; + audioSessionId: string; + probeId: string; + receivedAt: number; +} + +/** + * Ask the owning pod to send an `audio.udp_liveness_ack` over the user's WS. + * Used when a UDP probe lands on a non-owner pod: ingress can prove UDP reached + * the cluster, but only the owner pod holds the client's WebSocket. + */ +export async function publishUdpLivenessAck( + mentraUserId: string, + ack: UdpLivenessAckControl, +): Promise { + await getRedis().xadd( + controlStreamKey(mentraUserId), + "MAXLEN", + "~", + String(CONTROL_STREAM_MAXLEN), + "*", + "kind", + "udp-liveness-ack", + "sessionTag", + String(ack.sessionTag), + "audioSessionId", + ack.audioSessionId, + "probeId", + ack.probeId, + "receivedAt", + String(ack.receivedAt), + ); +} diff --git a/cloud-v2/packages/runtime/src/services/session/frame-timeline.test.ts b/cloud-v2/packages/runtime/src/services/session/frame-timeline.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f017825c9623de1c6864489fb7ef4a42a00cd4c --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/session/frame-timeline.test.ts @@ -0,0 +1,18 @@ +import {expect, test} from "bun:test"; +import {negotiatedFrameTimeline} from "./frame-timeline"; + +test("frame negotiation is default off until all ingress/worker readers are upgraded", () => { + const previous = process.env.AUDIO_FRAME_TIMELINE_ENABLED; + try { + delete process.env.AUDIO_FRAME_TIMELINE_ENABLED; + expect(negotiatedFrameTimeline(1)).toBeUndefined(); + process.env.AUDIO_FRAME_TIMELINE_ENABLED = "false"; + expect(negotiatedFrameTimeline(1)).toBeUndefined(); + process.env.AUDIO_FRAME_TIMELINE_ENABLED = "true"; + expect(negotiatedFrameTimeline(1)).toBe(1); + expect(negotiatedFrameTimeline()).toBeUndefined(); + } finally { + if (previous === undefined) delete process.env.AUDIO_FRAME_TIMELINE_ENABLED; + else process.env.AUDIO_FRAME_TIMELINE_ENABLED = previous; + } +}); diff --git a/cloud-v2/packages/runtime/src/services/session/frame-timeline.ts b/cloud-v2/packages/runtime/src/services/session/frame-timeline.ts new file mode 100644 index 0000000000000000000000000000000000000000..875539de3da314891221d7ca6c61352120830bcc --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/session/frame-timeline.ts @@ -0,0 +1,8 @@ +/** + * Enable only after every UDP ingress and audio worker supports positioned + * frames. Handshake negotiation alone cannot protect older cross-pod readers. + */ +export function negotiatedFrameTimeline(requested?: 1): 1 | undefined { + return requested === 1 && process.env.AUDIO_FRAME_TIMELINE_ENABLED === "true" + ? 1 : undefined; +} diff --git a/cloud-v2/packages/runtime/src/services/session/ownership.ts b/cloud-v2/packages/runtime/src/services/session/ownership.ts new file mode 100644 index 0000000000000000000000000000000000000000..f109867e0ae59b41ee3b990b25e3f4abc13c415f --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/session/ownership.ts @@ -0,0 +1,235 @@ +/** + * @fileoverview Ownership: deciding which server instance is in charge of a user. + * + * Background. This service is the cloud side of live transcription: a user's + * glasses stream audio up, and we stream transcripts back down. To handle many + * users and to survive a machine dying, the service runs as many identical + * copies at once. Each copy is a "pod" (one running container), and a load + * balancer spreads incoming traffic across them. + * + * The problem this file solves. A user's audio packets can land on ANY pod (the + * load balancer doesn't care which), but the actual transcription for that user + * has to run on exactly ONE pod at a time: the one holding that user's WebSocket + * connection. We call that pod the user's "owner". So the pods need a way to + * agree on who owns each user, and to hand a user off automatically when the + * owner crashes. + * + * How it works. There is one Redis key per user that acts as a claim ticket: + * `{user:}:owner` holds the owning pod's id. Two rules make it safe: + * + * 1. A pod can only take the key if nobody else holds it (Redis `SET ... NX`), + * so at most one pod owns a user at a time. This is a "distributed lock": + * a single shared flag that only one party can hold. + * + * 2. The key is set to expire after a few seconds (Redis `SET ... EX 5`). While + * a pod is alive it resets that timer every 1.5s. If it crashes, hangs, or + * loses its network, it stops resetting the timer, the key expires on its + * own, and another pod is free to claim the user. A missing refresh is the + * single signal for "the owner is gone", so we need no separate health check. + * + * Why the Lua scripts at the bottom. "Refresh" and "release" both mean "do + * something only if I'm still the owner". They run as Redis Lua scripts so the + * check and the action happen as one atomic step, otherwise another pod's claim + * could slip in between reading the key and acting on it, and we'd extend or + * delete a claim that is no longer ours. + */ + +import { createLogger } from "@mentra/cloud-shared"; +import { getRedis } from "../../clients/redis.client"; + +const logger = createLogger("audio").child({ service: "ownership.service" }); + +/** TTL on the ownership key. Beyond this, the claim is forfeit. */ +export const OWNERSHIP_TTL_SEC = 5; + +/** How often the owner pod renews its claim. Comfortably inside TTL. */ +export const OWNERSHIP_REFRESH_INTERVAL_MS = 1_500; + +function ownerKey(mentraUserId: string): string { + return `{user:${mentraUserId}}:owner`; +} + +export type ClaimResult = "claimed" | "already-ours" | "owned-by-other"; + +/** + * Try once to become this user's owner. Returns one of: + * - "claimed": we just took ownership (the key was free, our SET won). + * - "already-ours": the key was already set to our own pod id, so we still + * effectively own it. Calling this twice in a row is safe. + * - "owned-by-other": a different pod currently owns this user. The caller + * decides what to do next: retry and wait for that claim + * to expire, or give up and report the conflict. + */ +export async function tryClaimOwnership( + mentraUserId: string, + podId: string, +): Promise { + const redis = getRedis(); + const set = await redis.set( + ownerKey(mentraUserId), + podId, + "EX", + OWNERSHIP_TTL_SEC, + "NX", + ); + if (set === "OK") return "claimed"; + + // Failed. Was it us or someone else? + const current = await redis.get(ownerKey(mentraUserId)); + if (current === podId) return "already-ours"; + if (current === null) { + const retry = await redis.set( + ownerKey(mentraUserId), + podId, + "EX", + OWNERSHIP_TTL_SEC, + "NX", + ); + if (retry === "OK") return "claimed"; + const afterRetry = await redis.get(ownerKey(mentraUserId)); + if (afterRetry === podId) return "already-ours"; + } + return "owned-by-other"; +} + +/** + * Like `tryClaimOwnership`, but if another pod currently owns the user, keep + * retrying for a short while. This gives a crashed owner's claim time to expire + * on its own so we can then take over. The default deadline is twice the key's + * expiry, which is long enough that a dead owner's claim is always gone before + * we give up. + */ +export async function claimOwnershipWithRetry( + mentraUserId: string, + podId: string, + deadlineMs = OWNERSHIP_TTL_SEC * 2 * 1000, +): Promise { + const deadline = Date.now() + deadlineMs; + let result: ClaimResult = "owned-by-other"; + while (Date.now() < deadline) { + result = await tryClaimOwnership(mentraUserId, podId); + if (result !== "owned-by-other") return result; + await Bun.sleep(500); + } + return result; +} + +/** + * Reset the expiry timer on our claim, but only if we still own it. The owner + * pod calls this on a timer so its claim never expires while it is healthy. + * Returns true if the refresh worked. Returns false if some other pod has + * already taken the user over, which means we were too slow (our claim expired + * and someone grabbed it), and we should stop treating this user as ours. + */ +export async function refreshOwnership( + mentraUserId: string, + podId: string, +): Promise { + const redis = getRedis(); + const result = (await redis.eval( + REFRESH_SCRIPT, + 1, + ownerKey(mentraUserId), + podId, + String(OWNERSHIP_TTL_SEC), + )) as number; + return result === 1; +} + +/** + * Give up ownership of a user, but only if we still own it. Called on a clean + * disconnect so the user can be claimed elsewhere right away instead of waiting + * for the timer to expire. If some other pod already holds the claim (ours + * expired and got grabbed), this does nothing, deleting their claim would be + * wrong. + */ +export async function releaseOwnership( + mentraUserId: string, + podId: string, +): Promise { + const redis = getRedis(); + const result = (await redis.eval( + RELEASE_SCRIPT, + 1, + ownerKey(mentraUserId), + podId, + )) as number; + return result === 1; +} + +/** Read which pod currently owns this user, or null if nobody does. A plain + * read with no claiming; handy for tests and diagnostics. */ +export async function getOwner(mentraUserId: string): Promise { + return getRedis().get(ownerKey(mentraUserId)); +} + +// === Lua scripts === +// +// These run inside Redis as a single atomic step. Each one reads the owner key +// and only acts if the stored pod id matches ours (KEYS[1] is the key, ARGV[1] +// is our pod id). Doing the read and the action together is what stops two pods +// from racing on the same claim. + +const REFRESH_SCRIPT = ` +if redis.call("GET", KEYS[1]) == ARGV[1] then + redis.call("EXPIRE", KEYS[1], ARGV[2]) + return 1 +else + return 0 +end +`; + +const RELEASE_SCRIPT = ` +if redis.call("GET", KEYS[1]) == ARGV[1] then + redis.call("DEL", KEYS[1]) + return 1 +else + return 0 +end +`; + +// === Refresh loop === + +let refreshTimer: ReturnType | null = null; + +/** + * Start a background timer that keeps all of this pod's claims alive. On each + * tick it asks the caller which users this pod currently owns (via the + * `getOwnedUserIds` callback, normally the set of live WebSocket sessions) and + * refreshes each one's claim. Call this once at startup; calling it again does + * nothing, so a second call cannot create a duplicate timer. + */ +export function startOwnershipRefreshLoop(opts: { + podId: string; + getOwnedUserIds: () => Iterable; + onLostOwnership?: (mentraUserId: string) => void; +}): void { + if (refreshTimer) return; + refreshTimer = setInterval(async () => { + try { + for (const userId of opts.getOwnedUserIds()) { + const ok = await refreshOwnership(userId, opts.podId); + if (!ok) { + // We thought we owned this user but Redis disagrees. Could be a + // partition, could be a missed refresh that let TTL expire and + // someone else grabbed it. Either way, log; later batches will + // hand off the affected sessions cleanly. + logger.warn( + { mentraUserId: userId, podId: opts.podId }, + "ownership refresh failed, claim no longer ours", + ); + opts.onLostOwnership?.(userId); + } + } + } catch (err) { + logger.error({ err }, "ownership refresh loop threw"); + } + }, OWNERSHIP_REFRESH_INTERVAL_MS); +} + +export function stopOwnershipRefreshLoop(): void { + if (refreshTimer) { + clearInterval(refreshTimer); + refreshTimer = null; + } +} diff --git a/cloud-v2/packages/runtime/src/services/session/stream.ts b/cloud-v2/packages/runtime/src/services/session/stream.ts new file mode 100644 index 0000000000000000000000000000000000000000..75331b01d484e7808b439f793f6c829482fae3cc --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/session/stream.ts @@ -0,0 +1,376 @@ +/** + * @fileoverview Audio Redis substrate. Owns three pieces of state in Redis: + * + * 1. **Per-user audio streams** (`{user:mentraUserId}:audio`). XADDed by any pod + * that receives a UDP packet for that user; XREADGROUPed by the owner + * pod (whichever pod holds the WS). Bounded by MAXLEN ~ retained-window. + * + * 2. **Session-tag registry** (`sessionTag:{u32}`). Maps the u32 in UDP + * packet headers to a Mentra user (and which pod owns the WS). Lets a + * pod that received a UDP packet for a session it doesn't own resolve + * "who is this for" without coordinating with the owner. + * + * 3. **Stream consumer-group name** (constant). All worker pools across + * pods join one group so XAUTOCLAIM can rebalance work after pod death. + * + * Wire-format and lifecycle decisions live in `docs/issues/003-audio/`. + */ + +import nacl from "tweetnacl"; +import { getRedis } from "../../clients/redis.client"; +import { UDP_LIVENESS_PROBE_PREFIX } from "@mentra/cloud-protocol/audio"; + +// === Stream constants === + +/** Per-user audio stream key. */ +export function audioStreamKey(mentraUserId: string): string { + return `{user:${mentraUserId}}:audio`; +} + +/** 6-byte UDP/WS audio packet header: [sessionTag:u32 BE][sequence:u16 BE]. */ +export const AUDIO_PACKET_HEADER_SIZE = 6; + +export interface ParsedAudioPacket { + sessionTag: number; + sequence: number; + payload: Uint8Array; +} + +/** + * Parse the shared UDP/WS audio packet wire format: + * [sessionTag:u32 BE][sequence:u16 BE][lc3-payload] + * + * Returns null if the buffer is too short to contain a header. + */ +export function parseAudioPacket(buf: Uint8Array): ParsedAudioPacket | null { + if (buf.byteLength < AUDIO_PACKET_HEADER_SIZE) return null; + const view = Buffer.isBuffer(buf) + ? buf + : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return { + sessionTag: view.readUInt32BE(0), + sequence: view.readUInt16BE(4), + payload: view.subarray(AUDIO_PACKET_HEADER_SIZE), + }; +} + +export interface LocalSessionLookup { + mentraUserId: string; + audioSessionId: string; + /** + * The session's UDP frame key (base64). Needed to decrypt UDP frames on the + * same-pod fast path. Omitted by the WS-binary fallback path, whose frames + * are not secretbox-encrypted (they ride the TLS WebSocket). + */ + encryptionKeyB64?: string; + frameTimelineVersion?: 1; +} + +export interface IngestResult { + ok: boolean; + kind?: "audio" | "probe"; + origin?: "local" | "redis"; + mentraUserId?: string; + audioSessionId?: string; + /** Bytes written to the stream (the decrypted length for UDP frames). */ + payloadLen?: number; + probeId?: string; +} + +export interface IngestOptions { + /** + * Whether the payload is secretbox-encrypted. UDP frames are (the payload is + * `[nonce(24)|ciphertext]`); the WS-binary fallback is not. When true we + * decrypt with the session key and write plaintext to the stream, so the + * worker only ever sees decode-ready audio. + */ + encrypted?: boolean; +} + +/** secretbox (XSalsa20-Poly1305) nonce length, 24 bytes. */ +const UDP_NONCE_BYTES = nacl.secretbox.nonceLength; + +/** + * Decrypt a UDP frame payload `[nonce(24)|ciphertext]` with the session key. + * Returns the plaintext audio bytes, or null if the key is missing/wrong size, + * the frame is too short, or the Poly1305 tag does not verify (forged or + * corrupted packet). + */ +function decryptUdpPayload( + payload: Uint8Array, + keyB64: string | undefined, +): Uint8Array | null { + if (!keyB64) return null; + if (payload.byteLength <= UDP_NONCE_BYTES) return null; + const key = Buffer.from(keyB64, "base64"); + if (key.byteLength !== nacl.secretbox.keyLength) return null; + const nonce = payload.subarray(0, UDP_NONCE_BYTES); + const ciphertext = payload.subarray(UDP_NONCE_BYTES); + return nacl.secretbox.open(ciphertext, nonce, key); +} + +function decodeProbeId(payload: Uint8Array): string | null { + const prefix = UDP_LIVENESS_PROBE_PREFIX; + if (payload.byteLength <= prefix.length) return null; + for (let i = 0; i < prefix.length; i += 1) { + if (payload[i] !== prefix.charCodeAt(i)) return null; + } + let id = ""; + for (let i = prefix.length; i < payload.byteLength; i += 1) { + const c = payload[i]; + if (c < 0x20 || c > 0x7e) return null; + id += String.fromCharCode(c); + } + return id || null; +} + +/** + * Resolve a sessionTag → user (local map first, Redis fallback), then XADD + * the packet to the user's audio stream. Shared by both ingress paths: + * + * - UDP ingress (`udp-ingress.service.ts`) + * - WS-binary fallback (`session.service.ts` message handler) + * + * Returns `{ ok: false }` when the sessionTag is unknown — typical when a + * packet arrives just before/after the session's lifetime, not an error. + * + * `localLookup` is the same-pod fast path: a callback the caller provides + * that consults the in-process session map. We accept a callback (rather + * than importing session.service directly) to keep the dependency direction + * one-way and avoid a circular import. + */ +export async function ingestAudioPacket( + packet: ParsedAudioPacket, + localLookup: (tag: number) => LocalSessionLookup | undefined, + opts: IngestOptions = {}, +): Promise { + let mentraUserId: string; + let audioSessionId: string; + let encryptionKeyB64: string | undefined; + let origin: "local" | "redis"; + let frameTimelineVersion: 1 | undefined; + + const local = localLookup(packet.sessionTag); + if (local) { + mentraUserId = local.mentraUserId; + audioSessionId = local.audioSessionId; + encryptionKeyB64 = local.encryptionKeyB64; + frameTimelineVersion = local.frameTimelineVersion; + origin = "local"; + } else { + const remote = await lookupSessionTagInRedis(packet.sessionTag); + if (!remote) return { ok: false }; + mentraUserId = remote.mentraUserId; + audioSessionId = remote.audioSessionId; + encryptionKeyB64 = remote.encryptionKeyB64; + frameTimelineVersion = remote.frameTimelineVersion; + origin = "redis"; + } + + // UDP frames are encrypted; decrypt before the stream so the worker only sees + // plaintext. A frame that fails the Poly1305 tag check (forged, corrupted, or + // wrong key) is dropped rather than stored. + let payload = packet.payload; + if (opts.encrypted) { + const plaintext = decryptUdpPayload(payload, encryptionKeyB64); + if (!plaintext) return { ok: false, origin, mentraUserId }; + payload = plaintext; + } + + const probeId = opts.encrypted ? decodeProbeId(payload) : null; + if (probeId) { + return { + ok: true, + kind: "probe", + origin, + mentraUserId, + audioSessionId, + payloadLen: payload.byteLength, + probeId, + }; + } + + let offsetMs: number | undefined; + if (frameTimelineVersion === 1) { + if (payload.byteLength < 8) return { ok: false, origin, mentraUserId }; + offsetMs = new DataView( + payload.buffer, + payload.byteOffset, + payload.byteLength, + ).getFloat64(0, false); + if (!Number.isFinite(offsetMs) || offsetMs < 0) + return { ok: false, origin, mentraUserId }; + payload = payload.subarray(8); + } + await appendAudioPacket(mentraUserId, { + seq: packet.sequence, + payload, + sessionTag: packet.sessionTag, + audioSessionId, + offsetMs, + }); + + return { + ok: true, + kind: "audio", + origin, + mentraUserId, + audioSessionId, + payloadLen: payload.byteLength, + }; +} + +/** + * Stream length cap. ~10 seconds at typical packet rates (≈100 pkt/s). + * The `~` (approximate) trimming lets Redis trim in efficient bulk — + * MAXLEN is enforced only loosely. + */ +export const AUDIO_STREAM_MAXLEN = 1000; + +/** Consumer group all worker dispatch loops join. Created lazily on first read. */ +export const AUDIO_STREAM_GROUP = "audio-workers"; + +// === Stream operations === + +export interface AudioPacket { + seq: number; + /** The raw audio payload (LC3 frames or PCM bytes). */ + payload: Uint8Array; + /** Useful for tracing — which u32 tag generated this entry. */ + sessionTag: number; + /** Useful for tracing — which audio-session this entry belongs to. */ + audioSessionId: string; + offsetMs?: number; +} + +/** + * XADD an audio packet to a user's stream. Idempotent in the sense that + * "same user, different sequence" produces distinct entries; we do not + * de-dupe on `seq` (the producer is responsible for monotonicity). + * + * Payload is base64-encoded on write — ioredis returns stream values as + * strings by default, which corrupts binary bytes outside ASCII via UTF-8 + * decoding. Base64 is binary-safe at the cost of ~33% storage overhead. + * Workers `Buffer.from(payload, "base64")` to recover the original bytes. + * + * Returns the Redis-assigned stream entry ID (`-`). + */ +export async function appendAudioPacket( + mentraUserId: string, + packet: AudioPacket, +): Promise { + const redis = getRedis(); + const id = await redis.xadd( + audioStreamKey(mentraUserId), + "MAXLEN", + "~", + String(AUDIO_STREAM_MAXLEN), + "*", + "seq", + String(packet.seq), + "sessionTag", + String(packet.sessionTag), + "audioSessionId", + packet.audioSessionId, + "offsetMs", + packet.offsetMs === undefined ? "" : String(packet.offsetMs), + "payload", + Buffer.from(packet.payload).toString("base64"), + ); + return id ?? ""; +} + +// === Session-tag registry === + +/** + * How long a sessionTag registration is valid in Redis without a refresh. + * Owners refresh on a timer (well inside the TTL) and on clean WS close + * delete the key outright. The TTL is the recovery guarantee — if a pod + * crashes without releasing, abandoned tag mappings vanish within this + * window so the next reconnect's mapping can take over. + */ +export const SESSION_TAG_TTL_SEC = 60; + +/** Owner refreshes at this cadence — well inside the TTL. */ +export const SESSION_TAG_REFRESH_INTERVAL_MS = 20_000; + +export interface SessionTagRecord { + mentraUserId: string; + tenantId: string; + audioSessionId: string; + authSessionId: string; + /** Which pod's WebSocket owns this session. Used by dispatch later. */ + podId: string; + /** + * The session's audio frame encryption key (base64). Carried so a UDP packet + * that lands on any pod can fetch this session's key by sessionTag and + * decrypt the frame. + */ + encryptionKeyB64: string; + frameTimelineVersion?: 1; +} + +/** Set before ACK; remote UDP ingress must decode the same format as local ingress. */ +export async function enableSessionFrameTimeline( + tag: number, + audioSessionId: string, +): Promise { + const redis = getRedis(); + const raw = await redis.get(sessionTagKey(tag)); + if (!raw) throw new Error("audio session tag expired before init"); + const record = JSON.parse(raw) as SessionTagRecord; + if (record.audioSessionId !== audioSessionId) + throw new Error("audio session tag replaced before init"); + record.frameTimelineVersion = 1; + const result = await redis.set( + sessionTagKey(tag), + JSON.stringify(record), + "EX", + SESSION_TAG_TTL_SEC, + "XX", + ); + if (result !== "OK") throw new Error("audio session tag expired during init"); +} + +function sessionTagKey(tag: number): string { + return `sessionTag:${tag}`; +} + +export async function registerSessionTag( + tag: number, + record: SessionTagRecord, +): Promise { + const redis = getRedis(); + const result = await redis.set( + sessionTagKey(tag), + JSON.stringify(record), + "EX", + SESSION_TAG_TTL_SEC, + "NX", + ); + return result === "OK"; +} + +export async function refreshSessionTag(tag: number): Promise { + const redis = getRedis(); + await redis.expire(sessionTagKey(tag), SESSION_TAG_TTL_SEC); +} + +export async function unregisterSessionTag(tag: number): Promise { + const redis = getRedis(); + await redis.del(sessionTagKey(tag)); +} + +/** Returns null if the tag is unknown or has TTL'd out. */ +export async function lookupSessionTagInRedis( + tag: number, +): Promise { + const redis = getRedis(); + const raw = await redis.get(sessionTagKey(tag)); + if (!raw) return null; + try { + return JSON.parse(raw) as SessionTagRecord; + } catch { + return null; + } +} diff --git a/cloud-v2/packages/runtime/src/services/session/subscriptions-store.ts b/cloud-v2/packages/runtime/src/services/session/subscriptions-store.ts new file mode 100644 index 0000000000000000000000000000000000000000..59d60bf8de31367c8d15fd34ed177742da333663 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/session/subscriptions-store.ts @@ -0,0 +1,300 @@ +/** + * @fileoverview Subscription source of truth in Redis. + * + * The authoritative audio subscription set for a user lives in one Redis key, + * `{user:X}:subscriptions`. It holds the full subscription set plus the last + * accepted `sessionId` and `version`. The hash tag `{user:X}` matches the + * ownership key (`{user:X}:owner`) and the control stream (`{user:X}:control`) + * so all of one user's keys land on the same Redis Cluster shard. + * + * Why a single guarded key instead of applying REST writes directly to a + * worker: the legacy system had two scars this design closes. + * 1. Out-of-order application. A retried or reordered REST write could apply + * an older snapshot on top of a newer one. The monotonic `version` guard + * discards anything not strictly newer than what we already accepted. + * 2. A reconnect's empty snapshot wiping a live set. After reconnect the + * client briefly has an empty set; if that landed late it could clear a + * newer, populated set. Because an empty set must still carry a newer + * version for the current session to be accepted, a stale empty can never + * win against a live set. + * + * The key is also the source of truth the owning worker reconciles from. REST + * writes additionally drop a nudge into the control stream (see + * `control-stream.ts`); the worker reads that nudge and then re-reads THIS key, + * never trusting the nudge payload alone. That keeps a single source of truth + * and avoids the derived-cache drift the legacy system suffered. + */ + +import { getRedis } from "../../clients/redis.client"; +import type { AudioSubscription } from "@mentra/cloud-protocol/audio"; + +/** + * Subscription key TTL. Refreshed by the owner while the session is live and + * deleted on clean disconnect. The TTL is the backstop: if a pod crashes + * without releasing, the abandoned set vanishes within this window so a later + * session for the same user starts clean rather than inheriting stale subs. + */ +export const SUBSCRIPTIONS_TTL_SEC = 60; + +/** What the subscription key holds, decoded. */ +export interface SubscriptionRecord { + subscriptions: AudioSubscription[]; + /** The session that last wrote this set (from `connection.ack.sessionId`). */ + sessionId: string; + /** Monotonic per snapshot. A write must be strictly newer to be accepted. */ + version: number; +} + +/** Outcome of a guarded write. */ +export interface WriteResult { + applied: boolean; + /** The version now in effect (the accepted one, or the existing one if rejected). */ + version: number; + /** Present when `applied` is false: why the write was rejected. */ + reason?: "stale-session" | "stale-version"; + /** + * Present when rejected with "stale-session": the sessionId currently + * holding the key. The caller can check whether that session is actually + * alive and take over a dead session's record (see audio.api.ts). + */ + currentSessionId?: string; +} + +function subscriptionsKey(mentraUserId: string): string { + return `{user:${mentraUserId}}:subscriptions`; +} + +/** Read the current subscription record, or null if none exists yet. */ +export async function readSubscriptions( + mentraUserId: string, +): Promise { + const raw = await getRedis().get(subscriptionsKey(mentraUserId)); + if (!raw) return null; + try { + return JSON.parse(raw) as SubscriptionRecord; + } catch { + return null; + } +} + +/** + * Seed the key for a brand-new session without clobbering a live session. Called from + * `connection.init` so the initial subscription set is in place before any + * audio flows. A fresh handshake establishes a new `sessionId` baseline at + * `version` 0; subsequent REST writes for that session are then guarded + * against it by `writeSubscriptions`. + * + * If another live socket already seeded the user's key, this returns false + * rather than replacing that socket's session guard. The existing key TTL is + * refreshed by the owner and removed on clean last-session close. + */ +export async function seedSubscriptions( + mentraUserId: string, + record: SubscriptionRecord, +): Promise { + const applied = (await getRedis().eval( + SEED_SCRIPT, + 1, + subscriptionsKey(mentraUserId), + JSON.stringify(record), + SUBSCRIPTIONS_TTL_SEC, + record.sessionId, + )) as number; + return applied === 1; +} + +/** + * Guarded write of a full subscription snapshot, used by the REST endpoint. + * + * The read-check-write runs as one atomic Lua step so two concurrent REST + * writes (retry plus original, two pods) cannot interleave and accept an older + * snapshot. The guard rejects a write whose `sessionId` is not the current + * session, and any write whose `version` is not strictly greater than the last + * accepted version. An empty subscription set is just a normal snapshot under + * these rules: it is honored only when it is the newest version for the current + * session, so a stale empty can never wipe a live set. + * + * If no record exists yet (the seed somehow never ran, e.g. a write racing + * ahead of `connection.init`), the write is accepted and establishes the + * baseline, so a subscription change is never silently lost. + */ +export async function writeSubscriptions( + mentraUserId: string, + record: SubscriptionRecord, +): Promise { + const result = (await getRedis().eval( + WRITE_SCRIPT, + 1, + subscriptionsKey(mentraUserId), + JSON.stringify(record.subscriptions), + record.sessionId, + String(record.version), + String(SUBSCRIPTIONS_TTL_SEC), + )) as [number, string, number, string?]; + + const [appliedFlag, reason, effectiveVersion, currentSessionId] = result; + if (appliedFlag === 1) { + return { applied: true, version: effectiveVersion }; + } + return { + applied: false, + version: effectiveVersion, + reason: reason === "stale-session" ? "stale-session" : "stale-version", + ...(currentSessionId ? { currentSessionId } : {}), + }; +} + +/** + * Unconditional snapshot write that REPLACES whatever record exists. Reserved + * for taking over a DEAD session's record: the caller must have verified that + * the record's sessionId no longer corresponds to a live socket (and that this + * pod owns the user) before forcing. Establishes a fresh version baseline. + */ +export async function takeoverSubscriptions( + mentraUserId: string, + record: SubscriptionRecord, +): Promise { + await getRedis().set( + subscriptionsKey(mentraUserId), + JSON.stringify(record), + "EX", + SUBSCRIPTIONS_TTL_SEC, + ); +} + +/** + * Refresh the key's TTL — but only when the record still belongs to the + * refreshing session. An unconditional refresh would let ANY open socket for + * the user keep a DEAD session's record alive forever (each reconnect's + * refresh loop re-arms the TTL), permanently wedging seeding and REST writes + * behind a session that no longer exists. Session-scoped refresh restores the + * TTL's role as the dead-record backstop: a record whose session is gone + * expires within {@link SUBSCRIPTIONS_TTL_SEC}. + */ +export async function refreshSubscriptions( + mentraUserId: string, + sessionId: string, +): Promise { + await getRedis().eval( + REFRESH_IF_SESSION_SCRIPT, + 1, + subscriptionsKey(mentraUserId), + sessionId, + String(SUBSCRIPTIONS_TTL_SEC), + ); +} + +/** Delete the key on clean disconnect so the next session starts fresh. */ +export async function deleteSubscriptions(mentraUserId: string): Promise { + await getRedis().del(subscriptionsKey(mentraUserId)); +} + +/** + * Delete the key only if it is still owned by one of the given sessions. + * Used when a pod loses user ownership: its sessions are being torn down, but + * the new owner may have already seeded this key for a NEWER session — an + * unconditional delete from the stale pod would wipe the live owner's + * subscription state cluster-wide. Returns true when the key was deleted. + */ +export async function deleteSubscriptionsIfSessionIn( + mentraUserId: string, + sessionIds: string[], +): Promise { + if (sessionIds.length === 0) return false; + const deleted = (await getRedis().eval( + DELETE_IF_SESSION_SCRIPT, + 1, + subscriptionsKey(mentraUserId), + JSON.stringify(sessionIds), + )) as number; + return deleted === 1; +} + +// === Lua === +// +// Atomic guarded write. KEYS[1] is the subscription key. ARGV: [1] the new +// subscription set as JSON, [2] the writer's sessionId, [3] the new version, +// [4] the TTL in seconds. Returns a 3-tuple [applied, reason, version]: +// - applied: 1 if written, 0 if rejected +// - reason: "" when applied; "stale-session" or "stale-version" when not +// - version: the version now in effect (the new one if applied, else the +// existing one) so the caller can echo the authoritative version +// back to the client. +// +// We store the record as a JSON object so a single GET in the read path +// recovers everything. The Lua decodes only the two scalar guard fields it +// needs (sessionId, version) and rewrites the whole object on accept. +const WRITE_SCRIPT = ` +local existing = redis.call("GET", KEYS[1]) +local newSubs = ARGV[1] +local newSession = ARGV[2] +local newVersion = tonumber(ARGV[3]) +local ttl = ARGV[4] + +if existing then + local decoded = cjson.decode(existing) + if decoded.sessionId ~= newSession then + return {0, "stale-session", decoded.version, decoded.sessionId} + end + if newVersion <= decoded.version then + return {0, "stale-version", decoded.version} + end +end + +local record = string.format( + '{"subscriptions":%s,"sessionId":%s,"version":%d}', + newSubs, cjson.encode(newSession), newVersion +) +redis.call("SET", KEYS[1], record, "EX", ttl) +return {1, "", newVersion} +`; + +// Conditional delete. ARGV[1] is a JSON array of sessionIds being torn down; +// the key is removed only when its record's sessionId is one of them. +const DELETE_IF_SESSION_SCRIPT = ` +local existing = redis.call("GET", KEYS[1]) +if not existing then + return 0 +end +local decoded = cjson.decode(existing) +local sessions = cjson.decode(ARGV[1]) +for _, id in ipairs(sessions) do + if decoded.sessionId == id then + redis.call("DEL", KEYS[1]) + return 1 + end +end +return 0 +`; + +// Conditional TTL refresh. ARGV: [1] the refreshing session's id, [2] TTL +// seconds. Only re-arms the TTL when the record still belongs to that session. +const REFRESH_IF_SESSION_SCRIPT = ` +local existing = redis.call("GET", KEYS[1]) +if not existing then + return 0 +end +local decoded = cjson.decode(existing) +if decoded.sessionId ~= ARGV[1] then + return 0 +end +redis.call("EXPIRE", KEYS[1], ARGV[2]) +return 1 +`; + +const SEED_SCRIPT = ` +local existing = redis.call("GET", KEYS[1]) +local record = ARGV[1] +local ttl = ARGV[2] +local newSession = ARGV[3] + +if existing then + local decoded = cjson.decode(existing) + if decoded.sessionId ~= newSession then + return 0 + end +end + +redis.call("SET", KEYS[1], record, "EX", ttl) +return 1 +`; diff --git a/cloud-v2/packages/runtime/src/services/session/subscriptions.ts b/cloud-v2/packages/runtime/src/services/session/subscriptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfae84809f92193f413a4ff9a13f572a7ebef178 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/session/subscriptions.ts @@ -0,0 +1,43 @@ +/** + * @fileoverview Shared audio types used across services + workers. + * + * The canonical subscription/result types and their zod schemas live in + * `protocol/audio.ts` (the isomorphic `@mentra/cloud-runtime/protocol` + * entrypoint). This module re-exports the subscription types and adds the + * server-side `subscriptionKey()` canonicalization used for structural + * equality + Map keys. + * + * Per the design (docs/issues/002-cloud-runtime/audio/spec.md "Subscription + * model"): "Phone aggregates and dedupes across local miniapps; sends a flat + * list to cloud on every (re)connect. Identity is structural." + */ +export type { + LanguageSource, + TranscriptionSubscription, + TranslationSubscription, + AudioSubscription, +} from "@mentra/cloud-protocol/audio"; + +import type { AudioSubscription, LanguageSource } from "@mentra/cloud-protocol/audio"; + +/** + * Stable string key for a subscription, used for equality + Map keys. + * Canonicalizes `hints` ordering so two subs with the same hints in + * different array orders compare equal. + */ +export function subscriptionKey(sub: AudioSubscription): string { + if (sub.kind === "transcription") { + return `t:${languageKey(sub.language)}`; + } + return `x:${languageKey(sub.source)}>${sub.target}`; +} + +function languageKey(lang: LanguageSource): string { + if (lang.mode === "specific") return `s:${lang.code}`; + const hints = lang.hints ? [...lang.hints].sort().join(",") : ""; + return `a:${hints}`; +} + +// WS inbound message envelopes (the v1 phone wire contract: +// `phone_subscription_update`, `ping`) live in `wire/phone-protocol.ts`, +// which translates them into the `AudioSubscription` shape above. diff --git a/cloud-v2/packages/runtime/src/services/storage/providers/local.provider.ts b/cloud-v2/packages/runtime/src/services/storage/providers/local.provider.ts new file mode 100644 index 0000000000000000000000000000000000000000..f453631cd2413fd9cae1cc77569d8f36a39427d5 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/storage/providers/local.provider.ts @@ -0,0 +1,94 @@ +/** + * @fileoverview Local-fs storage provider. + * + * Stores blobs in a temp directory and lets the runtime serve them itself: the + * presigned upload/download URLs point back at the runtime's own + * `/api/camera/blob/:key` endpoints (see api/camera.api.ts). Because the runtime + * is the upload endpoint, it knows the instant an upload lands, so there is no + * polling or webhook for completion. + * + * This is the default provider: local dev, CI, and a worked example of a custom + * implementation, with no third-party dependency. Production points + * `STORAGE_PROVIDER` at r2/s3 instead. + */ + +import { mkdir, readFile, writeFile, unlink, stat } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { tmpdir } from "node:os"; +import type { + PresignedUpload, + PresignOptions, + StorageProvider, + StoredObject, +} from "../storage.service"; + +/** Where blobs live on disk. Override with CAMERA_LOCAL_DIR. */ +const BLOB_DIR = process.env.CAMERA_LOCAL_DIR ?? join(tmpdir(), "mentra-camera-blobs"); + +/** The runtime path that serves local blobs. Kept in sync with camera.api.ts. */ +const BLOB_ROUTE = "/api/camera/blob"; + +/** A tiny per-key content-type sidecar so `get` can return the right type. */ +function paths(key: string): { blob: string; meta: string } { + const safe = key.replace(/\.\.(\/|\\)/g, ""); // defense-in-depth against traversal + const blob = join(BLOB_DIR, safe); + return { blob, meta: `${blob}.type` }; +} + +export function createLocalProvider(): StorageProvider { + return { + name: "local", + servesBytes: true, + + async presignUpload(key: string, opts: PresignOptions): Promise { + // No real signature: the local endpoints are unauthenticated dev URLs. + // The origin makes the URL absolute so a device (or a test) can PUT to it. + const base = opts.origin ?? ""; + return { + url: `${base}${BLOB_ROUTE}/${key}`, + method: "PUT", + headers: opts.contentType ? { "Content-Type": opts.contentType } : undefined, + }; + }, + + async presignDownload(key: string, opts?: PresignOptions): Promise { + const base = opts?.origin ?? ""; + return `${base}${BLOB_ROUTE}/${key}`; + }, + + async exists(key: string): Promise { + try { + await stat(paths(key).blob); + return true; + } catch { + return false; + } + }, + + async delete(key: string): Promise { + const { blob, meta } = paths(key); + await unlink(blob).catch(() => undefined); + await unlink(meta).catch(() => undefined); + }, + + async put(key: string, bytes: Uint8Array, contentType: string): Promise { + const { blob, meta } = paths(key); + await mkdir(dirname(blob), { recursive: true }); + await writeFile(blob, bytes); + await writeFile(meta, contentType); + }, + + async get(key: string): Promise { + const { blob, meta } = paths(key); + try { + const bytes = await readFile(blob); + const contentType = await readFile(meta, "utf8").catch( + () => "application/octet-stream", + ); + return { bytes: new Uint8Array(bytes), contentType }; + } catch { + return null; + } + }, + }; +} diff --git a/cloud-v2/packages/runtime/src/services/storage/providers/s3.provider.ts b/cloud-v2/packages/runtime/src/services/storage/providers/s3.provider.ts new file mode 100644 index 0000000000000000000000000000000000000000..324d186867a9c41e7685c2c599a08c24c307bc76 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/storage/providers/s3.provider.ts @@ -0,0 +1,97 @@ +/** + * @fileoverview S3-compatible storage provider (Cloudflare R2 and friends). + * + * Backed by Bun's native S3 client, so it needs no third-party SDK. The same + * client targets any S3-compatible store by endpoint + credentials: Cloudflare + * R2 (the default target), AWS S3, MinIO, and Alibaba OSS's S3-compatible + * endpoint (config-only, not separately validated yet). + * + * The byte path does NOT pass through the runtime: the device PUTs straight to + * the presigned upload URL and reads from the presigned download URL. The + * runtime learns an upload completed from the provider's object-created event, + * delivered to the camera storage webhook (see api/camera.api.ts); this provider + * only mints presigned URLs and does object existence/delete. + * + * Config (env), with R2_* fallbacks for the common case: + * STORAGE_S3_ENDPOINT (e.g. https://.r2.cloudflarestorage.com) + * STORAGE_S3_BUCKET + * STORAGE_S3_ACCESS_KEY_ID + * STORAGE_S3_SECRET_ACCESS_KEY + * STORAGE_S3_REGION (default "auto", which R2 expects) + */ + +import type { + PresignedUpload, + PresignOptions, + StorageProvider, +} from "../storage.service"; + +/** Presigned URL lifetime. Long enough for a glasses upload, short enough to limit replay. */ +const PRESIGN_EXPIRES_SEC = 600; + +/** First defined value among the given env var names. */ +function env(...names: string[]): string | undefined { + for (const name of names) { + if (process.env[name]) return process.env[name]; + } + return undefined; +} + +export function createS3Provider(): StorageProvider { + // Accept the v2 STORAGE_S3_* names, plus R2_* and the v1 CLOUDFLARE_R2_* + // names, so existing Cloudflare R2 credentials work without re-keying. + const endpoint = env("STORAGE_S3_ENDPOINT", "R2_ENDPOINT", "CLOUDFLARE_R2_S3_ENDPOINT"); + const bucket = env("STORAGE_S3_BUCKET", "R2_BUCKET", "CLOUDFLARE_R2_GALLERY_BUCKET"); + const accessKeyId = env("STORAGE_S3_ACCESS_KEY_ID", "R2_ACCESS_KEY_ID", "CLOUDFLARE_R2_ACCESS_KEY_ID"); + const secretAccessKey = env( + "STORAGE_S3_SECRET_ACCESS_KEY", + "R2_SECRET_ACCESS_KEY", + "CLOUDFLARE_R2_SECRET_ACCESS_KEY", + ); + const region = env("STORAGE_S3_REGION") ?? "auto"; + + if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) { + throw new Error( + "STORAGE_PROVIDER=r2/s3 requires STORAGE_S3_ENDPOINT, STORAGE_S3_BUCKET, " + + "STORAGE_S3_ACCESS_KEY_ID, and STORAGE_S3_SECRET_ACCESS_KEY (R2_* fallbacks accepted).", + ); + } + + const client = new Bun.S3Client({ + endpoint, + bucket, + accessKeyId, + secretAccessKey, + region, + }); + + return { + name: "s3", + servesBytes: false, + + async presignUpload(key: string, opts: PresignOptions): Promise { + const url = client.presign(key, { + method: "PUT", + expiresIn: PRESIGN_EXPIRES_SEC, + type: opts.contentType, + }); + return { + url, + method: "PUT", + headers: opts.contentType ? { "Content-Type": opts.contentType } : undefined, + }; + }, + + async presignDownload(key: string): Promise { + return client.presign(key, { method: "GET", expiresIn: PRESIGN_EXPIRES_SEC }); + }, + + async exists(key: string): Promise { + return await client.exists(key); + }, + + async delete(key: string): Promise { + await client.delete(key); + }, + }; +} diff --git a/cloud-v2/packages/runtime/src/services/storage/storage.service.ts b/cloud-v2/packages/runtime/src/services/storage/storage.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..987250803c2d4a22f818ea5b11fb831b52ba92a7 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/storage/storage.service.ts @@ -0,0 +1,86 @@ +/** + * @fileoverview Blob storage abstraction for the runtime. + * + * A thin wrapper over swappable blob providers (Cloudflare R2, a local-fs dev + * provider, and the same S3 client points at Alibaba OSS / AWS / MinIO by + * config). Services use this instead of talking to a provider directly, so the + * camera service (and later miniapp bundles, if the runtime ever stores them) + * is provider-agnostic. + * + * Mirrors the provider-wrapper pattern in Cloud Core's storage-service, but + * instantiated within Mentra Runtime Services because the runtime is + * self-hostable: a self-hosted runtime points at the OEM's own blob config, + * independent of Cloud Core's instance. + * + * Provider is chosen by `STORAGE_PROVIDER`: + * - "local" (default): real temp-fs storage; the runtime serves the bytes + * itself (presigned URLs point at its own /api/camera/blob endpoints). For + * local dev, CI, and as the reference for a custom implementation, with no + * third-party dependency. + * - "r2" / "s3": Cloudflare R2 (or any S3-compatible store, including Alibaba + * OSS's S3 endpoint) via Bun's native S3 client. The byte path goes straight + * to the provider; completion arrives via the event webhook. + * + * See docs/issues/002-cloud-runtime/camera/spec.md and + * docs/issues/001-cloud-core/storage-service/. + */ + +import { createLocalProvider } from "./providers/local.provider"; +import { createS3Provider } from "./providers/s3.provider"; + +/** A presigned upload target the caller hands to the device. */ +export interface PresignedUpload { + url: string; + method: "PUT"; + /** Headers the uploader must send (for example a fixed Content-Type). */ + headers?: Record; +} + +export interface PresignOptions { + /** MIME type the upload will carry, fixed into the signature when relevant. */ + contentType?: string; + /** + * The request origin (scheme + host), used by the local provider to build + * absolute URLs pointing back at this runtime. Ignored by remote providers, + * whose URLs are absolute provider URLs. + */ + origin?: string; +} + +/** Bytes plus their content type, returned by the local provider's `get`. */ +export interface StoredObject { + bytes: Uint8Array; + contentType: string; +} + +/** + * The provider contract. `put` / `get` are implemented only by the local + * provider (which serves its own bytes); remote providers leave them undefined + * because their byte path does not pass through the runtime. + */ +export interface StorageProvider { + readonly name: string; + presignUpload(key: string, opts: PresignOptions): Promise; + presignDownload(key: string, opts?: PresignOptions): Promise; + exists(key: string): Promise; + delete(key: string): Promise; + /** True when the runtime serves this provider's bytes (the local provider). */ + readonly servesBytes: boolean; + put?(key: string, bytes: Uint8Array, contentType: string): Promise; + get?(key: string): Promise; +} + +let provider: StorageProvider | null = null; + +/** The configured storage provider (built once per process). */ +export function getStorageProvider(): StorageProvider { + if (provider) return provider; + const kind = process.env.STORAGE_PROVIDER ?? "local"; + provider = kind === "r2" || kind === "s3" ? createS3Provider() : createLocalProvider(); + return provider; +} + +/** Test/boot hook: reset the cached provider (for example to switch config). */ +export function resetStorageProvider(): void { + provider = null; +} diff --git a/cloud-v2/packages/runtime/src/services/stream/providers/cloudflare-stream.provider.ts b/cloud-v2/packages/runtime/src/services/stream/providers/cloudflare-stream.provider.ts new file mode 100644 index 0000000000000000000000000000000000000000..421c60d6b6e806d2360d9e2cd2fecc62ab343d5b --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/stream/providers/cloudflare-stream.provider.ts @@ -0,0 +1,407 @@ +/** + * @fileoverview Cloudflare Stream provider (real live-input provisioning). + * + * Provisions a Cloudflare Stream live input over the Cloudflare API and returns + * its ingest (RTMPS + SRT + WebRTC/WHIP) and HLS/DASH playback coordinates. + * No SDK: a couple of authed fetch calls. + * + * All three ingest protocols are surfaced because real networks differ: office + * firewalls commonly kill RTMPS:443 mid-handshake while SRT passes, and the + * device-side publisher picks its protocol from the URL prefix. The composed + * `rtmpUrl`/`srtUrl`/`webrtcPublishUrl` are ready-to-publish (stream key / + * streamid+passphrase already embedded). + * + * Config (env): + * CF_STREAM_ACCOUNT_ID Cloudflare account id + * CF_STREAM_API_TOKEN API token with Stream:Edit + * CF_STREAM_CUSTOMER_SUBDOMAIN customer-.cloudflarestream.com (for playback URLs) + * + * Cloudflare API: + * POST /accounts/:acct/stream/live_inputs -> { result: { uid, rtmps, srt, webRTC, ... } } + * GET /accounts/:acct/stream/live_inputs/:uid -> { result: { status: { current: {...} } } } + * DELETE /accounts/:acct/stream/live_inputs/:uid + * POST /accounts/:acct/stream/live_inputs/:uid/outputs (restream destinations) + * GET /accounts/:acct/stream/live_inputs/:uid/videos (recordings of this input) + * DELETE /accounts/:acct/stream/:videoUid (a recording) + * + * Recordings are separate objects from the live input and outlive it: deleting + * an input orphans its recordings, which keep counting against the account's + * storage quota. Recording cannot simply be turned off -- HLS playback requires + * `mode: automatic` -- so `stop()` deletes the recordings before the input, and + * `deleteRecordingAfterDays` is set as a floor for anything that slips past. + * Inputs are disabled before cleanup and retained whenever a recording is still + * finalizing, so no billable recording becomes unreachable through its input. + */ + +import type { ManagedStream, StreamOptions, StreamStatusResult } from "@mentra/cloud-protocol/camera"; +import type { + StreamCleanupResult, + StreamDiscoveryResult, + StreamProvider, +} from "../stream.service"; + +const CF_API = "https://api.cloudflare.com/client/v4"; + +/** Cloudflare's minimum for `deleteRecordingAfterDays`. A floor, not the policy. */ +const RECORDING_RETENTION_DAYS = 30; + +interface LiveInputSummary { + uid?: string; + created?: string; + modified?: string; + meta?: unknown; +} + +/** `GET /live_inputs` -- every input on the account. */ +interface LiveInputListResult { + result?: { + liveInputs?: LiveInputSummary[]; + range?: number; + total?: number; + }; + success: boolean; +} + +/** `GET /live_inputs/:uid/videos` -- the recordings produced by an input. */ +interface VideoListResult { + result?: Array<{ + uid: string; + status?: { state?: string } | null; + }>; + success: boolean; +} + +interface LiveInputResult { + result?: { + uid: string; + enabled?: boolean; + meta?: unknown; + rtmps?: { url: string; streamKey: string }; + rtmpsPlayback?: { url: string; streamKey: string }; + srt?: { url: string; streamId: string; passphrase: string }; + webRTC?: { url: string }; + webRTCPlayback?: { url: string }; + status?: + | string + | { + current?: { + state?: string | null; + statusEnteredAt?: string; + statusLastSeen?: string; + reason?: string; + } | null; + } + | null; + }; + success: boolean; + errors?: Array<{ code: number; message: string }>; +} + +/** First defined value among the given env var names. */ +function env(...names: string[]): string | undefined { + for (const name of names) { + if (process.env[name]) return process.env[name]; + } + return undefined; +} + +export function createCloudflareStreamProvider(): StreamProvider { + // Accept the CF_STREAM_* names plus the v1 CLOUDFLARE_* names, so existing + // Cloudflare credentials work without re-keying. The token needs Stream:Edit. + const accountId = env("CF_STREAM_ACCOUNT_ID", "CLOUDFLARE_ACCOUNT_ID"); + const apiToken = env("CF_STREAM_API_TOKEN", "CLOUDFLARE_API_TOKEN"); + const customerSubdomain = env("CF_STREAM_CUSTOMER_SUBDOMAIN"); + + if (!accountId || !apiToken) { + throw new Error( + "STREAM_PROVIDER=cloudflare requires CF_STREAM_ACCOUNT_ID/CLOUDFLARE_ACCOUNT_ID " + + "and CF_STREAM_API_TOKEN/CLOUDFLARE_API_TOKEN.", + ); + } + + const base = `${CF_API}/accounts/${accountId}/stream/live_inputs`; + const authHeaders = { Authorization: `Bearer ${apiToken}` }; + + /** Playback host for a live input. Falls back to Cloudflare's shared host. */ + function playbackUrls(uid: string): { hls: string; dash: string } { + const host = customerSubdomain + ? `https://${customerSubdomain}` + : "https://videodelivery.net"; + return { + hls: `${host}/${uid}/manifest/video.m3u8`, + dash: `${host}/${uid}/manifest/video.mpd`, + }; + } + + function currentStatus(input: NonNullable): { + state: string | null; + statusEnteredAt?: string; + statusLastSeen?: string; + reason?: string; + } { + if (typeof input.status === "string") return { state: input.status }; + return { + state: input.status?.current?.state ?? null, + statusEnteredAt: input.status?.current?.statusEnteredAt, + statusLastSeen: input.status?.current?.statusLastSeen, + reason: input.status?.current?.reason, + }; + } + + function isReclaimProtectedState(state: string | null): boolean { + return ( + state === "connected" || + state === "reconnected" || + state === "reconnecting" || + state === "live" + ); + } + + function isConnectedState(state: string | null): boolean { + return state === "connected" || state === "reconnected" || state === "live"; + } + + function isMentraInput(input: LiveInputSummary): boolean { + if (!input.meta || typeof input.meta !== "object") return false; + const name = (input.meta as Record).name; + return typeof name === "string" && name.startsWith("mentra-"); + } + + async function getLiveInput(inputUid: string): Promise | null> { + const res = await fetch(`${base}/${inputUid}`, { headers: authHeaders }); + if (res.status === 404) return null; + + const body = (await res.json()) as LiveInputResult; + if (!res.ok || !body.success || !body.result) { + const detail = body.errors?.map((e) => e.message).join("; ") ?? res.statusText; + throw new Error(`cloudflare live input get failed: ${detail}`); + } + return body.result; + } + + async function disableInput(inputUid: string): Promise { + const res = await fetch(`${base}/${inputUid}`, { + method: "PUT", + headers: { ...authHeaders, "Content-Type": "application/json" }, + body: JSON.stringify({ enabled: false }), + }); + if (res.status === 404) return false; + if (!res.ok) throw new Error(`cloudflare live input disable failed: ${res.status}`); + return true; + } + + async function deleteInput(inputUid: string): Promise { + const res = await fetch(`${base}/${inputUid}`, { + method: "DELETE", + headers: authHeaders, + }); + if (!res.ok && res.status !== 404) { + throw new Error(`cloudflare live input delete failed: ${res.status}`); + } + } + + interface RecordingCleanupResult { + deleted: number; + failed: number; + pending: number; + seen: number; + } + + /** + * Delete every finished recording belonging to a live input. + * + * A stream that has just ended may not have a recording yet (Cloudflare can + * take time to make one available). Callers use the returned pending/failure + * counts to retain the input for a later sweep instead of orphaning video. + * + * Returns a lifecycle summary so callers can distinguish complete cleanup + * from a safe deferral. + */ + async function cleanupRecordings(inputUid: string): Promise { + const listed = await fetch(`${base}/${inputUid}/videos`, { headers: authHeaders }); + if (!listed.ok) { + throw new Error(`cloudflare recording list failed: ${listed.status}`); + } + + const body = (await listed.json()) as VideoListResult; + if (!body.success || !Array.isArray(body.result)) { + throw new Error("cloudflare recording list returned an invalid response"); + } + const videos = body.result ?? []; + let deleted = 0; + let failed = 0; + let pending = 0; + + for (const video of videos) { + const state = video.status?.state; + if (state !== "ready" && state !== "error") { + // Unknown and processing states are deliberately retained. Deleting + // the input now would orphan a recording that Cloudflare has not + // finished materializing yet. + pending += 1; + continue; + } + + const res = await fetch(`${CF_API}/accounts/${accountId}/stream/${video.uid}`, { + method: "DELETE", + headers: authHeaders, + }); + if (res.ok || res.status === 404) deleted += 1; + else failed += 1; + } + return { deleted, failed, pending, seen: videos.length }; + } + + async function listLiveInputs(): Promise<{ + inputs: LiveInputSummary[]; + total: number; + }> { + const listed = await fetch(base, { headers: authHeaders }); + if (!listed.ok) throw new Error(`cloudflare live input list failed: ${listed.status}`); + + const body = (await listed.json()) as LiveInputListResult; + const inputs = body.result?.liveInputs; + if (!body.success || !Array.isArray(inputs)) { + throw new Error("cloudflare live input list returned an invalid response"); + } + return { inputs, total: body.result?.total ?? inputs.length }; + } + + /** + * Disable an input, delete terminal recordings, then delete the input only + * when no recording can be orphaned. Explicit stops defer an empty recording + * list because Cloudflare may still be materializing it; queue recovery can + * accept an empty list after its grace period. + */ + async function cleanupInput( + inputUid: string, + allowEmpty: boolean, + ): Promise { + if (!(await disableInput(inputUid))) return { recordings: 0, input: "missing" }; + + const cleanup = await cleanupRecordings(inputUid); + if (cleanup.failed > 0) { + throw new Error(`cloudflare recording cleanup failed for ${cleanup.failed} recording(s)`); + } + if (cleanup.pending > 0 || (!allowEmpty && cleanup.seen === 0)) { + return { recordings: cleanup.deleted, input: "retained" }; + } + + await deleteInput(inputUid); + return { recordings: cleanup.deleted, input: "deleted" }; + } + + async function reclaim(inputUid: string): Promise { + // A registry entry may refer to a live stream lasting longer than the + // abandonment grace period. Verify provider state before disabling it. + const current = await getLiveInput(inputUid); + if (!current) return { recordings: 0, input: "missing" }; + if (isReclaimProtectedState(currentStatus(current).state)) { + return { recordings: 0, input: "retained" }; + } + return await cleanupInput(inputUid, true); + } + + async function discover(): Promise { + const listed = await listLiveInputs(); + const inputs = listed.inputs.flatMap((input) => { + if (!input.uid || !isMentraInput(input)) return []; + const createdAt = Date.parse(input.created ?? input.modified ?? ""); + if (!Number.isFinite(createdAt)) return []; + return [{ streamId: input.uid, createdAt }]; + }); + return { inputs, truncated: listed.total > listed.inputs.length }; + } + + return { + name: "cloudflare", + + async provision(mentraUserId: string, opts: StreamOptions): Promise { + const res = await fetch(base, { + method: "POST", + headers: { ...authHeaders, "Content-Type": "application/json" }, + body: JSON.stringify({ + meta: { name: `mentra-${mentraUserId}` }, + // `automatic` is required: HLS/DASH playback does not work with + // recording off, and Mentra Call needs the live HLS URL. + recording: { mode: "automatic" }, + // Backstop only. `stop()` deletes recordings explicitly; this bounds + // anything it misses (a stream that ends by disconnect, a failed + // delete). Cloudflare's minimum for this field is 30 days, so it + // cannot replace explicit deletion. + deleteRecordingAfterDays: RECORDING_RETENTION_DAYS, + }), + }); + const body = (await res.json()) as LiveInputResult; + if (!res.ok || !body.success || !body.result) { + const detail = body.errors?.map((e) => e.message).join("; ") ?? res.statusText; + throw new Error(`cloudflare live input create failed: ${detail}`); + } + const { uid, rtmps, srt, webRTC, webRTCPlayback } = body.result; + + // Ready-to-publish URLs: key/credentials embedded so the device can use + // them verbatim (its publisher detects protocol from the URL prefix). + const rtmpUrl = rtmps?.url && rtmps?.streamKey ? `${rtmps.url}${rtmps.streamKey}` : undefined; + const srtUrl = + srt?.url && srt?.streamId && srt?.passphrase + ? `${srt.url}?streamid=${encodeURIComponent(srt.streamId)}&passphrase=${encodeURIComponent(srt.passphrase)}` + : undefined; + + // Restream destinations (re-publish the ingest to external RTMP targets). + // Best-effort: a failed output should not fail the provision — the stream + // itself is healthy without it. + const destinations = opts.restreamDestinations ?? []; + for (const dest of destinations) { + const url = typeof dest === "string" ? dest : dest.url; + const name = typeof dest === "string" ? undefined : dest.name; + try { + await fetch(`${base}/${uid}/outputs`, { + method: "POST", + headers: { ...authHeaders, "Content-Type": "application/json" }, + body: JSON.stringify({ url, enabled: true, ...(name ? { meta: { name } } : {}) }), + }); + } catch { + /* best-effort; surfaced via status polling if it matters */ + } + } + + return { + streamId: uid, + ingest: { + protocol: "rtmps", + url: rtmps?.url ?? "", + streamKey: rtmps?.streamKey ?? "", + rtmpUrl, + srtUrl, + webrtcPublishUrl: webRTC?.url, + }, + playback: { + ...playbackUrls(uid), + webrtc: webRTCPlayback?.url, + }, + }; + }, + + async status(streamId: string): Promise { + const input = await getLiveInput(streamId); + if (!input) throw new Error("cloudflare live input status failed: input not found"); + const current = currentStatus(input); + const state = current.state; + return { + streamId, + isConnected: isConnectedState(state), + state, + connectedAt: current.statusEnteredAt, + lastSeenAt: current.statusLastSeen, + reason: current.reason, + }; + }, + + async stop(streamId: string): Promise { + return await cleanupInput(streamId, false); + }, + + reclaim, + discover, + }; +} diff --git a/cloud-v2/packages/runtime/src/services/stream/stream.service.ts b/cloud-v2/packages/runtime/src/services/stream/stream.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7d5ae20231ba11bd216fbb8dc828bda6dd40508 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/stream/stream.service.ts @@ -0,0 +1,286 @@ +/** + * @fileoverview Live-stream provisioning abstraction for managed stream. + * + * Managed stream provisions a real live video stream on a provider and returns + * the ingest (where the device pushes) and playback (where viewers watch) + * coordinates. Unlike blob storage there is no local-real equivalent (you can't + * stand up a real RTMP ingest + HLS playback with no dependency), so the only + * provider today is Cloudflare Stream. With no provider configured, provisioning + * fails loudly rather than returning fake coordinates. + * + * Provider is chosen by `STREAM_PROVIDER` (default "cloudflare"). + * + * Spec: docs/issues/002-cloud-runtime/camera/spec.md ("Managed stream"). + */ + +import type { ManagedStream, StreamOptions, StreamStatusResult } from "@mentra/cloud-protocol/camera"; +import { createLogger } from "@mentra/cloud-shared"; +import { getRedis } from "../../clients/redis.client"; +import { createCloudflareStreamProvider } from "./providers/cloudflare-stream.provider"; + +const logger = createLogger("audio").child({ service: "stream.service" }); + +export interface StreamProvider { + readonly name: string; + provision(mentraUserId: string, opts: StreamOptions): Promise; + status(streamId: string): Promise; + stop(streamId: string): Promise; + /** + * Reclaim a known abandoned input. Unlike an explicit stop, an empty + * recording list is terminal because the queue's grace period has elapsed. + */ + reclaim?(streamId: string): Promise; + /** Seed the durable queue with inputs created before the queue existed. */ + discover?(): Promise; +} + +export interface StreamCleanupResult { + recordings: number; + input: "deleted" | "retained" | "missing"; +} + +export interface StreamDiscoveryResult { + inputs: Array<{ streamId: string; createdAt: number }>; + truncated: boolean; +} + +let provider: StreamProvider | null = null; + +/** The configured stream provider, or throws if none is configured. */ +export function getStreamProvider(): StreamProvider { + if (provider) return provider; + const kind = process.env.STREAM_PROVIDER ?? "cloudflare"; + if (kind === "cloudflare") { + provider = createCloudflareStreamProvider(); + return provider; + } + throw new Error(`unknown STREAM_PROVIDER: ${kind}`); +} + +/** Test/boot hook: reset the cached provider. */ +export function resetStreamProvider(): void { + provider = null; +} + +// === Managed stream lifecycle === + +const CLEANUP_QUEUE_KEY = "managed-stream:cleanup"; +const ABANDONED_STREAM_GRACE_MS = 6 * 60 * 60 * 1000; +const STOP_CLEANUP_RETRY_MS = 60 * 1000; +const SWEEP_RETRY_MS = 15 * 60 * 1000; +const LEGACY_DISCOVERY_INTERVAL_MS = 60 * 60 * 1000; +const SWEEP_BATCH_SIZE = 100; + +type CleanupAction = "reclaim" | "stop"; + +function cleanupQueueMember(action: CleanupAction, streamId: string): string { + return `${action}:${streamId}`; +} + +function parseCleanupQueueMember(member: string): { + action: CleanupAction; + streamId: string; +} { + if (member.startsWith("stop:")) { + return { action: "stop", streamId: member.slice("stop:".length) }; + } + if (member.startsWith("reclaim:")) { + return { action: "reclaim", streamId: member.slice("reclaim:".length) }; + } + // Entries written by earlier builds used the bare stream id. + return { action: "reclaim", streamId: member }; +} + +function cleanupQueueMembers(streamId: string): [string, string] { + return [cleanupQueueMember("reclaim", streamId), cleanupQueueMember("stop", streamId)]; +} + +export async function provisionStream( + mentraUserId: string, + opts: StreamOptions, +): Promise { + const p = getStreamProvider(); + const stream = await p.provision(mentraUserId, opts); + try { + await getRedis().zadd( + CLEANUP_QUEUE_KEY, + Date.now() + ABANDONED_STREAM_GRACE_MS, + cleanupQueueMember("reclaim", stream.streamId), + ); + } catch (err) { + // Do not hand out an input that recovery cannot find. This input has never + // been published to, so reclaiming an empty input is safe. + await p.reclaim?.(stream.streamId).catch(() => undefined); + throw err; + } + return stream; +} + +export async function streamStatus(streamId: string): Promise { + const status = await getStreamProvider().status(streamId); + // Status is polled throughout an active managed stream. Treat each successful + // observation as activity so a long-running stream never becomes sweepable + // merely because its original provision time is old. XX prevents a status + // response that finishes after completed teardown from recreating the entry. + await getRedis() + .zadd( + CLEANUP_QUEUE_KEY, + "XX", + Date.now() + ABANDONED_STREAM_GRACE_MS, + cleanupQueueMember("reclaim", streamId), + ) + .catch((err) => logger.warn({ err, streamId }, "stream activity refresh failed")); + return status; +} + +export async function stopStream(streamId: string): Promise { + const redis = getRedis(); + const stopMember = cleanupQueueMember("stop", streamId); + + // Persist the finalization retry before touching Cloudflare. It is separate + // from the inactivity deadline, so an in-flight status poll cannot postpone + // an explicit stop and an empty recording list remains protected until a + // later stop retry observes the finalized recording. + await redis.zadd(CLEANUP_QUEUE_KEY, Date.now() + STOP_CLEANUP_RETRY_MS, stopMember); + + const result = await getStreamProvider().stop(streamId); + if (result.input !== "retained") { + await redis.zrem(CLEANUP_QUEUE_KEY, ...cleanupQueueMembers(streamId)); + } +} + +// === Recording sweep loop === + +/** How often to process the durable cleanup queue. */ +const SWEEP_INTERVAL_MS = STOP_CLEANUP_RETRY_MS; + +let sweepTimer: ReturnType | null = null; +let sweepLoopStarted = false; +let nextLegacyDiscoveryAt = 0; + +export async function sweepStreamsOnce(): Promise<{ recordings: number; inputs: number }> { + const p = getStreamProvider(); + const redis = getRedis(); + const now = Date.now(); + + // Best-effort migration for inputs created before the durable registry. + // Cloudflare's endpoint exposes only its first window, so the registry is + // authoritative for all newly provisioned streams. Queue processing runs + // every minute, but account-wide discovery remains hourly. + let discovered: StreamDiscoveryResult | undefined; + if (now >= nextLegacyDiscoveryAt) { + nextLegacyDiscoveryAt = now + LEGACY_DISCOVERY_INTERVAL_MS; + try { + discovered = await p.discover?.(); + } catch (err) { + // Migration is advisory. A list-endpoint failure must never block cleanup + // of inputs already present in the authoritative queue. + logger.warn({ err }, "Cloudflare legacy input discovery failed"); + } + } + if (discovered) { + const pipeline = redis.pipeline(); + for (const input of discovered.inputs) { + pipeline.zadd( + CLEANUP_QUEUE_KEY, + "NX", + input.createdAt + ABANDONED_STREAM_GRACE_MS, + cleanupQueueMember("reclaim", input.streamId), + ); + } + await pipeline.exec(); + if (discovered.truncated) { + logger.warn( + { discovered: discovered.inputs.length }, + "Cloudflare legacy input discovery is truncated; durable registry remains authoritative", + ); + } + } + + const claimed = await redis.zrangebyscore( + CLEANUP_QUEUE_KEY, + "-inf", + now, + "LIMIT", + 0, + SWEEP_BATCH_SIZE, + ); + if (claimed.length > 0) { + // Move the batch forward before touching Cloudflare. Concurrent pods may + // very occasionally select the same batch, but provider operations are + // idempotent and this avoids losing work if a pod exits mid-cleanup. + const pipeline = redis.pipeline(); + for (const member of claimed) { + const { action } = parseCleanupQueueMember(member); + const retryMs = action === "stop" ? STOP_CLEANUP_RETRY_MS : SWEEP_RETRY_MS; + pipeline.zadd(CLEANUP_QUEUE_KEY, now + retryMs, member); + } + await pipeline.exec(); + } + + let recordings = 0; + let inputs = 0; + for (const member of claimed) { + const { action, streamId } = parseCleanupQueueMember(member); + try { + if (action === "reclaim" && !p.reclaim) continue; + const result = action === "stop" ? await p.stop(streamId) : await p.reclaim!(streamId); + recordings += result.recordings; + if (result.input === "deleted" || result.input === "missing") { + await redis.zrem(CLEANUP_QUEUE_KEY, ...cleanupQueueMembers(streamId), streamId); + if (result.input === "deleted") inputs += 1; + } + // Retained inputs already carry the claim's retry timestamp. + } catch (err) { + logger.warn({ err, streamId }, "stream cleanup retained input for retry"); + } + } + return { recordings, inputs }; +} + +/** + * Start the background sweep that reclaims abandoned live inputs and their + * recordings. + * + * `stop()` handles the tidy case, but it only runs when a client explicitly + * ends a stream; anything that ends by disconnect leaks. Recordings cannot be + * disabled (HLS playback needs `mode: automatic`), and Cloudflare's built-in + * `deleteRecordingAfterDays` has a 30-day minimum, so without this the account + * fills and Cloudflare starts rejecting broadcasts at publish -- which reaches + * the user as an unexplained network failure. + * + * Call once at startup. Idempotent, so a second call cannot create a duplicate + * timer. Every pod running this is fine: deletes are idempotent and a 404 + * counts as success. + */ +export function startStreamSweepLoop(): void { + if (sweepLoopStarted) return; + sweepLoopStarted = true; + + const run = async () => { + try { + const { recordings, inputs } = await sweepStreamsOnce(); + if (recordings || inputs) { + logger.info({ recordings, inputs }, "stream sweep reclaimed abandoned inputs"); + } + } catch (err) { + // A provider that is not configured, or a Cloudflare blip. Next tick retries. + logger.warn({ err }, "stream sweep failed"); + } finally { + // Schedule only after this run settles so slow account cleanup can never + // overlap itself and multiply Cloudflare API traffic. + if (sweepLoopStarted) sweepTimer = setTimeout(run, SWEEP_INTERVAL_MS); + } + }; + + void run(); +} + +/** Test/shutdown hook: stop the sweep loop. */ +export function stopStreamSweepLoop(): void { + sweepLoopStarted = false; + nextLegacyDiscoveryAt = 0; + if (!sweepTimer) return; + clearTimeout(sweepTimer); + sweepTimer = null; +} diff --git a/cloud-v2/packages/runtime/src/services/tts/providers/elevenlabs.provider.ts b/cloud-v2/packages/runtime/src/services/tts/providers/elevenlabs.provider.ts new file mode 100644 index 0000000000000000000000000000000000000000..9f6e5fb024d44330e13f4875819c2ea843531003 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/tts/providers/elevenlabs.provider.ts @@ -0,0 +1,135 @@ +/** + * @fileoverview ElevenLabs streaming TTS provider. + */ +import { createLogger } from "@mentra/cloud-shared"; +import { DEFAULT_TTS_AUDIO_FORMAT, TTS_AUDIO_FORMATS, type TtsAudioFormat } from "../tts-formats"; +import type { TtsProvider, TtsProviderSpeakRequest } from "../tts.service"; + +const logger = createLogger("tts").child({ service: "elevenlabs.tts.provider" }); + +const ELEVENLABS_DEFAULTS = { + voiceId: process.env.ELEVENLABS_DEFAULT_VOICE_ID || "8IRrZoKuYTPnpLc6lM6a", + modelId: process.env.ELEVENLABS_DEFAULT_MODEL_ID || "eleven_flash_v2_5", + speed: Number.parseFloat(process.env.ELEVENLABS_DEFAULT_SPEED || "1.13"), + stability: Number.parseFloat(process.env.ELEVENLABS_DEFAULT_STABILITY || "0.68"), + similarityBoost: Number.parseFloat(process.env.ELEVENLABS_DEFAULT_SIMILARITY || "0.75"), + style: Number.parseFloat(process.env.ELEVENLABS_DEFAULT_STYLE || "0.0"), +}; + +/** + * ElevenLabs `output_format` per runtime format. MP3 sends none, so the + * request stays exactly what older hosts relied on (ElevenLabs' MP3 default). + */ +const ELEVENLABS_OUTPUT_FORMAT: Record = { + mp3: undefined, + pcm_24000: "pcm_24000", +}; + +/** Exported for tests: the ElevenLabs streaming URL for a voice and format. */ +export function elevenLabsStreamUrl(voiceId: string, format: TtsAudioFormat): string { + const outputFormat = ELEVENLABS_OUTPUT_FORMAT[format]; + const base = `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}/stream`; + return outputFormat ? `${base}?output_format=${outputFormat}` : base; +} + +function json(data: unknown, status: number): Response { + return new Response(JSON.stringify(data), { + status, + headers: { "Content-Type": "application/json" }, + }); +} + +export class ElevenLabsTtsProvider implements TtsProvider { + preflight(format: TtsAudioFormat = DEFAULT_TTS_AUDIO_FORMAT): Response { + if (!process.env.ELEVENLABS_API_KEY) { + logger.error("ELEVENLABS_API_KEY environment variable not set"); + return json( + { + success: false, + message: "TTS service not configured", + }, + 500, + ); + } + + return new Response(null, { + headers: { + "Content-Type": TTS_AUDIO_FORMATS[format].contentType, + "Cache-Control": "no-cache", + }, + }); + } + + async speak(req: TtsProviderSpeakRequest): Promise { + const apiKey = process.env.ELEVENLABS_API_KEY; + if (!apiKey) { + logger.error("ELEVENLABS_API_KEY environment variable not set"); + return json( + { + success: false, + message: "TTS service not configured", + }, + 500, + ); + } + + const voiceId = req.voiceId || ELEVENLABS_DEFAULTS.voiceId; + const modelId = req.modelId || ELEVENLABS_DEFAULTS.modelId; + const voiceSettings = req.voiceSettings || { + speed: ELEVENLABS_DEFAULTS.speed, + stability: ELEVENLABS_DEFAULTS.stability, + similarity_boost: ELEVENLABS_DEFAULTS.similarityBoost, + style: ELEVENLABS_DEFAULTS.style, + }; + const format = req.format ?? DEFAULT_TTS_AUDIO_FORMAT; + const elevenLabsUrl = elevenLabsStreamUrl(voiceId, format); + + logger.info({ voiceId, modelId, format }, "streaming TTS request"); + + const response = await fetch(elevenLabsUrl, { + method: "POST", + headers: { + "Content-Type": "application/json", + "xi-api-key": apiKey, + }, + body: JSON.stringify({ + text: req.text, + model_id: modelId, + voice_settings: voiceSettings, + }), + }); + + if (!response.ok) { + const errorText = await response.text(); + logger.error({ status: response.status, body: errorText }, "ElevenLabs TTS request failed"); + return json( + { + success: false, + message: `TTS service error: ${response.status}`, + details: errorText, + }, + response.status, + ); + } + + if (!response.body) { + return json( + { + success: false, + message: "No audio data received from TTS service", + }, + 500, + ); + } + + // ElevenLabs relays PCM as it is synthesized; the body is raw samples with + // no container, so the content type carries the sample format. + return new Response(response.body, { + headers: { + "Content-Type": TTS_AUDIO_FORMATS[format].contentType, + "Cache-Control": "no-cache", + Connection: "keep-alive", + }, + }); + } +} diff --git a/cloud-v2/packages/runtime/src/services/tts/tts-formats.ts b/cloud-v2/packages/runtime/src/services/tts/tts-formats.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e8289492badb3771e57af9daf9e574f351bfbe5 --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/tts/tts-formats.ts @@ -0,0 +1,19 @@ +/** + * @fileoverview Audio encodings the runtime TTS route can return. + * + * `mp3` is the default so older hosts keep working. `pcm_24000` is raw signed + * 16-bit little-endian mono PCM at 24 kHz, for hosts that stream it straight + * into a PCM player. + */ +export const TTS_AUDIO_FORMATS = { + mp3: { contentType: "audio/mpeg" }, + pcm_24000: { contentType: "audio/pcm;encoding=s16le;rate=24000;channels=1" }, +} as const; + +export type TtsAudioFormat = keyof typeof TTS_AUDIO_FORMATS; + +export const DEFAULT_TTS_AUDIO_FORMAT: TtsAudioFormat = "mp3"; + +export function isTtsAudioFormat(value: string): value is TtsAudioFormat { + return Object.prototype.hasOwnProperty.call(TTS_AUDIO_FORMATS, value); +} diff --git a/cloud-v2/packages/runtime/src/services/tts/tts.service.ts b/cloud-v2/packages/runtime/src/services/tts/tts.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa4631a06e09b3cf326f4e0b8fcfa83b1dff975e --- /dev/null +++ b/cloud-v2/packages/runtime/src/services/tts/tts.service.ts @@ -0,0 +1,48 @@ +/** + * @fileoverview Runtime TTS service. + * + * The API layer owns HTTP/query validation. This service owns provider choice + * and keeps the route independent from ElevenLabs-specific transport details. + */ +import { ElevenLabsTtsProvider } from "./providers/elevenlabs.provider"; +import { DEFAULT_TTS_AUDIO_FORMAT, type TtsAudioFormat } from "./tts-formats"; + +export { + DEFAULT_TTS_AUDIO_FORMAT, + isTtsAudioFormat, + TTS_AUDIO_FORMATS, + type TtsAudioFormat, +} from "./tts-formats"; + +export interface TtsSpeakOptions { + voiceId?: string; + modelId?: string; + voiceSettings?: Record; + format?: TtsAudioFormat; +} + +export interface TtsProviderSpeakRequest extends TtsSpeakOptions { + text: string; +} + +export interface TtsProvider { + preflight(format: TtsAudioFormat): Response; + speak(req: TtsProviderSpeakRequest): Promise; +} + +export class TtsService { + constructor(private readonly provider: TtsProvider = new ElevenLabsTtsProvider()) {} + + preflight(format: TtsAudioFormat = DEFAULT_TTS_AUDIO_FORMAT): Response { + return this.provider.preflight(format); + } + + speak(text: string, options: TtsSpeakOptions = {}): Promise { + return this.provider.speak({ + text, + ...options, + }); + } +} + +export const ttsService = new TtsService(); diff --git a/cloud-v2/packages/shared/package.json b/cloud-v2/packages/shared/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7451162a143783668832e8726ad94d3621a2d009 --- /dev/null +++ b/cloud-v2/packages/shared/package.json @@ -0,0 +1,24 @@ +{ + "name": "@mentra/cloud-shared", + "version": "0.0.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./logger": "./src/logger.ts", + "./health": "./src/health.ts", + "./auth": "./src/auth.ts" + }, + "scripts": { + "test": "bun test" + }, + "dependencies": { + "hono": "^4.11.1", + "jose": "^5.9.6", + "pino": "^9.6.0" + }, + "devDependencies": { + "pino-pretty": "^11.3.0" + } +} diff --git a/cloud-v2/packages/shared/src/auth.test.ts b/cloud-v2/packages/shared/src/auth.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b7c9985d2fabe724c7a75a405b5d033e398e82d3 --- /dev/null +++ b/cloud-v2/packages/shared/src/auth.test.ts @@ -0,0 +1,394 @@ +import crypto from "node:crypto" +import {afterEach, describe, expect, test} from "bun:test" +import * as jose from "jose" + +import { + resetMentraKeyCache, + resetRuntimeAuthCache, + signRuntimeToken, + verifyAccessTokenSignature, + verifyRuntimeToken, +} from "./auth" + +const savedEnv = { + MENTRA_JWT_PUBLIC_KEY: process.env.MENTRA_JWT_PUBLIC_KEY, + CLOUD_CORE_ISSUER: process.env.CLOUD_CORE_ISSUER, + CLOUD_RUNTIME_AUTH_AUDIENCE: process.env.CLOUD_RUNTIME_AUTH_AUDIENCE, + CLOUD_RUNTIME_AUTH_ISSUERS: process.env.CLOUD_RUNTIME_AUTH_ISSUERS, + TEST_RUNTIME_PUBLIC_KEY: process.env.TEST_RUNTIME_PUBLIC_KEY, +} + +afterEach(() => { + restoreEnv("CLOUD_RUNTIME_AUTH_AUDIENCE", savedEnv.CLOUD_RUNTIME_AUTH_AUDIENCE) + restoreEnv("CLOUD_RUNTIME_AUTH_ISSUERS", savedEnv.CLOUD_RUNTIME_AUTH_ISSUERS) + restoreEnv("TEST_RUNTIME_PUBLIC_KEY", savedEnv.TEST_RUNTIME_PUBLIC_KEY) + restoreEnv("MENTRA_JWT_PUBLIC_KEY", savedEnv.MENTRA_JWT_PUBLIC_KEY) + restoreEnv("CLOUD_CORE_ISSUER", savedEnv.CLOUD_CORE_ISSUER) + resetRuntimeAuthCache() + resetMentraKeyCache() +}) + +// Core's signing key signs phone access tokens (kid mentra-access-1), runtime +// tokens and the sign-in server's tokens (kid mentra-oidc-1, typ at+jwt). Each +// verifier pins the key ID and type, not only the signature and claims. +describe("phone access token verification pins the key and type", () => { + async function signWithCoreKey(privateKey: string, header: jose.JWTHeaderParameters, claims: jose.JWTPayload = {}) { + const key = await jose.importPKCS8(`-----BEGIN PRIVATE KEY-----\n${privateKey}\n-----END PRIVATE KEY-----`, "EdDSA") + return new jose.SignJWT({tenant_id: "mentra", session_id: "sess_1", ...claims}) + .setProtectedHeader(header) + .setIssuer("cloud-core") + .setAudience("cloud-core") + .setSubject("mu_1") + .setJti("jti_1") + .setIssuedAt() + .setExpirationTime("60s") + .sign(key) + } + + function useCoreKey() { + const keypair = createEd25519Keypair() + process.env.MENTRA_JWT_PUBLIC_KEY = keypair.publicKey + delete process.env.CLOUD_CORE_ISSUER + resetMentraKeyCache() + return keypair + } + + test("a phone access token (kid mentra-access-1, no typ) verifies", async () => { + const keypair = useCoreKey() + const token = await signWithCoreKey(keypair.privateKey, {alg: "EdDSA", kid: "mentra-access-1"}) + await expect(verifyAccessTokenSignature(token)).resolves.toMatchObject({mentraUserId: "mu_1"}) + }) + + test.each([ + ["the sign-in server's kid", {alg: "EdDSA", kid: "mentra-oidc-1"}], + ["an at+jwt access token", {alg: "EdDSA", kid: "mentra-access-1", typ: "at+jwt"}], + ["the runtime kid", {alg: "EdDSA", kid: "cloud-core-runtime-1"}], + ["no kid", {alg: "EdDSA"}], + // The header is caller-controlled JSON: a non-string typ is refused, never a TypeError. + ["a numeric typ", {alg: "EdDSA", kid: "mentra-access-1", typ: 1}], + ["an object typ", {alg: "EdDSA", kid: "mentra-access-1", typ: {}}], + ])("a token with matching claims but %s is refused", async (_label, header) => { + const keypair = useCoreKey() + const token = await signWithCoreKey(keypair.privateKey, header as jose.JWTHeaderParameters) + await expect(verifyAccessTokenSignature(token)).rejects.toThrow("not a Mentra access token") + }) +}) + +describe("runtime token verification pins the key and type", () => { + function configure(extra: Record = {}) { + const keypair = createEd25519Keypair() + process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey + process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([ + {issuer: "test-runtime", publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY", userIdClaim: "sub", tenantIdClaim: "tenant_id", ...extra}, + ]) + return keypair + } + + test.each(["mentra-oidc-1", "mentra-access-1", "mentra-miniapp-1", "mentra-account-1"])( + "a token under Core's %s key ID is never a runtime token", + async (kid) => { + const keypair = configure() + const token = await signRuntimeToken({privateKey: keypair.privateKey, issuer: "test-runtime", subject: "u", tenantId: "t", expiresInSeconds: 60, kid}) + await expect(verifyRuntimeToken(token)).rejects.toThrow("not a runtime token") + }, + ) + + test("a typed at+jwt token is refused", async () => { + const keypair = configure() + const key = await jose.importPKCS8(`-----BEGIN PRIVATE KEY-----\n${keypair.privateKey}\n-----END PRIVATE KEY-----`, "EdDSA") + const token = await new jose.SignJWT({tenant_id: "t"}) + .setProtectedHeader({alg: "EdDSA", kid: "cloud-core-runtime-1", typ: "at+jwt"}) + .setIssuer("test-runtime") + .setAudience("cloud-runtime") + .setSubject("u") + .setIssuedAt() + .setExpirationTime("60s") + .sign(key) + await expect(verifyRuntimeToken(token)).rejects.toThrow("not a runtime token") + }) + + test.each([1, {}])("a non-string typ (%p) is refused, never a TypeError", async (typ) => { + const keypair = configure() + const key = await jose.importPKCS8(`-----BEGIN PRIVATE KEY-----\n${keypair.privateKey}\n-----END PRIVATE KEY-----`, "EdDSA") + const token = await new jose.SignJWT({tenant_id: "t"}) + .setProtectedHeader({alg: "EdDSA", kid: "cloud-core-runtime-1", typ} as unknown as jose.JWTHeaderParameters) + .setIssuer("test-runtime") + .setAudience("cloud-runtime") + .setSubject("u") + .setIssuedAt() + .setExpirationTime("60s") + .sign(key) + await expect(verifyRuntimeToken(token)).rejects.toThrow("not a runtime token") + }) + + test("an issuer's keyIds pin the key ID", async () => { + const keypair = configure({keyIds: ["cloud-core-runtime-1"]}) + const sign = (kid: string) => signRuntimeToken({privateKey: keypair.privateKey, issuer: "test-runtime", subject: "u", tenantId: "t", expiresInSeconds: 60, kid}) + await expect(verifyRuntimeToken(await sign("cloud-core-runtime-1"))).resolves.toMatchObject({mentraUserId: "u"}) + await expect(verifyRuntimeToken(await sign("other-1"))).rejects.toThrow("unexpected key ID") + }) +}) + +describe("runtime token verification", () => { + test("requires explicit runtime issuer config", async () => { + delete process.env.CLOUD_RUNTIME_AUTH_ISSUERS + + await expect(verifyRuntimeToken("not-a-runtime-token")).rejects.toThrow("runtime auth issuer config is required") + }) + + test("accepts a configured cloud-runtime issuer", async () => { + const keypair = createEd25519Keypair() + process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey + process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([ + { + issuer: "test-runtime", + publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY", + userIdClaim: "sub", + tenantIdClaim: "tenant_id", + }, + ]) + + const token = await signRuntimeToken({ + privateKey: keypair.privateKey, + issuer: "test-runtime", + subject: "user-1", + tenantId: "oem-1", + jti: "runtime-jti", + expiresInSeconds: 60, + }) + + await expect(verifyRuntimeToken(token)).resolves.toEqual({ + mentraUserId: "user-1", + tenantId: "oem-1", + sessionId: "runtime_runtime-jti", + jti: "runtime-jti", + exp: expect.any(Number), + }) + }) + + test("preserves a Core-attested federated workforce identity", async () => { + const keypair = createEd25519Keypair() + process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey + process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([ + { + issuer: "https://core.workspace.example", + publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY", + userIdClaim: "sub", + tenantIdClaim: "tenant_id", + }, + ]) + + const token = await signRuntimeToken({ + privateKey: keypair.privateKey, + issuer: "https://core.workspace.example", + subject: "mu_01TEST", + tenantId: "acme-private", + sessionId: "sess_01TEST", + federatedIdentity: { + providerId: "workforce", + providerKind: "microsoft-entra", + issuer: "https://login.microsoftonline.com/tenant/v2.0", + subject: "employee-object-id", + directoryTenantId: "tenant", + }, + expiresInSeconds: 60, + }) + + await expect(verifyRuntimeToken(token)).resolves.toEqual({ + mentraUserId: "mu_01TEST", + tenantId: "acme-private", + sessionId: "sess_01TEST", + jti: expect.any(String), + exp: expect.any(Number), + federatedIdentity: { + providerId: "workforce", + providerKind: "microsoft-entra", + issuer: "https://login.microsoftonline.com/tenant/v2.0", + subject: "employee-object-id", + directoryTenantId: "tenant", + }, + }) + }) + + test("accepts legacy issuer tenant config while preferring tenant_id tokens", async () => { + const keypair = createEd25519Keypair() + process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey + process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([ + { + issuer: "test-runtime", + publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY", + userIdClaim: "sub", + oemIdClaim: "oem_id", + }, + ]) + + const token = await signRuntimeToken({ + privateKey: keypair.privateKey, + issuer: "test-runtime", + subject: "user-1", + tenantId: "tenant-1", + jti: "runtime-jti", + expiresInSeconds: 60, + }) + + await expect(verifyRuntimeToken(token)).resolves.toEqual({ + mentraUserId: "user-1", + tenantId: "tenant-1", + sessionId: "runtime_runtime-jti", + jti: "runtime-jti", + exp: expect.any(Number), + }) + }) + + test("accepts legacy fixed OEM config as fixed tenant config", async () => { + const keypair = createEd25519Keypair() + process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey + process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([ + { + issuer: "test-runtime", + publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY", + userIdClaim: "sub", + fixedOemId: "tenant-legacy", + }, + ]) + + const token = await signRuntimeToken({ + privateKey: keypair.privateKey, + issuer: "test-runtime", + subject: "user-1", + tenantId: "tenant-token", + jti: "runtime-jti", + expiresInSeconds: 60, + }) + + await expect(verifyRuntimeToken(token)).resolves.toEqual({ + mentraUserId: "user-1", + tenantId: "tenant-legacy", + sessionId: "runtime_runtime-jti", + jti: "runtime-jti", + exp: expect.any(Number), + }) + }) + + test("rejects tokens with the wrong audience", async () => { + const keypair = createEd25519Keypair() + process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey + process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([ + { + issuer: "test-runtime", + publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY", + userIdClaim: "sub", + fixedTenantId: "oem-1", + }, + ]) + + const token = await signRuntimeToken({ + privateKey: keypair.privateKey, + issuer: "test-runtime", + audience: "cloud-core", + subject: "user-1", + tenantId: "oem-1", + expiresInSeconds: 60, + }) + + await expect(verifyRuntimeToken(token)).rejects.toThrow("runtime_token rejected") + }) + + test("enforces configured delegated scopes and native client ids", async () => { + const keypair = createEd25519Keypair() + process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey + process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([ + { + issuer: "https://login.example/tenant/v2.0", + publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY", + userIdClaim: "oid", + fixedTenantId: "tenant-1", + requiredScopes: ["mentra.runtime"], + allowedClientIds: ["native-client"], + }, + ]) + + const valid = await signClaims(keypair.privateKey, { + iss: "https://login.example/tenant/v2.0", + aud: "cloud-runtime", + oid: "employee-1", + scp: "mentra.runtime", + azp: "native-client", + }) + await expect(verifyRuntimeToken(valid)).resolves.toEqual({ + mentraUserId: "employee-1", + tenantId: "tenant-1", + sessionId: expect.stringMatching(/^runtime_/), + jti: expect.any(String), + exp: expect.any(Number), + }) + + const wrongClient = await signClaims(keypair.privateKey, { + iss: "https://login.example/tenant/v2.0", + aud: "cloud-runtime", + oid: "employee-1", + scp: "mentra.runtime", + azp: "other-client", + }) + await expect(verifyRuntimeToken(wrongClient)).rejects.toThrow("client is not allowed") + }) + + test("rejects symmetric algorithms and an explicitly empty client allowlist", async () => { + const keypair = createEd25519Keypair() + process.env.TEST_RUNTIME_PUBLIC_KEY = keypair.publicKey + process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([ + { + issuer: "test-runtime", + publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY", + fixedTenantId: "tenant-1", + algorithms: ["HS256"], + }, + ]) + await expect(verifyRuntimeToken("not-reached")).rejects.toThrow("algorithms must use EdDSA, RS256, or ES256") + + process.env.CLOUD_RUNTIME_AUTH_ISSUERS = JSON.stringify([ + { + issuer: "test-runtime", + publicKeyEnv: "TEST_RUNTIME_PUBLIC_KEY", + fixedTenantId: "tenant-1", + allowedClientIds: [], + }, + ]) + const token = await signRuntimeToken({ + privateKey: keypair.privateKey, + issuer: "test-runtime", + subject: "user-1", + tenantId: "tenant-1", + expiresInSeconds: 60, + }) + await expect(verifyRuntimeToken(token)).rejects.toThrow("client is not allowed") + }) +}) + +async function signClaims(privateKey: string, claims: jose.JWTPayload): Promise { + const key = await jose.importPKCS8(`-----BEGIN PRIVATE KEY-----\n${privateKey}\n-----END PRIVATE KEY-----`, "EdDSA") + return new jose.SignJWT(claims).setProtectedHeader({alg: "EdDSA"}).setIssuedAt().setExpirationTime("60s").sign(key) +} + +function createEd25519Keypair(): {privateKey: string; publicKey: string} { + const {privateKey, publicKey} = crypto.generateKeyPairSync("ed25519") + return { + privateKey: stripPem(privateKey.export({type: "pkcs8", format: "pem"}).toString()), + publicKey: stripPem(publicKey.export({type: "spki", format: "pem"}).toString()), + } +} + +function stripPem(pem: string): string { + return pem + .replace(/-----BEGIN [A-Z ]+-----/, "") + .replace(/-----END [A-Z ]+-----/, "") + .replace(/\s+/g, "") +} + +function restoreEnv(key: string, value: string | undefined): void { + if (value === undefined) { + delete process.env[key] + } else { + process.env[key] = value + } +} diff --git a/cloud-v2/packages/shared/src/auth.ts b/cloud-v2/packages/shared/src/auth.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ac27b39c462f7d26387fc15ddbd604cd44f048c --- /dev/null +++ b/cloud-v2/packages/shared/src/auth.ts @@ -0,0 +1,443 @@ +/** + * @fileoverview Mentra access-token verification, shared across packages. + * + * Pure-crypto: signature + claims. **Does not check revocation.** Revocation + * lives in core's Mongo, and only core's wrapper consults it. Other packages + * (audio, proxy) accept up-to-1h staleness on revoked access tokens — the + * actual revocation surface is the refresh token, which core owns. + * + * Both Mentra-issued private and public keys are PEM bodies (base64, no + * BEGIN/END wrapper) in env. See cloud-v2/docs/issues/001-oem-auth/design.md + * "Mentra-issued access token" for the claim shape. + */ + +import crypto from "node:crypto" +import * as jose from "jose" + +const ALG = "EdDSA" +const CORE_AUDIENCE = "cloud-core" +/** The key ID Core signs its phone access tokens under. */ +export const ACCESS_TOKEN_KID = "mentra-access-1" +/** + * Key IDs under which Core signs tokens that are never runtime tokens: phone + * access tokens, the sign-in server's ID and access tokens, miniapp tokens and + * account subject tokens. Some of them share Core's signing key with runtime + * tokens, so the key ID is pinned as well as the claims. + */ +const CORE_NON_RUNTIME_KIDS: ReadonlySet = new Set([ACCESS_TOKEN_KID, "mentra-oidc-1", "mentra-miniapp-1", "mentra-account-1"]) + +/** + * A plain signed JWT: no `typ`, or `typ` "JWT". Typed tokens, such as the + * sign-in server's `at+jwt` access tokens, are never accepted as phone or + * runtime tokens. + */ +function isPlainJwtType(typ: unknown): boolean { + return typ === undefined || (typeof typ === "string" && typ.toUpperCase() === "JWT") +} + +function protectedHeader(token: string, label: string): jose.ProtectedHeaderParameters { + try { + return jose.decodeProtectedHeader(token) + } catch { + throw new AccessTokenError(`${label} is not a parseable JWT`) + } +} + +export interface FederatedIdentity { + providerId: string + providerKind: string + issuer: string + subject: string + directoryTenantId?: string +} + +export interface VerifiedAccessToken { + mentraUserId: string + tenantId: string + sessionId: string + jti: string + exp: number + federatedIdentity?: FederatedIdentity +} + +/** + * Thrown when an access token fails signature or claim verification. Marker + * class so callers can catch via `instanceof AccessTokenError` without + * coupling to specific error messages. + */ +export class AccessTokenError extends Error { + constructor(message: string) { + super(message) + this.name = "AccessTokenError" + } +} + +let publicKeyPromise: Promise | null = null +const RUNTIME_DEFAULT_AUDIENCE = "cloud-runtime" +const RUNTIME_DEFAULT_ALGORITHMS = ["EdDSA", "RS256", "ES256"] as const +const RUNTIME_ALLOWED_ALGORITHMS = new Set(RUNTIME_DEFAULT_ALGORITHMS) + +interface RuntimeIssuerConfig { + issuer: string + jwksUrl?: string + publicKey?: string + publicKeyEnv?: string + userIdClaim?: string + tenantIdClaim?: string + legacyTenantIdClaim?: string + fixedTenantId?: string + algorithms?: string[] + requiredScopes?: string[] + allowedClientIds?: string[] + /** When set, the token's `kid` must be one of these. */ + keyIds?: string[] +} + +const runtimeRemoteJwks = new Map>() +const runtimeStaticKeys = new Map>() + +/** Reset the cached public key. Test-only — call after mutating env. */ +export function resetMentraKeyCache(): void { + publicKeyPromise = null + resetRuntimeAuthCache() +} + +async function getPublicKey(): Promise { + if (!publicKeyPromise) { + const pubBody = process.env.MENTRA_JWT_PUBLIC_KEY + if (!pubBody) { + throw new AccessTokenError("env var MENTRA_JWT_PUBLIC_KEY is not set") + } + const pem = `-----BEGIN PUBLIC KEY-----\n${pubBody}\n-----END PUBLIC KEY-----` + publicKeyPromise = jose.importSPKI(pem, ALG, {extractable: false}) + } + return publicKeyPromise +} + +/** + * Verify signature, issuer, audience, and expiry on a Mentra-issued access + * token. Throws `AccessTokenError` on failure. Does NOT check the revocation + * blacklist — see file header. + */ +export async function verifyAccessTokenSignature(token: string): Promise { + // Core's signing key also signs runtime tokens and the sign-in server's tokens: + // pin the key ID and the token type as well as the issuer and audience. + const header = protectedHeader(token, "access_token") + if (header.kid !== ACCESS_TOKEN_KID || !isPlainJwtType(header.typ)) { + throw new AccessTokenError("access_token rejected: not a Mentra access token") + } + const publicKey = await getPublicKey() + + let payload: jose.JWTPayload + try { + const result = await jose.jwtVerify(token, publicKey, { + audience: CORE_AUDIENCE, + issuer: process.env.CLOUD_CORE_ISSUER ?? "cloud-core", + algorithms: [ALG], + }) + payload = result.payload + } catch (err) { + throw new AccessTokenError(`access_token rejected: ${(err as Error).message}`) + } + + const sub = typeof payload.sub === "string" ? payload.sub : null + const tenantId = typeof payload.tenant_id === "string" ? payload.tenant_id : null + const sessionId = typeof payload.session_id === "string" ? payload.session_id : null + const jti = typeof payload.jti === "string" ? payload.jti : null + const exp = typeof payload.exp === "number" ? payload.exp : null + const federatedIdentity = parseFederatedIdentity(payload.federated_identity) + + const missingClaims = [ + !sub ? "sub" : null, + !tenantId ? "tenant_id" : null, + !sessionId ? "session_id" : null, + !jti ? "jti" : null, + !exp ? "exp" : null, + ].filter((claim): claim is string => Boolean(claim)) + if (missingClaims.length > 0) { + throw new AccessTokenError(`access_token missing required claims: ${missingClaims.join(", ")}`) + } + + return { + mentraUserId: sub!, + tenantId: tenantId!, + sessionId: sessionId!, + jti: jti!, + exp: exp!, + ...(federatedIdentity ? {federatedIdentity} : {}), + } +} + +export async function verifyRuntimeToken(token: string): Promise { + const issuers = configuredRuntimeIssuers() + if (issuers.length === 0) { + throw new AccessTokenError("runtime auth issuer config is required") + } + + const header = protectedHeader(token, "runtime_token") + if (!isPlainJwtType(header.typ) || (header.kid !== undefined && CORE_NON_RUNTIME_KIDS.has(header.kid))) { + throw new AccessTokenError("runtime_token rejected: not a runtime token") + } + + let payload: jose.JWTPayload + let iss: string | undefined + try { + payload = jose.decodeJwt(token) + iss = typeof payload.iss === "string" ? payload.iss : undefined + } catch { + throw new AccessTokenError("runtime_token is not a parseable JWT") + } + + const issuer = issuers.find((entry) => entry.issuer === iss) + if (!issuer) { + throw new AccessTokenError(`runtime_token issuer not trusted: ${iss ?? "missing"}`) + } + + if (issuer.keyIds !== undefined && (header.kid === undefined || !issuer.keyIds.includes(header.kid))) { + throw new AccessTokenError("runtime_token rejected: unexpected key ID") + } + + const key = await runtimeKeyForIssuer(issuer) + try { + const result = await jose.jwtVerify(token, key as jose.JWTVerifyGetKey, { + audience: process.env.CLOUD_RUNTIME_AUTH_AUDIENCE ?? RUNTIME_DEFAULT_AUDIENCE, + issuer: issuer.issuer, + algorithms: issuer.algorithms ?? [...RUNTIME_DEFAULT_ALGORITHMS], + clockTolerance: "5 minutes", + }) + payload = result.payload + } catch (err) { + throw new AccessTokenError(`runtime_token rejected: ${(err as Error).message}`) + } + + const scopes = new Set(typeof payload.scp === "string" ? payload.scp.split(" ").filter(Boolean) : []) + for (const requiredScope of issuer.requiredScopes ?? []) { + if (!scopes.has(requiredScope)) { + throw new AccessTokenError(`runtime_token missing required scope: ${requiredScope}`) + } + } + if (issuer.allowedClientIds !== undefined) { + const clientId = stringClaim(payload.azp) ?? stringClaim(payload.appid) + if (!clientId || !issuer.allowedClientIds.includes(clientId)) { + throw new AccessTokenError("runtime_token client is not allowed") + } + } + + const userIdClaim = issuer.userIdClaim ?? "sub" + const userId = stringClaim(payload[userIdClaim]) + const tenantId = + issuer.fixedTenantId ?? + stringClaim(payload[issuer.tenantIdClaim ?? "tenant_id"]) ?? + (issuer.legacyTenantIdClaim ? stringClaim(payload[issuer.legacyTenantIdClaim]) : undefined) + const jti = stringClaim(payload.jti) ?? cryptoRandomId() + const sessionId = stringClaim(payload.session_id) ?? `runtime_${jti}` + const exp = typeof payload.exp === "number" ? payload.exp : undefined + + if (!userId || !tenantId || !exp) { + throw new AccessTokenError("runtime_token missing required identity claims") + } + + const federatedIdentity = parseFederatedIdentity(payload.federated_identity) + return { + mentraUserId: userId, + tenantId, + sessionId, + jti, + exp, + ...(federatedIdentity ? {federatedIdentity} : {}), + } +} + +export async function signRuntimeToken(args: { + privateKey: string + issuer: string + audience?: string + subject: string + tenantId: string + sessionId?: string + jti?: string + expiresInSeconds: number + kid?: string + federatedIdentity?: FederatedIdentity +}): Promise { + const privateKey = await jose.importPKCS8(toPrivatePem(args.privateKey), "EdDSA", {extractable: false}) + const claims: jose.JWTPayload = { + tenant_id: args.tenantId, + } + if (args.federatedIdentity) { + claims.federated_identity = serializeFederatedIdentity(args.federatedIdentity) + } + if (args.sessionId) claims.session_id = args.sessionId + const jwt = new jose.SignJWT(claims) + .setProtectedHeader({alg: "EdDSA", kid: args.kid ?? "cloud-runtime-1"}) + .setIssuer(args.issuer) + .setAudience(args.audience ?? RUNTIME_DEFAULT_AUDIENCE) + .setSubject(args.subject) + .setIssuedAt() + .setExpirationTime(`${args.expiresInSeconds}s`) + if (args.jti) jwt.setJti(args.jti) + return jwt.sign(privateKey) +} + +function serializeFederatedIdentity(identity: FederatedIdentity): Record { + return { + provider_id: identity.providerId, + provider_kind: identity.providerKind, + issuer: identity.issuer, + subject: identity.subject, + ...(identity.directoryTenantId ? {directory_tenant_id: identity.directoryTenantId} : {}), + } +} + +function parseFederatedIdentity(value: unknown): FederatedIdentity | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return undefined + } + const claims = value as Record + const providerId = stringClaim(claims.provider_id) + const providerKind = stringClaim(claims.provider_kind) + const issuer = stringClaim(claims.issuer) + const subject = stringClaim(claims.subject) + if (!providerId || !providerKind || !issuer || !subject) return undefined + const directoryTenantId = stringClaim(claims.directory_tenant_id) + return { + providerId, + providerKind, + issuer, + subject, + ...(directoryTenantId ? {directoryTenantId} : {}), + } +} + +export function resetRuntimeAuthCache(): void { + runtimeRemoteJwks.clear() + runtimeStaticKeys.clear() +} + +export function assertRuntimeAuthConfigured(): void { + const issuers = configuredRuntimeIssuers() + if (issuers.length === 0) { + throw new AccessTokenError( + [ + "CLOUD_RUNTIME_AUTH_ISSUERS must configure at least one issuer.", + "For local Cloud V2 development, run `bun run dev` from cloud-v2.", + "That command starts the integrated dev stack and generates matching local Core/Runtime auth keys.", + "Use `bun run dev:runtime` only when intentionally running Runtime in isolation with CLOUD_RUNTIME_AUTH_ISSUERS set yourself.", + ].join(" "), + ) + } +} + +function configuredRuntimeIssuers(): RuntimeIssuerConfig[] { + const raw = process.env.CLOUD_RUNTIME_AUTH_ISSUERS + if (!raw?.trim()) return [] + try { + const parsed = JSON.parse(raw) as unknown + if (!Array.isArray(parsed)) throw new Error("expected array") + return parsed.map(parseRuntimeIssuerConfig) + } catch (err) { + throw new AccessTokenError(`CLOUD_RUNTIME_AUTH_ISSUERS is invalid: ${(err as Error).message}`) + } +} + +function parseRuntimeIssuerConfig(value: unknown): RuntimeIssuerConfig { + if (!value || typeof value !== "object") { + throw new Error("issuer config must be an object") + } + const obj = value as Record + const issuer = stringClaim(obj.issuer) + if (!issuer) throw new Error("issuer config missing issuer") + + const legacyTenantIdClaim = stringClaim(obj.oemIdClaim) + const legacyFixedTenantId = stringClaim(obj.fixedOemId) + const tenantIdClaim = stringClaim(obj.tenantIdClaim) ?? (legacyTenantIdClaim ? "tenant_id" : undefined) + const fixedTenantId = stringClaim(obj.fixedTenantId) ?? legacyFixedTenantId + if (!tenantIdClaim && !fixedTenantId) { + throw new Error(`issuer ${issuer} must set tenantIdClaim or fixedTenantId`) + } + if (tenantIdClaim && fixedTenantId) { + throw new Error(`issuer ${issuer} cannot set both tenantIdClaim and fixedTenantId`) + } + + const algorithms = Array.isArray(obj.algorithms) + ? obj.algorithms.filter((v): v is string => typeof v === "string") + : undefined + if ( + algorithms !== undefined && + (algorithms.length === 0 || algorithms.some((algorithm) => !RUNTIME_ALLOWED_ALGORITHMS.has(algorithm))) + ) { + throw new Error(`issuer ${issuer} algorithms must use EdDSA, RS256, or ES256`) + } + const requiredScopes = stringArrayClaim(obj.requiredScopes, "requiredScopes") + const allowedClientIds = stringArrayClaim(obj.allowedClientIds, "allowedClientIds") + const keyIds = stringArrayClaim(obj.keyIds, "keyIds") + + return { + issuer, + jwksUrl: stringClaim(obj.jwksUrl), + publicKey: stringClaim(obj.publicKey), + publicKeyEnv: stringClaim(obj.publicKeyEnv), + userIdClaim: stringClaim(obj.userIdClaim), + tenantIdClaim, + legacyTenantIdClaim, + fixedTenantId, + algorithms, + requiredScopes, + allowedClientIds, + keyIds, + } +} + +function stringArrayClaim(value: unknown, name: string): string[] | undefined { + if (value === undefined) return undefined + if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || !entry.trim())) { + throw new Error(`${name} must be an array of non-empty strings`) + } + return value as string[] +} + +async function runtimeKeyForIssuer( + issuer: RuntimeIssuerConfig, +): Promise> { + if (issuer.jwksUrl) { + let jwks = runtimeRemoteJwks.get(issuer.jwksUrl) + if (!jwks) { + jwks = jose.createRemoteJWKSet(new URL(issuer.jwksUrl), { + cooldownDuration: 30_000, + cacheMaxAge: 5 * 60_000, + }) + runtimeRemoteJwks.set(issuer.jwksUrl, jwks) + } + return jwks + } + + const keyMaterial = issuer.publicKey ?? (issuer.publicKeyEnv ? process.env[issuer.publicKeyEnv] : undefined) + if (!keyMaterial) { + throw new AccessTokenError(`issuer ${issuer.issuer} has no key source`) + } + + let key = runtimeStaticKeys.get(keyMaterial) + if (!key) { + key = jose.importSPKI(toPublicPem(keyMaterial), issuer.algorithms?.[0] ?? "EdDSA", {extractable: false}) + runtimeStaticKeys.set(keyMaterial, key) + } + return key +} + +function toPublicPem(value: string): string { + if (value.includes("BEGIN PUBLIC KEY")) return value + return `-----BEGIN PUBLIC KEY-----\n${value}\n-----END PUBLIC KEY-----` +} + +function toPrivatePem(value: string): string { + if (value.includes("BEGIN PRIVATE KEY")) return value + return `-----BEGIN PRIVATE KEY-----\n${value}\n-----END PRIVATE KEY-----` +} + +function stringClaim(value: unknown): string | undefined { + return typeof value === "string" && value.length > 0 ? value : undefined +} + +function cryptoRandomId(): string { + return crypto.randomBytes(16).toString("hex") +} diff --git a/cloud-v2/packages/shared/src/health.ts b/cloud-v2/packages/shared/src/health.ts new file mode 100644 index 0000000000000000000000000000000000000000..8011353ae73815cfa9a70e462cddc6c44674228a --- /dev/null +++ b/cloud-v2/packages/shared/src/health.ts @@ -0,0 +1,84 @@ +/** + * Health and readiness endpoint factory. + * + * `/healthz` — liveness. Returns 200 if the event loop is responsive + * (which it is by definition if we're answering). K8s liveness probe + * uses this; a failure triggers pod restart. + * + * `/ready` — readiness. Returns 200 only if every configured readiness + * check passes. Otherwise 503 with the failing checks listed in the + * response body. K8s readiness probe uses this; a failure removes the + * pod from the Service's load balancer rotation but does NOT restart + * it. Useful for transient dependency outages (Mongo briefly down, + * etc.) where restarting wouldn't help. + * + * Each package wires its own readiness checks (Redis ping, Mongo ping, + * worker pool alive, etc.). + */ + +import { Hono } from "hono"; + +export type ReadinessCheck = { + name: string; + /** Return true if healthy. Throw or return false to fail. */ + check: () => Promise | boolean; +}; + +export type HealthAppOptions = { + /** Which cloud-v2 package this is. Echoed in responses for debugging. */ + packageName: string; + /** Optional readiness checks evaluated on every /ready hit. */ + readinessChecks?: ReadinessCheck[]; + /** Non-secret static service composition surfaced for operators. */ + details?: Record; +}; + +type CheckResult = { + name: string; + ok: boolean; + error?: string; +}; + +export function createHealthApp(opts: HealthAppOptions): Hono { + const app = new Hono(); + + app.get("/healthz", (c) => + c.json({ status: "ok", package: opts.packageName, ...opts.details }), + ); + + app.get("/ready", async (c) => { + const checks = opts.readinessChecks ?? []; + const results: CheckResult[] = []; + + for (const rc of checks) { + try { + const ok = await rc.check(); + results.push({ name: rc.name, ok }); + } catch (err) { + console.error("readiness check failed", { + packageName: opts.packageName, + check: rc.name, + err, + }); + results.push({ + name: rc.name, + ok: false, + error: "readiness check failed", + }); + } + } + + const allOk = results.every((r) => r.ok); + return c.json( + { + status: allOk ? "ok" : "not_ready", + package: opts.packageName, + checks: results, + ...opts.details, + }, + allOk ? 200 : 503, + ); + }); + + return app; +} diff --git a/cloud-v2/packages/shared/src/index.ts b/cloud-v2/packages/shared/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..82b2e505d81a7a274d4d9aedbb9d22279ea7c104 --- /dev/null +++ b/cloud-v2/packages/shared/src/index.ts @@ -0,0 +1,21 @@ +/** + * `@mentra/cloud-shared` — types, config, observability primitives shared + * across the core, audio, and proxy packages. + */ + +export {createLogger, type Logger} from "./logger" +export {createHealthApp, type HealthAppOptions, type ReadinessCheck} from "./health" +export { + verifyAccessTokenSignature, + assertRuntimeAuthConfigured, + verifyRuntimeToken, + signRuntimeToken, + AccessTokenError, + resetMentraKeyCache, + resetRuntimeAuthCache, + type VerifiedAccessToken, + type FederatedIdentity, +} from "./auth" +export {verifyOidcToken, resetOidcVerifierCache, OidcTokenError, type OidcProviderConfig} from "./oidc" + +export const PACKAGE_NAME = "@mentra/cloud-shared" diff --git a/cloud-v2/packages/shared/src/logger.ts b/cloud-v2/packages/shared/src/logger.ts new file mode 100644 index 0000000000000000000000000000000000000000..269710f4502216e3ee7b34b0fed5f0ed329b4076 --- /dev/null +++ b/cloud-v2/packages/shared/src/logger.ts @@ -0,0 +1,85 @@ +/** + * Cloud V2 logger. Pino-based, structured JSON. + * + * Two output modes, selected by `LOG_STDOUT_JSON` env var: + * + * LOG_STDOUT_JSON=true → raw JSON to stdout, picked up by Vector (BetterStack) + * (anything else) → pino-pretty for human-readable dev output + * + * Every log line carries pod-level metadata (hostname, env, region, package). + * Sub-loggers via `.child({ service: ... })` add scope without losing pod fields. + * + * Conventions: include a `feature` field for cross-cutting concerns + * (e.g. `feature: "audio-ingress"`) and a `service` field for the component + * emitting the log. Both fields are filterable in the future when needed. + */ + +import { hostname } from "node:os"; +import pino, { type Logger, type LoggerOptions } from "pino"; + +const NODE_ENV = process.env.NODE_ENV ?? "development"; +const REGION = process.env.REGION ?? process.env.DEPLOYMENT_REGION ?? "local"; +const LOG_LEVEL = process.env.LOG_LEVEL ?? (NODE_ENV === "production" ? "info" : "debug"); +const LOG_STDOUT_JSON = process.env.LOG_STDOUT_JSON === "true"; + +// pino-pretty types use a CJS export-assignment (`export =`), so the module +// type IS the factory; the runtime `.default` comes from Bun's ESM interop of +// that same assignment and needs a cast to line the two views up. +type PrettyFactory = typeof import("pino-pretty"); + +const PinoPretty: PrettyFactory | null = LOG_STDOUT_JSON + ? null + : ((await import("pino-pretty")) as unknown as { default: PrettyFactory }).default; + +function podHostname(): string { + if (NODE_ENV === "production") { + return hostname(); + } + return `local-${hostname()}-${process.pid}`; +} + +/** + * Build a root logger for a specific package. + * + * @param packageName e.g. "core", "audio", "proxy". Becomes the `package` field on every log line. + */ +export function createLogger(packageName: string): Logger { + const base = { + package: packageName, + pod: podHostname(), + env: NODE_ENV, + region: REGION, + }; + + const options: LoggerOptions = { + level: LOG_LEVEL, + base, + timestamp: pino.stdTimeFunctions.isoTime, + formatters: { + level(label) { + return { level: label }; + }, + }, + }; + + if (LOG_STDOUT_JSON) { + // Raw JSON to stdout; Vector picks it up from the container's stdout. + return pino(options); + } + + // Dev mode: pino-pretty as a direct stream. + // We avoid `transport: { target: "pino-pretty" }` because that uses Node + // worker_threads, which doesn't resolve pino-pretty's entry point cleanly + // under Bun. Passing the pretty stream directly to pino() works on both + // Bun and Node. + // Non-null: PinoPretty is only null when LOG_STDOUT_JSON, returned above. + const prettyStream = PinoPretty!({ + colorize: true, + translateTime: "HH:MM:ss.l", + ignore: "pod,env,region", + singleLine: false, + }); + return pino(options, prettyStream); +} + +export type { Logger }; diff --git a/cloud-v2/packages/shared/src/oidc.ts b/cloud-v2/packages/shared/src/oidc.ts new file mode 100644 index 0000000000000000000000000000000000000000..91bced229d5bef0b2de4fb25edbcbd634c06df94 --- /dev/null +++ b/cloud-v2/packages/shared/src/oidc.ts @@ -0,0 +1,81 @@ +import * as jose from "jose" + +export interface OidcProviderConfig { + issuer: string + jwksUrl: string + audience: string + algorithms?: string[] + requiredScopes?: string[] + allowedClientIds?: string[] +} + +export class OidcTokenError extends Error { + constructor(message: string) { + super(message) + this.name = "OidcTokenError" + } +} + +const remoteJwks = new Map>() +const ALLOWED_OIDC_ALGORITHMS = new Set(["EdDSA", "RS256", "ES256"]) + +export async function verifyOidcToken(token: string, config: OidcProviderConfig): Promise { + const algorithms = config.algorithms ?? ["RS256"] + if (algorithms.length === 0 || algorithms.some((algorithm) => !ALLOWED_OIDC_ALGORITHMS.has(algorithm))) { + throw new OidcTokenError("OIDC algorithms must use EdDSA, RS256, or ES256") + } + + let keySet = remoteJwks.get(config.jwksUrl) + if (!keySet) { + let url: URL + try { + url = new URL(config.jwksUrl) + } catch { + throw new OidcTokenError("OIDC jwksUrl is not a valid URL") + } + if (url.protocol !== "https:") { + throw new OidcTokenError("OIDC jwksUrl must use HTTPS") + } + keySet = jose.createRemoteJWKSet(url, { + cooldownDuration: 30_000, + cacheMaxAge: 5 * 60_000, + }) + remoteJwks.set(config.jwksUrl, keySet) + } + + let payload: jose.JWTPayload + try { + ;({payload} = await jose.jwtVerify(token, keySet, { + issuer: config.issuer, + audience: config.audience, + algorithms, + clockTolerance: "5 minutes", + })) + } catch (err) { + throw new OidcTokenError(`OIDC token rejected: ${(err as Error).message}`) + } + + const grantedScopes = new Set(typeof payload.scp === "string" ? payload.scp.split(" ").filter(Boolean) : []) + for (const requiredScope of config.requiredScopes ?? []) { + if (!grantedScopes.has(requiredScope)) { + throw new OidcTokenError(`OIDC token missing required scope: ${requiredScope}`) + } + } + + if (config.allowedClientIds !== undefined) { + const clientId = stringClaim(payload.azp) ?? stringClaim(payload.appid) + if (!clientId || !config.allowedClientIds.includes(clientId)) { + throw new OidcTokenError("OIDC token client is not allowed") + } + } + + return payload +} + +export function resetOidcVerifierCache(): void { + remoteJwks.clear() +} + +function stringClaim(value: unknown): string | undefined { + return typeof value === "string" && value.length > 0 ? value : undefined +} diff --git a/cloud-v2/packages/shared/tsconfig.json b/cloud-v2/packages/shared/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..cb555584569f6b4b761a33a4389edad736b566da --- /dev/null +++ b/cloud-v2/packages/shared/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "composite": true, + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"] +} diff --git a/cloud-v2/packages/workspace-contract/package.json b/cloud-v2/packages/workspace-contract/package.json new file mode 100644 index 0000000000000000000000000000000000000000..55770924197b1100face574e289f0f2b42f2c6db --- /dev/null +++ b/cloud-v2/packages/workspace-contract/package.json @@ -0,0 +1,18 @@ +{ + "name": "@mentra/workspace-contract", + "version": "0.0.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./server": "./src/server.ts", + "./fleet-ui": "./src/fleet-ui.ts", + "./portal-module-ui": "./src/portal-module-ui.ts", + "./portal-billing": "./src/portal-billing.ts", + "./portal-billing-icons": "./src/portal-billing-icons.ts" + }, + "dependencies": { + "zod": "^3.24.1" + } +} diff --git a/cloud-v2/packages/workspace-contract/src/capabilities.test.ts b/cloud-v2/packages/workspace-contract/src/capabilities.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7dc2499ead3756089af544b3358027996edb4358 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/capabilities.test.ts @@ -0,0 +1,121 @@ +import {describe, expect, test} from "bun:test" +import type {WorkspaceCapability, WorkspaceRole} from "./capabilities" +import { + OPERATOR_KEY_SCOPES, + ORGANIZATION_CAPABILITIES, + WORKSPACE_CAPABILITIES, + WORKSPACE_ROLES, + canChangeRole, + capabilitiesForRole, + roleAtLeast, +} from "./capabilities" + +describe("capabilitiesForRole", () => { + test("roles are cumulative", () => { + expect(capabilitiesForRole("member").has("miniapps.publish")).toBe(false) + expect(capabilitiesForRole("developer").has("miniapps.publish")).toBe(true) + expect(capabilitiesForRole("developer").has("workspace.members.read")).toBe(false) + expect(capabilitiesForRole("admin").has("fleet.read")).toBe(true) + expect(capabilitiesForRole("admin").has("workspace.roles.managePrivileged")).toBe(false) + expect(capabilitiesForRole("owner").has("workspace.delete")).toBe(true) + }) + + test("the owner holds every workspace capability and each role holds all the capabilities of the one below", () => { + expect([...capabilitiesForRole("owner")].sort()).toEqual([...WORKSPACE_CAPABILITIES].sort()) + for (let i = 1; i < WORKSPACE_ROLES.length; i++) { + const lower = capabilitiesForRole(WORKSPACE_ROLES[i - 1]) + const higher = capabilitiesForRole(WORKSPACE_ROLES[i]) + for (const capability of lower) expect(higher.has(capability)).toBe(true) + expect(higher.size).toBeGreaterThan(lower.size) + } + }) + + test("each role holds exactly the documented capability set", () => { + const member: WorkspaceCapability[] = ["workspace.read", "miniapps.access"] + const developer: WorkspaceCapability[] = [...member, "miniapps.publish", "miniapps.credentials.create"] + const admin: WorkspaceCapability[] = [ + ...developer, + "workspace.members.read", + "workspace.members.manage", + "workspace.settings.manage", + "workspace.audit.read", + "workspace.credentials.revoke", + "fleet.read", + "fleet.devices.manage", + "miniapps.assign", + "workspace.licenses.read", + "workspace.licenses.assign", + "workspace.billing.manage", + ] + const owner: WorkspaceCapability[] = [...admin, "workspace.roles.managePrivileged", "workspace.delete"] + const expected: Record = {member, developer, admin, owner} + for (const role of WORKSPACE_ROLES) { + expect([...capabilitiesForRole(role)].sort()).toEqual([...expected[role]].sort()) + } + }) +}) + +describe("roleAtLeast", () => { + test("orders roles from member up to owner", () => { + expect(roleAtLeast("owner", "admin")).toBe(true) + expect(roleAtLeast("admin", "admin")).toBe(true) + expect(roleAtLeast("developer", "admin")).toBe(false) + expect(roleAtLeast("member", "member")).toBe(true) + expect(roleAtLeast("member", "developer")).toBe(false) + }) +}) + +describe("canChangeRole", () => { + test("admins move members and developers only; owners guard privileged roles on both sides", () => { + expect(canChangeRole("admin", "member", "developer")).toBe(true) + expect(canChangeRole("admin", null, "member")).toBe(true) // invite + expect(canChangeRole("admin", "developer", null)).toBe(true) // remove + expect(canChangeRole("admin", "member", "admin")).toBe(false) // grant privileged + expect(canChangeRole("admin", "admin", "member")).toBe(false) // demote privileged + expect(canChangeRole("admin", null, "admin")).toBe(false) // invite privileged + expect(canChangeRole("owner", "admin", "owner")).toBe(true) + expect(canChangeRole("developer", "member", "developer")).toBe(false) + }) + + test("only owners can remove or grant owner and admin", () => { + expect(canChangeRole("admin", "owner", null)).toBe(false) + expect(canChangeRole("admin", null, "owner")).toBe(false) + expect(canChangeRole("owner", "owner", null)).toBe(true) + expect(canChangeRole("owner", null, "owner")).toBe(true) + expect(canChangeRole("member", null, "member")).toBe(false) + }) +}) + +describe("operator key scopes", () => { + test("never include workspace administration and are all organization capabilities", () => { + expect(OPERATOR_KEY_SCOPES).not.toContain("organization.workspaces.administer") + expect(OPERATOR_KEY_SCOPES).not.toContain("organization.credentials.manage") + for (const scope of OPERATOR_KEY_SCOPES) expect(ORGANIZATION_CAPABILITIES).toContain(scope) + }) + + test("organization.fleet.administer is an organization capability and not an operator key scope", () => { + expect(ORGANIZATION_CAPABILITIES).toContain("organization.fleet.administer") + expect(OPERATOR_KEY_SCOPES).not.toContain("organization.fleet.administer") + }) + + test("organization.licenses.read is an organization capability and not an operator key scope", () => { + expect(ORGANIZATION_CAPABILITIES).toContain("organization.licenses.read") + expect(OPERATOR_KEY_SCOPES).not.toContain("organization.licenses.read") + }) + + test("organization.registry.administer is an organization capability and not an operator key scope", () => { + expect(ORGANIZATION_CAPABILITIES).toContain("organization.registry.administer") + expect(OPERATOR_KEY_SCOPES).not.toContain("organization.registry.administer") + }) +}) + +describe("license capabilities", () => { + test("Admins and Owners read licenses, assign seats and manage billing; Members and Developers do none of it", () => { + for (const capability of ["workspace.licenses.read", "workspace.licenses.assign", "workspace.billing.manage"] as const) { + expect({capability, member: capabilitiesForRole("member").has(capability)}).toEqual({capability, member: false}) + expect({capability, developer: capabilitiesForRole("developer").has(capability)}).toEqual({capability, developer: false}) + expect({capability, admin: capabilitiesForRole("admin").has(capability)}).toEqual({capability, admin: true}) + expect({capability, owner: capabilitiesForRole("owner").has(capability)}).toEqual({capability, owner: true}) + } + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/capabilities.ts b/cloud-v2/packages/workspace-contract/src/capabilities.ts new file mode 100644 index 0000000000000000000000000000000000000000..814d05ff822c26145a219c515d4e29eefca6a37f --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/capabilities.ts @@ -0,0 +1,96 @@ +/** Workspace roles, capabilities and the role-change rules shared by Core, the Store and the CLI. */ + +export const WORKSPACE_ROLES = ["member", "developer", "admin", "owner"] as const +export type WorkspaceRole = (typeof WORKSPACE_ROLES)[number] + +export const WORKSPACE_CAPABILITIES = [ + "workspace.read", + "miniapps.access", + "miniapps.publish", + "miniapps.credentials.create", + "workspace.credentials.revoke", + "workspace.members.read", + "workspace.members.manage", + "workspace.settings.manage", + "workspace.audit.read", + "workspace.roles.managePrivileged", + "workspace.delete", + "fleet.read", + "fleet.devices.manage", + "miniapps.assign", + "workspace.licenses.read", + "workspace.licenses.assign", + "workspace.billing.manage", +] as const +export type WorkspaceCapability = (typeof WORKSPACE_CAPABILITIES)[number] + +export const ORGANIZATION_CAPABILITIES = [ + "organization.workspaces.administer", + "organization.credentials.manage", + "organization.incidents.read", + "organization.supportProfiles.read", + "organization.testing.read", + "organization.testing.manage", + "organization.fleet.administer", + "organization.licenses.read", + "organization.registry.administer", +] as const +export type OrganizationCapability = (typeof ORGANIZATION_CAPABILITIES)[number] + +/** Scopes an operator key may carry; never workspace administration, Fleet administration, licenses or the miniapp registry. */ +export const OPERATOR_KEY_SCOPES: readonly OrganizationCapability[] = [ + "organization.incidents.read", + "organization.supportProfiles.read", + "organization.testing.read", + "organization.testing.manage", +] + +/** Capabilities each role adds on top of the role below it. */ +const ROLE_ADDITIONS: Record = { + member: ["workspace.read", "miniapps.access"], + developer: ["miniapps.publish", "miniapps.credentials.create"], + admin: [ + "workspace.members.read", + "workspace.members.manage", + "workspace.settings.manage", + "workspace.audit.read", + "workspace.credentials.revoke", + "fleet.read", + "fleet.devices.manage", + "miniapps.assign", + "workspace.licenses.read", + "workspace.licenses.assign", + "workspace.billing.manage", + ], + owner: ["workspace.roles.managePrivileged", "workspace.delete"], +} + +const CAPABILITIES_BY_ROLE = (() => { + const result = {} as Record> + const accumulated = new Set() + for (const role of WORKSPACE_ROLES) { + for (const capability of ROLE_ADDITIONS[role]) accumulated.add(capability) + result[role] = new Set(accumulated) + } + return result +})() + +export function capabilitiesForRole(role: WorkspaceRole): ReadonlySet { + return CAPABILITIES_BY_ROLE[role] +} + +export function roleAtLeast(role: WorkspaceRole, min: WorkspaceRole): boolean { + return WORKSPACE_ROLES.indexOf(role) >= WORKSPACE_ROLES.indexOf(min) +} + +const isPrivileged = (role: WorkspaceRole | null) => role === "admin" || role === "owner" + +/** + * Whether `actor` may move a member from `from` to `to` (`null` is "not a member", so invite is + * `null → role` and remove is `role → null`). Owner-only when either side of the transition is + * admin or owner; otherwise an admin is enough. + */ +export function canChangeRole(actor: WorkspaceRole, from: WorkspaceRole | null, to: WorkspaceRole | null): boolean { + if (isPrivileged(from) || isPrivileged(to)) return actor === "owner" + return roleAtLeast(actor, "admin") +} diff --git a/cloud-v2/packages/workspace-contract/src/client.test.ts b/cloud-v2/packages/workspace-contract/src/client.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..14b99fdfe16ffe821cbc534a6e19c11fdf620e6c --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/client.test.ts @@ -0,0 +1,963 @@ +import {describe, expect, test} from "bun:test" +import {CoreWorkspaceClientError, createCoreWorkspaceClient} from "./client" +import {SERVICE_HEADERS, verifyServiceRequest} from "./service-signature" +import {INVALID_TOKEN_ERROR, SERVICE_UNAUTHORIZED_ERROR} from "./types" +import type {WorkspaceRole} from "./capabilities" +import type {LicenseView, LicenseWrite} from "./licenses" +import type { + AuthorizeResponse, + DeletionHoldsResponse, + PrincipalResponse, + RegistryCheckResult, + RegistryEntryDetail, + WorkspaceChangeEvent, + WorkspaceDeletionHold, + WorkspaceSummary, +} from "./types" + +const SECRET = "client-secret" +const BASE = "https://core.test" + +interface Recorded { + url: string + method: string + headers: Headers + body: string +} + +type Handler = (request: Recorded, init: RequestInit) => Response | Promise + +function mockFetch(handler: Handler) { + const calls: Recorded[] = [] + const fetchImpl = async (input: string | URL | Request, init: RequestInit = {}) => { + const recorded: Recorded = { + url: String(input), + method: init.method ?? "GET", + headers: new Headers(init.headers), + body: typeof init.body === "string" ? init.body : "", + } + calls.push(recorded) + return handler(recorded, init) + } + return {calls, fetch: fetchImpl as unknown as typeof fetch} +} + +function json(body: unknown, status = 200) { + return new Response(JSON.stringify(body), {status, headers: {"content-type": "application/json"}}) +} + +function clientFor(handler: Handler, overrides: {timeoutMs?: number; baseUrl?: string} = {}) { + const mock = mockFetch(handler) + const client = createCoreWorkspaceClient({ + baseUrl: overrides.baseUrl ?? BASE, + service: "store", + secret: SECRET, + fetch: mock.fetch, + timeoutMs: overrides.timeoutMs, + }) + return {client, calls: mock.calls} +} + +const workspace = (): WorkspaceSummary => ({ + workspaceId: "ws_1", + name: "Acme", + status: "active", + authorizationRevision: 3, +}) + +const changeEvent = (seq: number, overrides: Partial = {}): WorkspaceChangeEvent => ({ + eventId: `01HZ00000000000000000000${seq}`, + seq, + workspaceId: "ws_1", + action: "membership.added", + occurredAt: "2026-10-13T12:00:00.000Z", + target: {membershipId: "wm_1", mentraUserId: "mu_1"}, + before: {role: null}, + after: {role: "member"}, + ...overrides, +}) + +const userPrincipal = () => + ({ + kind: "user", + mentraUserId: "user_1", + email: "a@example.com", + emailVerified: true, + isOrganizationAdmin: false, + } as const) + +const allowed = (): AuthorizeResponse => ({ + allowed: true, + principal: userPrincipal(), + workspace: workspace(), + membership: {membershipId: "mem_1", role: "developer"}, + capabilities: ["workspace.read", "miniapps.access", "miniapps.publish"], +}) + +async function expectClientError(promise: Promise, code: CoreWorkspaceClientError["code"]) { + const error = await promise.then( + () => null, + (caught: unknown) => caught, + ) + expect(error).toBeInstanceOf(CoreWorkspaceClientError) + expect((error as CoreWorkspaceClientError).code).toBe(code) + return error as CoreWorkspaceClientError +} + +describe("request signing", () => { + test("signs every request with the service headers over the exact path, query and body", async () => { + const {client, calls} = clientFor((request) => { + if (request.url.includes("/workspaces/ws%201")) return json(workspace()) + if (request.url.endsWith("/authorize")) return json(allowed()) + return json({}) + }) + + const before = Date.now() + await client.authorize({credential: {type: "mentra_user", mentraUserId: "user_1"}, workspaceId: "ws_1"}) + await client.getWorkspace("ws 1") + const after = Date.now() + + expect(calls.map((call) => call.url)).toEqual([ + `${BASE}/api/internal/workspaces/authorize`, + `${BASE}/api/internal/workspaces/workspaces/ws%201`, + ]) + for (const call of calls) { + const url = new URL(call.url) + expect(call.headers.get(SERVICE_HEADERS.service)).toBe("store") + const timestampMs = Number(call.headers.get(SERVICE_HEADERS.timestamp)) + expect(timestampMs).toBeGreaterThanOrEqual(before) + expect(timestampMs).toBeLessThanOrEqual(after) + expect( + verifyServiceRequest({ + secrets: [SECRET], + method: call.method, + pathWithQuery: `${url.pathname}${url.search}`, + body: call.body, + timestampMs, + signature: call.headers.get(SERVICE_HEADERS.signature) ?? "", + nowMs: timestampMs, + }), + ).toBe(true) + } + expect(calls[0].method).toBe("POST") + expect(calls[0].headers.get("content-type")).toBe("application/json") + expect(JSON.parse(calls[0].body)).toEqual({ + credential: {type: "mentra_user", mentraUserId: "user_1"}, + workspaceId: "ws_1", + }) + expect(calls[1].method).toBe("GET") + expect(calls[1].body).toBe("") + }) + + test("does not verify under another secret", async () => { + const {client, calls} = clientFor(() => json(workspace())) + await client.getWorkspace("ws_1") + const call = calls[0] + const timestampMs = Number(call.headers.get(SERVICE_HEADERS.timestamp)) + expect( + verifyServiceRequest({ + secrets: ["other"], + method: "GET", + pathWithQuery: "/api/internal/workspaces/workspaces/ws_1", + body: "", + timestampMs, + signature: call.headers.get(SERVICE_HEADERS.signature) ?? "", + nowMs: timestampMs, + }), + ).toBe(false) + }) + + test("tolerates a trailing slash on the base URL", async () => { + const {client, calls} = clientFor(() => json(workspace()), {baseUrl: `${BASE}/`}) + await client.getWorkspace("ws_1") + expect(calls[0].url).toBe(`${BASE}/api/internal/workspaces/workspaces/ws_1`) + }) +}) + +describe("operations", () => { + test("authorize returns the decision from Core", async () => { + const {client} = clientFor(() => json(allowed())) + const response = await client.authorize({credential: {type: "bearer", token: "t"}, capability: "miniapps.publish"}) + expect(response.allowed).toBe(true) + expect(response.capabilities).toContain("miniapps.publish") + }) + + test("authorize accepts null workspace and membership when Core has none to report", async () => { + const {client} = clientFor(() => + json({ + allowed: false, + reason: "workspace_not_found", + principal: null, + workspace: null, + membership: null, + capabilities: [], + }), + ) + const response = await client.authorize({credential: {type: "bearer", token: "t"}, workspaceId: "ws_missing"}) + expect(response.allowed).toBe(false) + expect(response.workspace).toBeNull() + expect(response.membership).toBeNull() + expect(response.principal).toBeNull() + }) + + test("authorize returns a denial with its reason", async () => { + const denied: AuthorizeResponse = { + allowed: false, + reason: "not_a_member", + principal: userPrincipal(), + capabilities: [], + } + const {client} = clientFor(() => json(denied)) + const response = await client.authorize({credential: {type: "mentra_user", mentraUserId: "user_1"}}) + expect(response.allowed).toBe(false) + expect(response.reason).toBe("not_a_member") + }) + + test("resolvePrincipal posts the token and maps an invalid_token 401 to null", async () => { + const principal: PrincipalResponse = { + principal: userPrincipal(), + workspaces: [ + {...workspace(), membership: {membershipId: "mem_1", role: "owner"}, capabilities: ["workspace.read"]}, + ], + } + const {client, calls} = clientFor((request) => + JSON.parse(request.body).token === "good" ? json(principal) : json({error: "invalid_token"}, 401), + ) + expect(await client.resolvePrincipal("good")).toEqual(principal) + expect(await client.resolvePrincipal("bad")).toBeNull() + expect(calls[0].url).toBe(`${BASE}/api/internal/workspaces/principal`) + expect(calls[0].method).toBe("POST") + expect(JSON.parse(calls[0].body)).toEqual({token: "good"}) + }) + + test("checkMemberships posts the user and workspaces and returns the map", async () => { + const memberships = {ws_1: {role: "admin", capabilities: ["workspace.read"]}, ws_2: null} + const {client, calls} = clientFor(() => json({memberships})) + expect(await client.checkMemberships("user_1", ["ws_1", "ws_2"])).toEqual(memberships as never) + expect(calls[0].url).toBe(`${BASE}/api/internal/workspaces/memberships/check`) + expect(JSON.parse(calls[0].body)).toEqual({mentraUserId: "user_1", workspaceIds: ["ws_1", "ws_2"]}) + }) + + test("getWorkspace returns the summary and maps 404 to null", async () => { + const {client, calls} = clientFor((request) => + request.url.endsWith("/ws_1") ? json(workspace()) : json({error: "workspace_not_found"}, 404), + ) + expect(await client.getWorkspace("ws_1")).toEqual(workspace()) + expect(await client.getWorkspace("missing")).toBeNull() + expect(calls[0].url).toBe(`${BASE}/api/internal/workspaces/workspaces/ws_1`) + expect(calls[0].method).toBe("GET") + }) + + test("getWorkspace reads only a workspace_not_found 404 as absent: any other 404 is an error, not an answer", async () => { + // A proxy, a wrong base URL or a Core without this API answers 404 too; none of them knows the workspace is gone. + for (const response of [ + () => json({error: "not_found"}, 404), + () => json({}, 404), + () => new Response("Not Found", {status: 404}), + ]) { + const {client} = clientFor(response) + const error = await expectClientError(client.getWorkspace("ws_1"), "bad_request") + expect(error.status).toBe(404) + } + }) + + test("getWorkspace escapes the workspace id in the path", async () => { + const {client, calls} = clientFor(() => json(workspace())) + await client.getWorkspace("a/b?c") + expect(calls[0].url).toBe(`${BASE}/api/internal/workspaces/workspaces/a%2Fb%3Fc`) + }) + + test("mintServiceCredential posts the request and returns the credential once", async () => { + const {client, calls} = clientFor(() => json({credentialId: "cred_1", token: "msk_dev_x.y"})) + const input = { + workspaceId: "ws_1", + name: "CI", + packageNames: ["com.example.app"], + issuedBy: {service: "store", actorEmail: "a@example.com"}, + } + expect(await client.mintServiceCredential(input)).toEqual({credentialId: "cred_1", token: "msk_dev_x.y"}) + expect(calls[0].url).toBe(`${BASE}/api/internal/workspaces/credentials`) + expect(JSON.parse(calls[0].body)).toEqual(input) + }) + + test("resolveEmail posts the email, signed like every other call, and maps user_not_found to null", async () => { + const {client, calls} = clientFor((request) => + JSON.parse(request.body).email === "a@example.com" + ? json({mentraUserId: "user_1"}) + : json({error: "user_not_found"}, 404), + ) + expect(await client.resolveEmail("a@example.com")).toBe("user_1") + expect(await client.resolveEmail("nobody@example.com")).toBeNull() + expect(calls[0].url).toBe(`${BASE}/api/internal/workspaces/users/resolve-email`) + expect(calls[0].method).toBe("POST") + expect(calls[0].headers.get(SERVICE_HEADERS.service)).toBe("store") + expect( + verifyServiceRequest({ + secrets: [SECRET], + method: "POST", + pathWithQuery: "/api/internal/workspaces/users/resolve-email", + body: calls[0].body, + timestampMs: Number(calls[0].headers.get(SERVICE_HEADERS.timestamp)), + signature: calls[0].headers.get(SERVICE_HEADERS.signature)!, + nowMs: Date.now(), + }), + ).toBe(true) + }) + + test("resolveEmail reads only a user_not_found 404 as nobody, and refuses an answer without a user id", async () => { + for (const response of [() => json({error: "not_found"}, 404), () => new Response("Not Found", {status: 404})]) { + const {client} = clientFor(response) + expect((await expectClientError(client.resolveEmail("a@example.com"), "bad_request")).status).toBe(404) + } + for (const body of [{}, {mentraUserId: ""}, {mentraUserId: 7}, ["user_1"]]) { + const {client} = clientFor(() => json(body)) + await expectClientError(client.resolveEmail("a@example.com"), "bad_response") + } + }) + + test("listChanges asks for the page after a cursor, signed over the exact query", async () => { + const page = {events: [changeEvent(8), changeEvent(9)], next: "9"} + const {client, calls} = clientFor(() => json(page)) + + expect(await client.listChanges({after: "7", limit: 2})).toEqual(page) + + expect(calls).toHaveLength(1) + expect(calls[0]!.method).toBe("GET") + expect(calls[0]!.url).toBe(`${BASE}/api/internal/workspaces/changes?after=7&limit=2`) + const url = new URL(calls[0]!.url) + expect( + verifyServiceRequest({ + secrets: [SECRET], + method: "GET", + pathWithQuery: `${url.pathname}${url.search}`, + body: "", + timestampMs: Number(calls[0]!.headers.get(SERVICE_HEADERS.timestamp)), + signature: calls[0]!.headers.get(SERVICE_HEADERS.signature) ?? "", + nowMs: Date.now(), + }), + ).toBe(true) + }) + + test("listChanges sends only what it is given: no cursor starts from the beginning", async () => { + const empty = {events: [], next: null} + const {client, calls} = clientFor(() => json(empty)) + + expect(await client.listChanges({})).toEqual(empty) + expect(await client.listChanges({after: null})).toEqual(empty) + expect(await client.listChanges({after: "0"})).toEqual(empty) + expect(await client.listChanges({limit: 500})).toEqual(empty) + + expect(calls.map(call => call.url.slice(BASE.length))).toEqual([ + "/api/internal/workspaces/changes", + "/api/internal/workspaces/changes", + "/api/internal/workspaces/changes?after=0", + "/api/internal/workspaces/changes?limit=500", + ]) + }) + + test("listChanges returns an event as Core sent it, tombstones with no workspace and null snapshots included", async () => { + const tombstone = changeEvent(10, { + workspaceId: null, + action: "user.deleted", + target: {mentraUserId: "mu_gone"}, + before: null, + after: null, + }) + const unknownAction = changeEvent(11, {action: "something.new", target: null}) + const {client} = clientFor(() => json({events: [tombstone, unknownAction], next: null})) + + expect(await client.listChanges({after: "9"})).toEqual({events: [tombstone, unknownAction], next: null}) + }) +}) + +describe("response shape", () => { + const mint = { + workspaceId: "ws_1", + name: "CI", + packageNames: [], + issuedBy: {service: "store", actorEmail: "a@example.com"}, + } + + test("rejects an authorize response without its decision or capabilities", async () => { + const {allowed: _allowed, ...withoutDecision} = allowed() + const {capabilities: _capabilities, ...withoutCapabilities} = allowed() + for (const body of [withoutDecision, withoutCapabilities, [allowed()]]) { + const {client} = clientFor(() => json(body)) + await expectClientError( + client.authorize({credential: {type: "mentra_user", mentraUserId: "user_1"}}), + "bad_response", + ) + } + }) + + test("rejects an authorize response whose nested principal or workspace is malformed", async () => { + const badBodies = [ + {...allowed(), principal: "user_1"}, + {...allowed(), principal: {...userPrincipal(), kind: "robot"}}, + {...allowed(), workspace: ["ws_1"]}, + {...allowed(), workspace: {...workspace(), workspaceId: 1}}, + ] + for (const body of badBodies) { + const {client} = clientFor(() => json(body)) + await expectClientError( + client.authorize({credential: {type: "mentra_user", mentraUserId: "user_1"}}), + "bad_response", + ) + } + }) + + test("rejects a principal response with a malformed principal or workspace", async () => { + const membership = {membershipId: "mem_1", role: "member"} as const + const {workspaceId: _workspaceId, ...withoutId} = workspace() + const badBodies = [ + {workspaces: []}, + {principal: {...userPrincipal(), kind: undefined}, workspaces: []}, + {principal: userPrincipal(), workspaces: [{...withoutId, membership, capabilities: []}]}, + {principal: userPrincipal(), workspaces: ["ws_1"]}, + ] + for (const body of badBodies) { + const {client} = clientFor(() => json(body)) + await expectClientError(client.resolvePrincipal("t"), "bad_response") + } + }) + + test("accepts a credential principal", async () => { + const principal: PrincipalResponse = { + principal: { + kind: "credential", + credentialId: "cred_1", + credentialKind: "workspace", + workspaceId: "ws_1", + scopes: [], + packageNames: [], + label: "CI", + }, + workspaces: [], + } + const {client} = clientFor(() => json(principal)) + expect(await client.resolvePrincipal("t")).toEqual(principal) + }) + + test("rejects a workspace summary without a workspace id", async () => { + const {workspaceId: _workspaceId, ...withoutId} = workspace() + for (const body of [withoutId, [workspace()], "ws_1"]) { + const {client} = clientFor(() => json(body)) + await expectClientError(client.getWorkspace("ws_1"), "bad_response") + } + }) + + test("fails closed when a membership check or minted credential has the wrong shape", async () => { + const memberships = clientFor(() => json({memberships: ["ws_1"]})) + await expectClientError(memberships.client.checkMemberships("user_1", ["ws_1"]), "bad_response") + const bareMap = clientFor(() => json({ws_1: null})) + await expectClientError(bareMap.client.checkMemberships("user_1", ["ws_1"]), "bad_response") + const credential = clientFor(() => json({credentialId: "cred_1"})) + await expectClientError(credential.client.mintServiceCredential(mint), "bad_response") + const notAnObject = clientFor(() => json([{credentialId: "cred_1", token: "msk_dev_x.y"}])) + await expectClientError(notAnObject.client.mintServiceCredential(mint), "bad_response") + }) + + test("fails closed when a change page has the wrong shape", async () => { + const good = changeEvent(1) + const bad: unknown[] = [ + [good], + {next: null}, + {events: good, next: null}, + {events: [good]}, + {events: [good], next: 1}, + {events: [good], next: ""}, + {events: [good], next: "not-a-cursor"}, + {events: ["event"], next: null}, + {events: [{...good, eventId: undefined}], next: null}, + {events: [{...good, seq: "1"}], next: null}, + {events: [{...good, seq: 1.5}], next: null}, + {events: [{...good, seq: -1}], next: null}, + {events: [{...good, action: undefined}], next: null}, + {events: [{...good, workspaceId: 7}], next: null}, + {events: [{...good, occurredAt: undefined}], next: null}, + {events: [{...good, target: "x"}], next: null}, + {events: [{...good, before: []}], next: null}, + {events: [{...good, after: 7}], next: null}, + ] + for (const body of bad) { + const {client} = clientFor(() => json(body)) + await expectClientError(client.listChanges({}), "bad_response") + } + }) + + test("fails closed when a change page is out of order or its cursor does not point at its last event", async () => { + const outOfOrder = clientFor(() => json({events: [changeEvent(5), changeEvent(4)], next: "4"})) + await expectClientError(outOfOrder.client.listChanges({}), "bad_response") + const repeated = clientFor(() => json({events: [changeEvent(5), changeEvent(5)], next: "5"})) + await expectClientError(repeated.client.listChanges({}), "bad_response") + const wrongCursor = clientFor(() => json({events: [changeEvent(5), changeEvent(6)], next: "9"})) + await expectClientError(wrongCursor.client.listChanges({}), "bad_response") + const cursorWithoutEvents = clientFor(() => json({events: [], next: "9"})) + await expectClientError(cursorWithoutEvents.client.listChanges({}), "bad_response") + }) +}) + +describe("failures", () => { + test("times out after timeoutMs with core_unavailable", async () => { + const {client} = clientFor( + (_request, init) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason ?? new Error("aborted"))) + }), + {timeoutMs: 25}, + ) + const started = Date.now() + await expectClientError(client.getWorkspace("ws_1"), "core_unavailable") + expect(Date.now() - started).toBeLessThan(1_000) + }) + + test("maps a network failure to core_unavailable", async () => { + const {client} = clientFor(() => { + throw new TypeError("fetch failed") + }) + await expectClientError(client.getWorkspace("ws_1"), "core_unavailable") + }) + + test("maps a 5xx response to core_unavailable", async () => { + const {client} = clientFor(() => json({error: "boom"}, 503)) + const error = await expectClientError(client.getWorkspace("ws_1"), "core_unavailable") + expect(error.status).toBe(503) + }) + + test("maps a service_unauthorized 401 to service_unauthorized on every operation", async () => { + const {client} = clientFor(() => json({error: SERVICE_UNAUTHORIZED_ERROR}, 401)) + const error = await expectClientError(client.getWorkspace("ws_1"), "service_unauthorized") + expect(error.status).toBe(401) + await expectClientError(client.getWorkspace("ws_1"), "service_unauthorized") + await expectClientError(client.checkMemberships("user_1", []), "service_unauthorized") + await expectClientError(client.authorize({credential: {type: "bearer", token: "t"}}), "service_unauthorized") + await expectClientError(client.resolveEmail("a@example.com"), "service_unauthorized") + }) + + test("resolvePrincipal throws instead of returning null for a service_unauthorized or unrecognised 401", async () => { + const service = clientFor(() => json({error: SERVICE_UNAUTHORIZED_ERROR}, 401)) + const serviceError = await expectClientError(service.client.resolvePrincipal("t"), "service_unauthorized") + expect(serviceError.status).toBe(401) + const other = clientFor(() => json({error: "something_else"}, 401)) + await expectClientError(other.client.resolvePrincipal("t"), "unauthorized") + const bare = clientFor(() => new Response("", {status: 401})) + await expectClientError(bare.client.resolvePrincipal("t"), "unauthorized") + const invalid = clientFor(() => json({error: INVALID_TOKEN_ERROR}, 401)) + expect(await invalid.client.resolvePrincipal("t")).toBeNull() + }) + + test("an invalid_token 401 on another operation is an unauthorized error, not a null", async () => { + const {client} = clientFor(() => json({error: INVALID_TOKEN_ERROR}, 401)) + await expectClientError(client.getWorkspace("ws_1"), "unauthorized") + }) + + test("maps other 401s to unauthorized and 403 to forbidden", async () => { + const unauthorized = clientFor(() => json({error: "bad_signature"}, 401)) + const error = await expectClientError(unauthorized.client.getWorkspace("ws_1"), "unauthorized") + expect(error.status).toBe(401) + const forbidden = clientFor(() => json({error: "forbidden"}, 403)) + await expectClientError( + forbidden.client.mintServiceCredential({ + workspaceId: "ws_1", + name: "CI", + packageNames: [], + issuedBy: {service: "fleet", actorEmail: "a@example.com"}, + }), + "forbidden", + ) + }) + + test("maps other client errors to bad_request and carries the error text", async () => { + const {client} = clientFor(() => json({error: "too_many_workspaces"}, 400)) + const error = await expectClientError(client.checkMemberships("user_1", []), "bad_request") + expect(error.status).toBe(400) + expect(error.message).toContain("too_many_workspaces") + }) + + test("maps a non-JSON or malformed body to bad_response", async () => { + const notJson = clientFor(() => new Response("gateway", {status: 200})) + await expectClientError(notJson.client.getWorkspace("ws_1"), "bad_response") + const wrongShape = clientFor(() => json({name: "no id"})) + await expectClientError(wrongShape.client.getWorkspace("ws_1"), "bad_response") + }) +}) + +describe("deletion holds", () => { + const AS_OF = new Date("2026-10-14T12:34:56.789Z") + const holds = (...entries: WorkspaceDeletionHold[]): DeletionHoldsResponse => ({workspaceId: "ws 1", holds: entries, ignored: false}) + const verifies = (call: Recorded) => { + const url = new URL(call.url) + const timestampMs = Number(call.headers.get(SERVICE_HEADERS.timestamp)) + return verifyServiceRequest({ + secrets: [SECRET], + method: call.method, + pathWithQuery: `${url.pathname}${url.search}`, + body: call.body, + timestampMs, + signature: call.headers.get(SERVICE_HEADERS.signature) ?? "", + nowMs: timestampMs, + }) + } + + test("setDeletionHold PUTs the reason, count and asOf to this service's own hold, signed over the exact path and body", async () => { + const answer = holds({service: "store", reason: "owns_miniapps", count: 3}) + const {client, calls} = clientFor(() => json(answer)) + + expect(await client.setDeletionHold("ws 1", {reason: "owns_miniapps", count: 3, asOf: AS_OF})).toEqual(answer) + + expect(calls).toHaveLength(1) + expect(calls[0].method).toBe("PUT") + // The service in the path is always the one the client signs as: a service sets only its own hold. + expect(calls[0].url).toBe(`${BASE}/api/internal/workspaces/workspaces/ws%201/deletion-holds/store`) + expect(calls[0].headers.get("content-type")).toBe("application/json") + expect(JSON.parse(calls[0].body)).toEqual({reason: "owns_miniapps", count: 3, asOf: "2026-10-14T12:34:56.789Z"}) + expect(verifies(calls[0])).toBe(true) + }) + + test("setDeletionHold sends no count when it is given none", async () => { + const {client, calls} = clientFor(() => json(holds({service: "store", reason: "owns_miniapps"}))) + await client.setDeletionHold("ws_1", {reason: "owns_miniapps", asOf: AS_OF}) + expect(JSON.parse(calls[0].body)).toEqual({reason: "owns_miniapps", asOf: "2026-10-14T12:34:56.789Z"}) + }) + + test("clearDeletionHold DELETEs this service's hold with its asOf, and returns the holds left", async () => { + const answer = holds({service: "fleet", reason: "manages_devices"}) + const {client, calls} = clientFor(() => json(answer)) + + expect(await client.clearDeletionHold("ws 1", {asOf: AS_OF})).toEqual(answer) + + expect(calls[0].method).toBe("DELETE") + expect(calls[0].url).toBe(`${BASE}/api/internal/workspaces/workspaces/ws%201/deletion-holds/store`) + expect(calls[0].headers.get("content-type")).toBe("application/json") + expect(JSON.parse(calls[0].body)).toEqual({asOf: "2026-10-14T12:34:56.789Z"}) + expect(verifies(calls[0])).toBe(true) + }) + + test("an update Core ignored as stale resolves with the holds Core keeps and ignored: true", async () => { + const answer: DeletionHoldsResponse = {workspaceId: "ws 1", holds: [{service: "store", reason: "owns_miniapps", count: 2}], ignored: true} + const {client} = clientFor(() => json(answer)) + expect(await client.clearDeletionHold("ws 1", {asOf: AS_OF})).toEqual(answer) + expect(await client.setDeletionHold("ws 1", {reason: "owns_miniapps", count: 5, asOf: AS_OF})).toEqual(answer) + }) + + test("an asOf that is not a valid date is refused before anything is sent", async () => { + const {client, calls} = clientFor(() => json(holds())) + const invalid = new Date(Number.NaN) + await expect(client.setDeletionHold("ws_1", {reason: "owns_miniapps", asOf: invalid})).rejects.toThrow(RangeError) + await expect(client.clearDeletionHold("ws_1", {asOf: invalid})).rejects.toThrow(RangeError) + expect(calls).toHaveLength(0) + }) + + test("a refusal is an error with Core's status: an unknown workspace, a deleted one, another service's hold", async () => { + const unknown = clientFor(() => json({error: "workspace_not_found"}, 404)) + expect((await expectClientError(unknown.client.setDeletionHold("ws_1", {reason: "owns_miniapps", asOf: AS_OF}), "bad_request")).status).toBe(404) + expect((await expectClientError(unknown.client.clearDeletionHold("ws_1", {asOf: AS_OF}), "bad_request")).status).toBe(404) + const deleted = clientFor(() => json({error: "workspace_deleted"}, 410)) + expect((await expectClientError(deleted.client.setDeletionHold("ws_1", {reason: "owns_miniapps", asOf: AS_OF}), "bad_request")).status).toBe(410) + const forbidden = clientFor(() => json({error: "forbidden"}, 403)) + await expectClientError(forbidden.client.setDeletionHold("ws_1", {reason: "owns_miniapps", asOf: AS_OF}), "forbidden") + }) + + test("fails closed on an answer that does not have the holds shape", async () => { + for (const body of [ + {}, + {workspaceId: "ws_1"}, + {workspaceId: "ws_1", holds: {}}, + {workspaceId: 5, holds: []}, + {workspaceId: "ws_1", holds: [{service: "store"}]}, + {workspaceId: "ws_1", holds: [{service: "store", reason: "owns_miniapps", count: "3"}]}, + {workspaceId: "ws_1", holds: [{service: "store", reason: "owns_miniapps", count: 0}]}, + // A Core that predates asOf says nothing about it, and would have applied a late call. + {workspaceId: "ws_1", holds: []}, + {workspaceId: "ws_1", holds: [], ignored: "true"}, + {workspaceId: "ws_1", holds: [], ignored: null}, + ]) { + const {client} = clientFor(() => json(body)) + await expectClientError(client.setDeletionHold("ws_1", {reason: "owns_miniapps", asOf: AS_OF}), "bad_response") + await expectClientError(client.clearDeletionHold("ws_1", {asOf: AS_OF}), "bad_response") + } + }) +}) + +describe("licenses", () => { + const LICENSE_ID = "01JZWY3V8N0F2E9GQ4T6KXH5RD" + const write = (overrides: Partial = {}): LicenseWrite => ({ + licenseId: LICENSE_ID, + revision: 3, + owner: {type: "workspace", workspaceId: "ws_1"}, + product: "mentra.call.unlimited", + features: [{key: "call.unlimited", packages: ["com.mentra.call"]}], + quantity: 5, + validFrom: "2026-10-01T00:00:00.000Z", + paidThrough: "2026-11-04T00:00:00.000Z", + ...overrides, + }) + const view = (overrides: Partial = {}): LicenseView => { + const {licenseId, ...rest} = write() + return {licenseId, ...rest, seatsUsed: 2, endedAt: null, ...overrides} + } + const verifies = (call: Recorded) => { + const url = new URL(call.url) + const timestampMs = Number(call.headers.get(SERVICE_HEADERS.timestamp)) + return verifyServiceRequest({ + secrets: [SECRET], + method: call.method, + pathWithQuery: `${url.pathname}${url.search}`, + body: call.body, + timestampMs, + signature: call.headers.get(SERVICE_HEADERS.signature) ?? "", + nowMs: timestampMs, + }) + } + + test("putLicense PUTs the whole write to the license's own path, signed, and returns whether Core applied it", async () => { + const {client, calls} = clientFor(() => json({applied: true, revision: 3})) + + expect(await client.putLicense(write())).toEqual({applied: true, revision: 3}) + + expect(calls).toHaveLength(1) + expect(calls[0].method).toBe("PUT") + expect(calls[0].url).toBe(`${BASE}/api/internal/licenses/${LICENSE_ID}`) + expect(calls[0].headers.get("content-type")).toBe("application/json") + expect(JSON.parse(calls[0].body)).toEqual(write()) + expect(verifies(calls[0])).toBe(true) + }) + + test("putLicense resolves a repeat Core already has as not applied", async () => { + const {client} = clientFor(() => json({applied: false, revision: 3})) + expect(await client.putLicense(write())).toEqual({applied: false, revision: 3}) + }) + + test("putLicense throws the client's error with Core's status and code: stale_revision, owner_not_found, unavailable", async () => { + const stale = clientFor(() => json({error: "stale_revision", error_description: "Core has revision 4", revision: 4}, 409)) + expect((await expectClientError(stale.client.putLicense(write()), "stale_revision")).status).toBe(409) + + const gone = clientFor(() => json({error: "owner_not_found", error_description: "the workspace is deleted"}, 404)) + expect((await expectClientError(gone.client.putLicense(write()), "owner_not_found")).status).toBe(404) + + const down = clientFor(() => json({error: "server_error"}, 503)) + expect((await expectClientError(down.client.putLicense(write()), "core_unavailable")).status).toBe(503) + + // Any other 404 or 409 says nothing about the owner or the revision. + const proxy = clientFor(() => new Response("not found", {status: 404})) + expect((await expectClientError(proxy.client.putLicense(write()), "bad_request")).status).toBe(404) + const conflict = clientFor(() => json({error: "membership_changed"}, 409)) + expect((await expectClientError(conflict.client.putLicense(write()), "bad_request")).status).toBe(409) + const invalid = clientFor(() => json({error: "invalid_request"}, 400)) + expect((await expectClientError(invalid.client.putLicense(write()), "bad_request")).status).toBe(400) + }) + + test("putLicense fails closed on an answer without applied and a whole revision", async () => { + for (const body of [{}, {applied: true}, {revision: 3}, {applied: "true", revision: 3}, {applied: true, revision: 1.5}]) { + const {client} = clientFor(() => json(body)) + await expectClientError(client.putLicense(write()), "bad_response") + } + }) + + test("listLicenses asks for one workspace's licenses, signed over the exact query", async () => { + const {client, calls} = clientFor(() => json({licenses: [view()]})) + + expect(await client.listLicenses("ws 1")).toEqual({licenses: [view()]}) + expect(calls[0].method).toBe("GET") + expect(calls[0].url).toBe(`${BASE}/api/internal/licenses?ownerType=workspace&ownerId=ws+1`) + expect(calls[0].body).toBe("") + expect(verifies(calls[0])).toBe(true) + }) + + test("listLicenses fails closed on an answer that is not a list of licenses", async () => { + for (const body of [ + {}, + {licenses: {}}, + {licenses: [{}]}, + {licenses: [{...view(), licenseId: 5}]}, + {licenses: [{...view(), seatsUsed: "2"}]}, + {licenses: [{...view(), owner: null}]}, + {licenses: [{...view(), revision: undefined}]}, + ]) { + const {client} = clientFor(() => json(body)) + await expectClientError(client.listLicenses("ws_1"), "bad_response") + } + }) +}) + +describe("the miniapp registry", () => { + const NOTES_URL = "https://notes.example.com/" + const verifies = (call: Recorded) => { + const url = new URL(call.url) + const timestampMs = Number(call.headers.get(SERVICE_HEADERS.timestamp)) + return verifyServiceRequest({ + secrets: [SECRET], + method: call.method, + pathWithQuery: `${url.pathname}${url.search}`, + body: call.body, + timestampMs, + signature: call.headers.get(SERVICE_HEADERS.signature) ?? "", + nowMs: timestampMs, + }) + } + const result = (overrides: Partial = {}): RegistryCheckResult => ({ + url: NOTES_URL, + status: "accepted", + packageName: "com.example.notes", + name: "Notes", + iconUrl: `${NOTES_URL}icon.png`, + private: false, + checkedAt: "2026-10-24T08:00:00.000Z", + ...overrides, + }) + const detail = (overrides: Partial = {}): RegistryEntryDetail => ({ + url: NOTES_URL, + packageName: "com.example.notes", + registrableDomain: "example.com", + name: "Notes", + version: "1.0.0", + ageRating: "4+", + iconUrl: `${NOTES_URL}icon.png`, + verification: "verified", + private: false, + status: "active", + firstRegisteredAt: "2026-10-24T08:00:00.000Z", + lastVerifiedAt: "2026-10-24T08:00:00.000Z", + manifest: { + packageName: "com.example.notes", + version: "1.0.0", + name: "Notes", + entry: {ui: "ui/index.html"}, + bundle: {url: "notes.zip", sha256: "ab".repeat(32)}, + }, + ...overrides, + }) + const check = {urls: [NOTES_URL, "https://tools.acme.com/"], workspaceId: "ws_1", mentraUserId: "mu_1"} + + test("checkRegistry POSTs the URLs, workspace and person, signed, and returns one result per URL", async () => { + const results = [result(), result({url: "https://tools.acme.com/", status: "unreachable", packageName: null, name: null, iconUrl: null})] + const {client, calls} = clientFor(() => json({results})) + + expect(await client.checkRegistry(check)).toEqual(results) + expect(calls[0].method).toBe("POST") + expect(calls[0].url).toBe(`${BASE}/api/internal/registry/check`) + expect(JSON.parse(calls[0].body)).toEqual(check) + expect(verifies(calls[0])).toBe(true) + }) + + test("checkRegistry fails closed on results that aren't the URLs asked about, in order, each of its shape", async () => { + for (const results of [ + [result()], + [result({url: "https://tools.acme.com/"}), result({url: NOTES_URL})], + [result(), result({url: "https://tools.acme.com/", status: "maybe" as never})], + [result(), result({url: "https://tools.acme.com/", private: null as never})], + [result(), result({url: "https://tools.acme.com/", name: 5 as never})], + [result(), result({url: "https://tools.acme.com/", checkedAt: "soon"})], + ]) { + const {client} = clientFor(() => json({results})) + await expectClientError(client.checkRegistry(check), "bad_response") + } + const {client} = clientFor(() => json({})) + await expectClientError(client.checkRegistry(check), "bad_response") + }) + + test("checkRegistry waits for Core's 10-second check deadline, past the client's usual timeout", async () => { + const results = [result(), result({url: "https://tools.acme.com/"})] + const slow = (delayMs: number) => (_request: Recorded, init: RequestInit) => + new Promise((resolve, reject) => { + const timer = setTimeout(() => resolve(json({results})), delayMs) + init.signal?.addEventListener("abort", () => { + clearTimeout(timer) + reject(init.signal?.reason) + }) + }) + // A client whose timeout is 50 ms still gets a check that takes longer, while its other calls time out. + const {client} = clientFor(slow(200), {timeoutMs: 50}) + expect(await client.checkRegistry(check)).toEqual(results) + await expectClientError(client.lookupRegistry({workspaceId: "ws_1", packageNames: ["com.example.notes"]}), "core_unavailable") + }) + + test("checkRegistry reads not_a_member as forbidden", async () => { + const {client} = clientFor(() => json({error: "not_a_member"}, 403)) + expect((await expectClientError(client.checkRegistry(check), "forbidden")).message).toContain("not_a_member") + }) + + test("lookupRegistry returns every package asked about, an own entry even for __proto__", async () => { + const entries = {"com.example.notes": {name: "Notes", iconUrl: null, private: false, archived: false}, ["__proto__"]: null} + const {client, calls} = clientFor(() => new Response(JSON.stringify({entries}), {status: 200})) + + const answer = await client.lookupRegistry({workspaceId: "ws_1", packageNames: ["com.example.notes", "__proto__"]}) + expect(answer["com.example.notes"]).toEqual(entries["com.example.notes"]) + expect(Object.prototype.hasOwnProperty.call(answer, "__proto__")).toBe(true) + expect(Object.getPrototypeOf(answer)).toBe(Object.prototype) + expect(calls[0].url).toBe(`${BASE}/api/internal/registry/lookup`) + expect(JSON.parse(calls[0].body)).toEqual({workspaceId: "ws_1", packageNames: ["com.example.notes", "__proto__"]}) + expect(verifies(calls[0])).toBe(true) + }) + + test("lookupRegistry fails closed on an answer that leaves a package out or has the wrong shape", async () => { + for (const entries of [ + {}, + {"com.example.notes": {name: "Notes", iconUrl: null, private: false}}, + {"com.example.notes": {name: "Notes", iconUrl: null, private: "no", archived: false}}, + {"com.example.notes": "Notes"}, + ]) { + const {client} = clientFor(() => json({entries})) + await expectClientError(client.lookupRegistry({workspaceId: "ws_1", packageNames: ["com.example.notes"]}), "bad_response") + } + }) + + test("getRegistryEntry asks for one URL, signed over the exact query, and reads only not_found as none", async () => { + const {client, calls} = clientFor(() => json({entry: detail()})) + expect(await client.getRegistryEntry(NOTES_URL)).toEqual(detail()) + expect(calls[0].method).toBe("GET") + expect(calls[0].url).toBe(`${BASE}/api/internal/registry/entries?url=https%3A%2F%2Fnotes.example.com%2F`) + expect(verifies(calls[0])).toBe(true) + + const none = clientFor(() => json({error: "not_found"}, 404)) + expect(await none.client.getRegistryEntry(NOTES_URL)).toBeNull() + const proxy = clientFor(() => new Response("not found", {status: 404})) + await expectClientError(proxy.client.getRegistryEntry(NOTES_URL), "bad_request") + }) + + test("getRegistryEntry accepts an entry with only its URL and package, and fails closed on a malformed one", async () => { + const hidden = detail({name: null, version: null, ageRating: null, iconUrl: null, private: true, manifest: null}) + expect(await clientFor(() => json({entry: hidden})).client.getRegistryEntry(NOTES_URL)).toEqual(hidden) + for (const entry of [ + undefined, + {...detail(), packageName: ""}, + {...detail(), ageRating: "21+"}, + {...detail(), verification: "trusted"}, + {...detail(), status: "deleted"}, + {...detail(), lastVerifiedAt: "never"}, + {...detail(), manifest: {name: "Notes"}}, + ]) { + const {client} = clientFor(() => json({entry})) + await expectClientError(client.getRegistryEntry(NOTES_URL), "bad_response") + } + }) + + test("archiveRegistry POSTs the rule, reason and actor, and returns what Core did", async () => { + const body = {rule: {kind: "domain" as const, value: "Example.com"}, reason: "spam", actorEmail: "staff@example.com"} + const {client, calls} = clientFor(() => json({rule: {kind: "domain", value: "example.com"}, created: true, entriesArchived: 3})) + expect(await client.archiveRegistry(body)).toEqual({rule: {kind: "domain", value: "example.com"}, created: true, entriesArchived: 3}) + expect(calls[0].url).toBe(`${BASE}/api/internal/registry/archive`) + expect(JSON.parse(calls[0].body)).toEqual(body) + expect(verifies(calls[0])).toBe(true) + + for (const answer of [{}, {rule: {kind: "everything", value: "x"}, created: true, entriesArchived: 0}, {rule: body.rule, created: true, entriesArchived: -1}]) { + const {client: bad} = clientFor(() => json(answer)) + await expectClientError(bad.archiveRegistry(body), "bad_response") + } + }) +}) + +describe("construction", () => { + test("throws on an empty or whitespace-only secret instead of signing forgeable requests", () => { + for (const secret of ["", " "]) { + expect(() => + createCoreWorkspaceClient({ + baseUrl: BASE, + service: "store", + secret, + fetch: mockFetch(() => json({})).fetch, + }), + ).toThrow() + } + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/client.ts b/cloud-v2/packages/workspace-contract/src/client.ts new file mode 100644 index 0000000000000000000000000000000000000000..f88fc086cf3f1bb66d6bd7da58f7bbfa2d2f81e4 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/client.ts @@ -0,0 +1,717 @@ +/** + * Signed client for Core's internal service API (`/api/internal/workspaces/*`, the Store's + * `/api/internal/licenses/*`, and the miniapp registry's `/api/internal/registry/*`), for a service that shares a + * secret with its Core (the Store, Fleet). Every request is signed over its timestamp, method, path and body hash + * (`service-signature.ts`); no request names an organization. + */ +import {WORKSPACE_ROLES} from "./capabilities" +import {isWorkspaceDeletionHold} from "./deletion-holds" +import {OWNER_NOT_FOUND_ERROR, STALE_REVISION_ERROR} from "./licenses" +import type {LicensesResponse, LicenseView, LicenseWrite, LicenseWriteResponse} from "./licenses" +import {SERVICE_HEADERS, signServiceRequest} from "./service-signature" +import { + INVALID_TOKEN_ERROR, + REGISTRY_CHECK_STATUSES, + REGISTRY_ENTRY_NOT_FOUND_ERROR, + SERVICE_UNAUTHORIZED_ERROR, + USER_NOT_FOUND_ERROR, + WORKSPACE_NOT_FOUND_ERROR, +} from "./types" +import type { + AuthorizeRequest, + AuthorizeResponse, + DeletionHoldsResponse, + DeletionHoldUpdate, + MembershipCheckEntry, + MembershipInterval, + MembershipIntervalsResponse, + PrincipalResponse, + RegistryArchiveRequest, + RegistryArchiveResponse, + RegistryArchiveRuleKind, + RegistryCheckRequest, + RegistryCheckResult, + RegistryEntryDetail, + RegistryLookupEntry, + RegistryLookupRequest, + WorkspaceChangeEvent, + WorkspaceChangesResponse, + WorkspaceMembersResponse, + WorkspaceSummary, +} from "./types" + +const API_PREFIX = "/api/internal/workspaces" +const LICENSES_PREFIX = "/api/internal/licenses" +const REGISTRY_PREFIX = "/api/internal/registry" +const REGISTRY_RULE_KINDS: readonly RegistryArchiveRuleKind[] = ["url", "package", "domain", "account"] +const AGE_RATINGS = ["4+", "9+", "13+", "16+", "18+"] +/** A feed cursor: a `seq` as a decimal string, with no sign, leading zero or fraction. */ +const CURSOR = /^[1-9]\d*$/ +const DEFAULT_TIMEOUT_MS = 5_000 +/** + * The least time a registry check gets: Core answers it within 10 seconds (`REGISTRY_CHECK_DEADLINE_MS` in Core), + * so the client waits that long and a little more for the answer to arrive, whatever its own timeout. + */ +export const REGISTRY_CHECK_TIMEOUT_MS = 15_000 + +export type CoreWorkspaceClientErrorCode = + /** Core could not be reached, timed out, or answered with a 5xx. */ + | "core_unavailable" + /** Core rejected this service's signature or secret (HTTP 401 `service_unauthorized`). */ + | "service_unauthorized" + /** Core answered 401 for another reason. */ + | "unauthorized" + /** This service is not allowed to call the endpoint (HTTP 403). */ + | "forbidden" + /** A license write older than the one Core has (HTTP 409 `stale_revision`): Core has the newer one. */ + | "stale_revision" + /** A license write for an owner that is deleted or never existed (HTTP 404 `owner_not_found`): retrying cannot help. */ + | "owner_not_found" + /** Core rejected the request itself (other 4xx). */ + | "bad_request" + /** The response was not valid JSON or did not have the documented shape. */ + | "bad_response" + +export class CoreWorkspaceClientError extends Error { + readonly code: CoreWorkspaceClientErrorCode + readonly status: number | undefined + + constructor(code: CoreWorkspaceClientErrorCode, message: string, status?: number) { + super(message) + this.name = "CoreWorkspaceClientError" + this.code = code + this.status = status + } +} + +export interface CoreWorkspaceClient { + authorize(req: AuthorizeRequest): Promise + /** Null only when Core says the token is invalid (HTTP 401 `invalid_token`); other 401s throw. */ + resolvePrincipal(bearerToken: string): Promise + checkMemberships(mentraUserId: string, workspaceIds: string[]): Promise> + /** Null only when Core says the workspace does not exist (HTTP 404 `workspace_not_found`); any other 404 throws. */ + getWorkspace(workspaceId: string): Promise + /** + * One page of the change feed, oldest first. `after` is the `seq` of the last event already + * processed, as a decimal string (omitted or null starts from the beginning); `limit` is at most 500 + * (Core's default when omitted is 100). `next` is the cursor for the following page, or null when + * the page was not full. Store a cursor only after the events up to it are processed. + */ + listChanges(input: {after?: string | null; limit?: number}): Promise + /** + * One page of membership interval history (Fleet only). Every interval overlapping the lookback window is + * returned, including an open one that started before it. `after` is the previous page's opaque `next` + * (omitted or null starts from the beginning); `limit` is at most 500. The response's `feedSeq` is the change-feed + * position the read is consistent with, so a consumer then applies feed events after it. + */ + listMembershipIntervals(input: {after?: string | null; limit?: number}): Promise + /** Who is in a workspace now, with names (Fleet only). An unknown or deleted workspace is `workspace_not_found`. */ + listWorkspaceMembers(workspaceId: string): Promise + mintServiceCredential(input: { + workspaceId: string + name: string + packageNames: string[] + issuedBy: {service: string; actorEmail: string} + }): Promise<{credentialId: string; token: string}> + /** + * The Mentra user id of the account whose verified email this is (Core creates the Mentra user on + * first use). Null only when Core says no account has it verified (HTTP 404 `user_not_found`). + */ + resolveEmail(email: string): Promise + /** + * Hold the workspace from deletion for this service, replacing its previous hold: while any service + * holds a workspace, Core refuses to delete it (409 `workspace_has_holds`). `reason` is a lowercase + * code (`owns_miniapps`); `count`, when given, is a positive whole number of what the reason names. + * `asOf` is when the service computed the hold, taken just before reading what it counts and later + * than the service's previous `asOf` for the workspace: Core ignores the call (`ignored: true`, + * changing nothing) when it has applied a newer one from this service, so a late call never + * overwrites a newer hold. A caller that needs the workspace held must find its own hold in the + * answer's `holds`, which an ignored call does not promise. Setting the hold the service already has + * changes no hold. Resolves to every hold on the workspace afterwards. Core refuses an unknown + * workspace (404), a deleted one (410) and an `asOf` more than five minutes ahead of its clock + * (400). An invalid `asOf` throws a `RangeError` before anything is sent. + */ + setDeletionHold(workspaceId: string, hold: {reason: string; count?: number; asOf: Date}): Promise + /** + * Clear this service's hold, if it has one (clearing nothing changes no hold, on a deleted workspace + * too). `asOf` is as for `setDeletionHold`: Core remembers it after the clear, so a set computed + * before it and applied late is ignored too. Resolves to the holds left on the workspace. Core + * refuses an unknown workspace (404). + */ + clearDeletionHold(workspaceId: string, update: {asOf: Date}): Promise + /** + * Write a license as billing last computed it (the Store only). Core applies it when `revision` is newer + * than the one it has (`applied: true`) and answers a repeat of the revision it has with `applied: + * false`. An older revision throws `stale_revision` (409): Core already has a newer one, so the write + * counts as delivered. A workspace that is deleted or never existed throws `owner_not_found` (404): stop + * sending it. A Core that cannot answer throws `core_unavailable` (5xx, or no answer): send it again. + * Any other refusal is a malformed write (`bad_request`). + */ + putLicense(write: LicenseWrite): Promise + /** One workspace's licenses, ended ones included, each with how many seats are assigned (the Store only). */ + listLicenses(workspaceId: string): Promise + /** + * What the miniapp registry says of each URL an admin is assigning (Fleet only): one result per URL, in order. + * Core registers a URL it doesn't know as the admin's own install would, answering a sign-in challenge with a + * token that names `workspaceId` when the admin is an active member of it (anyone else, such as an Organization + * Admin who isn't one, gets their own ordinary token), and gives up on a URL it hasn't finished within 10 seconds + * (`unknown`), so this call waits at least `REGISTRY_CHECK_TIMEOUT_MS` whatever the client's `timeoutMs`. A + * workspace that isn't active, or a person who isn't a live account, is `forbidden` (`403 not_a_member`). + */ + checkRegistry(input: RegistryCheckRequest): Promise + /** + * Names for a workspace's views (Fleet only): every package asked about, null where the registry has none. A + * private miniapp is named only for a workspace that assigned it. + */ + lookupRegistry(input: RegistryLookupRequest): Promise> + /** + * The registry's entry for a miniapp URL and Core's verified `miniapp.json` (the Store only), or null when the + * registry has none (`404 not_found`). Core shows a private or phone-reported entry's URL and package only. + */ + getRegistryEntry(url: string): Promise + /** + * Archive a URL, a package name, a registrable domain or an account's entries (the Store only), for the staff + * member `actorEmail`. Archiving a rule that exists changes nothing (`created: false`). A rule that can't name any + * entry is `bad_request`. + */ + archiveRegistry(input: RegistryArchiveRequest): Promise +} + +export interface CoreWorkspaceClientOptions { + /** Core's origin, e.g. `https://core.example.com`. Signed paths start at `/api/internal/`. */ + baseUrl: string + /** Sent as `x-mentra-service`; must be a service Core has a secret for. */ + service: string + secret: string + fetch?: typeof fetch + timeoutMs?: number +} + +type Json = Record + +const isRecord = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value) + +export function createCoreWorkspaceClient(opts: CoreWorkspaceClientOptions): CoreWorkspaceClient { + if (opts.secret.trim().length === 0) throw new Error("A Core workspace client needs a non-empty service secret") + const baseUrl = opts.baseUrl.replace(/\/+$/, "") + const doFetch = opts.fetch ?? fetch + const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS + + const badResponse = (path: string, detail: string) => + new CoreWorkspaceClientError("bad_response", `Core ${path} returned an invalid response: ${detail}`) + + function checkRecord(path: string, value: unknown, what: string): Json { + if (!isRecord(value)) throw badResponse(path, `${what} is not an object`) + return value + } + + function checkPrincipal(path: string, value: unknown): Json { + const principal = checkRecord(path, value, "the principal") + if (principal.kind !== "user" && principal.kind !== "credential") { + throw badResponse(path, "the principal is neither a user nor a credential") + } + return principal + } + + /** A record or null: the shape of an event's `target`, `before` and `after`. */ + function checkSnapshot(path: string, value: unknown, what: string): void { + if (value !== null) checkRecord(path, value, what) + } + + function checkChangeEvent(path: string, value: unknown): WorkspaceChangeEvent { + const event = checkRecord(path, value, "an event") + if (typeof event.eventId !== "string" || !event.eventId) throw badResponse(path, "an event has no eventId") + if (typeof event.seq !== "number" || !Number.isSafeInteger(event.seq) || event.seq < 1) { + throw badResponse(path, "an event has no positive integer seq") + } + if (typeof event.action !== "string" || !event.action) throw badResponse(path, "an event has no action") + if (event.workspaceId !== null && typeof event.workspaceId !== "string") { + throw badResponse(path, "an event's workspaceId is neither a string nor null") + } + if (typeof event.occurredAt !== "string") throw badResponse(path, "an event has no occurredAt") + checkSnapshot(path, event.target, "an event's target") + checkSnapshot(path, event.before, "an event's before") + checkSnapshot(path, event.after, "an event's after") + return event as unknown as WorkspaceChangeEvent + } + + const INTERVAL_END_REASONS = ["left", "removed", "workspace_deleted", "account_deleted"] + + /** An interval as Core lists it: a closed one names why it ended, an open one does not. */ + function checkInterval(path: string, value: unknown): MembershipInterval { + const interval = checkRecord(path, value, "an interval") + for (const field of ["membershipId", "workspaceId", "mentraUserId", "role"] as const) { + if (typeof interval[field] !== "string" || !interval[field]) throw badResponse(path, `an interval has no ${field}`) + } + if (typeof interval.start !== "string" || Number.isNaN(Date.parse(interval.start))) { + throw badResponse(path, "an interval's start is not a time") + } + if (interval.end === null) { + if (interval.endReason !== null) throw badResponse(path, "an open interval names an endReason") + } else { + if (typeof interval.end !== "string" || Number.isNaN(Date.parse(interval.end))) { + throw badResponse(path, "an interval's end is neither a time nor null") + } + if (Date.parse(interval.end) < Date.parse(interval.start)) throw badResponse(path, "an interval ends before it starts") + if (typeof interval.endReason !== "string" || !INTERVAL_END_REASONS.includes(interval.endReason)) { + throw badResponse(path, "a closed interval has no known endReason") + } + } + checkRoleIntervals(path, interval) + return interval as unknown as MembershipInterval + } + + /** An interval's role intervals: at least one, in order, inside the interval, only the last one open. */ + function checkRoleIntervals(path: string, interval: Json): void { + const roles = interval.roles + if (!Array.isArray(roles) || roles.length === 0) throw badResponse(path, "an interval has no role intervals") + const start = Date.parse(interval.start as string) + const end = interval.end === null ? null : Date.parse(interval.end as string) + let previousEnd = start + roles.forEach((value, index) => { + const entry = checkRecord(path, value, "a role interval") + if (typeof entry.role !== "string" || !(WORKSPACE_ROLES as readonly string[]).includes(entry.role)) { + throw badResponse(path, "a role interval has no known role") + } + const from = typeof entry.start === "string" ? Date.parse(entry.start) : NaN + if (Number.isNaN(from) || from < previousEnd) throw badResponse(path, "a role interval starts out of order") + const last = index === roles.length - 1 + if (entry.end === null) { + if (!last || end !== null) throw badResponse(path, "only the last role of an open interval is open") + return + } + const to = typeof entry.end === "string" ? Date.parse(entry.end) : NaN + if (Number.isNaN(to) || to < from || (end !== null && to > end)) throw badResponse(path, "a role interval's end is out of range") + if (last && end === null) throw badResponse(path, "the last role of an open interval is still held") + previousEnd = to + }) + } + + function checkWorkspace(path: string, value: unknown, what: string): Json { + const workspace = checkRecord(path, value, what) + if (typeof workspace.workspaceId !== "string") throw badResponse(path, `${what} has no workspaceId`) + return workspace + } + + /** A license as Core lists it: the fields a caller relies on, each of its type. */ + function checkLicense(path: string, value: unknown): LicenseView { + const license = checkRecord(path, value, "a license") + if (typeof license.licenseId !== "string" || !license.licenseId) throw badResponse(path, "a license has no licenseId") + if (!isRecord(license.owner) || typeof license.owner.type !== "string") throw badResponse(path, "a license has no owner") + for (const field of ["revision", "quantity", "seatsUsed"] as const) { + if (typeof license[field] !== "number" || !Number.isSafeInteger(license[field])) { + throw badResponse(path, `a license's ${field} is not a whole number`) + } + } + if (typeof license.product !== "string" || !Array.isArray(license.features)) { + throw badResponse(path, "a license has no product or features") + } + if (typeof license.validFrom !== "string" || typeof license.paidThrough !== "string") { + throw badResponse(path, "a license has no term") + } + if (license.endedAt !== null && typeof license.endedAt !== "string") { + throw badResponse(path, "a license's endedAt is neither a time nor null") + } + return license as unknown as LicenseView + } + + /** Every hold on a workspace, as `PUT` and `DELETE` on a deletion hold answer it. */ + function checkHolds(path: string, value: unknown): DeletionHoldsResponse { + const raw = checkRecord(path, value, "the deletion holds") + if (typeof raw.workspaceId !== "string") throw badResponse(path, "the deletion holds have no workspaceId") + if (!Array.isArray(raw.holds) || !raw.holds.every(isWorkspaceDeletionHold)) { + throw badResponse(path, "holds is not a list of deletion holds") + } + // Fail closed on a Core that does not say: one that predates `asOf` would apply a late call. + if (typeof raw.ignored !== "boolean") throw badResponse(path, "ignored is not a boolean") + return {workspaceId: raw.workspaceId, holds: raw.holds, ignored: raw.ignored} + } + + const isTextOrNull = (value: unknown) => value === null || typeof value === "string" + const isTime = (value: unknown) => typeof value === "string" && !Number.isNaN(Date.parse(value)) + + /** A check result for `url`, the URL asked about in its place. */ + function checkCheckResult(path: string, value: unknown, url: string): RegistryCheckResult { + const result = checkRecord(path, value, "a check result") + if (result.url !== url) throw badResponse(path, "the results are not the URLs asked about, in order") + if (typeof result.status !== "string" || !(REGISTRY_CHECK_STATUSES as readonly string[]).includes(result.status)) { + throw badResponse(path, "a check result has no known status") + } + for (const field of ["packageName", "name", "iconUrl"] as const) { + if (!isTextOrNull(result[field])) throw badResponse(path, `a check result's ${field} is not text or null`) + } + if (typeof result.private !== "boolean") throw badResponse(path, "a check result's private is not a boolean") + if (!isTime(result.checkedAt)) throw badResponse(path, "a check result's checkedAt is not a time") + return { + url, + status: result.status as RegistryCheckResult["status"], + packageName: result.packageName as string | null, + name: result.name as string | null, + iconUrl: result.iconUrl as string | null, + private: result.private, + checkedAt: result.checkedAt as string, + } + } + + function checkLookupEntry(path: string, value: unknown): RegistryLookupEntry | null { + if (value === null) return null + const entry = checkRecord(path, value, "a lookup entry") + if (!isTextOrNull(entry.name) || !isTextOrNull(entry.iconUrl)) { + throw badResponse(path, "a lookup entry's name or iconUrl is not text or null") + } + if (typeof entry.private !== "boolean" || typeof entry.archived !== "boolean") { + throw badResponse(path, "a lookup entry's private or archived is not a boolean") + } + return { + name: entry.name as string | null, + iconUrl: entry.iconUrl as string | null, + private: entry.private, + archived: entry.archived, + } + } + + /** A registry entry as `entries` answers it: the view's fields, each of its type, and the manifest or null. */ + function checkRegistryEntry(path: string, value: unknown): RegistryEntryDetail { + const entry = checkRecord(path, value, "the registry entry") + for (const field of ["url", "packageName", "registrableDomain"] as const) { + if (typeof entry[field] !== "string" || !entry[field]) throw badResponse(path, `the registry entry has no ${field}`) + } + for (const field of ["name", "version", "iconUrl"] as const) { + if (!isTextOrNull(entry[field])) throw badResponse(path, `the registry entry's ${field} is not text or null`) + } + if (entry.ageRating !== null && !AGE_RATINGS.includes(entry.ageRating as string)) { + throw badResponse(path, "the registry entry's ageRating is not a rating or null") + } + if (entry.verification !== "verified" && entry.verification !== "phone_reported") { + throw badResponse(path, "the registry entry has no known verification") + } + if (entry.status !== "active" && entry.status !== "archived") throw badResponse(path, "the registry entry has no known status") + if (typeof entry.private !== "boolean") throw badResponse(path, "the registry entry's private is not a boolean") + if (!isTime(entry.firstRegisteredAt)) throw badResponse(path, "the registry entry's firstRegisteredAt is not a time") + if (entry.lastVerifiedAt !== null && !isTime(entry.lastVerifiedAt)) { + throw badResponse(path, "the registry entry's lastVerifiedAt is neither a time nor null") + } + if (entry.manifest !== null) { + const manifest = checkRecord(path, entry.manifest, "the registry entry's manifest") + for (const field of ["packageName", "version", "name"] as const) { + if (typeof manifest[field] !== "string") throw badResponse(path, `the manifest has no ${field}`) + } + if (!isRecord(manifest.bundle) || typeof manifest.bundle.url !== "string" || typeof manifest.bundle.sha256 !== "string") { + throw badResponse(path, "the manifest has no bundle") + } + } + return entry as unknown as RegistryEntryDetail + } + + /** Sends one signed request. Resolves to the parsed JSON body, or null when `nullOn` accepts the failure. */ + async function call( + method: "GET" | "POST" | "PUT" | "DELETE", + pathWithQuery: string, + payload?: unknown, + nullOn?: (status: number, error: string | undefined) => boolean, + callTimeoutMs: number = timeoutMs, + ): Promise { + const body = payload === undefined ? "" : JSON.stringify(payload) + const timestampMs = Date.now() + const headers: Record = { + accept: "application/json", + [SERVICE_HEADERS.service]: opts.service, + [SERVICE_HEADERS.timestamp]: String(timestampMs), + [SERVICE_HEADERS.signature]: signServiceRequest({ + secret: opts.secret, + method, + pathWithQuery, + body, + timestampMs, + }), + } + if (payload !== undefined) headers["content-type"] = "application/json" + + let status: number + let text: string + try { + const response = await doFetch(`${baseUrl}${pathWithQuery}`, { + method, + headers, + body: payload === undefined ? undefined : body, + redirect: "error", + signal: AbortSignal.timeout(callTimeoutMs), + }) + status = response.status + text = await response.text() + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + throw new CoreWorkspaceClientError("core_unavailable", `Core ${pathWithQuery} is unreachable: ${reason}`) + } + + if (status < 200 || status >= 300) { + if (nullOn?.(status, errorCode(text))) return null + throw httpError(pathWithQuery, status, text) + } + try { + return JSON.parse(text) + } catch { + throw badResponse(pathWithQuery, "body is not JSON") + } + } + + /** The `error` string of a JSON error body, if there is one. */ + function errorCode(text: string): string | undefined { + try { + const parsed: unknown = JSON.parse(text) + if (isRecord(parsed) && typeof parsed.error === "string") return parsed.error + } catch { + // Not JSON; the status alone describes the failure. + } + return undefined + } + + function httpError(path: string, status: number, text: string) { + const error = errorCode(text) + const message = `Core ${path} failed with HTTP ${status}${error ? `: ${error}` : ""}` + if (status >= 500) return new CoreWorkspaceClientError("core_unavailable", message, status) + if (status === 401) { + const code = error === SERVICE_UNAUTHORIZED_ERROR ? "service_unauthorized" : "unauthorized" + return new CoreWorkspaceClientError(code, message, status) + } + if (status === 403) return new CoreWorkspaceClientError("forbidden", message, status) + // Only Core's own codes say something about the license; a bare 404 or 409 from anything else does not. + if (status === 409 && error === STALE_REVISION_ERROR) return new CoreWorkspaceClientError("stale_revision", message, status) + if (status === 404 && error === OWNER_NOT_FOUND_ERROR) return new CoreWorkspaceClientError("owner_not_found", message, status) + return new CoreWorkspaceClientError("bad_request", message, status) + } + + return { + async authorize(req) { + const path = `${API_PREFIX}/authorize` + const body = checkRecord(path, await call("POST", path, req), "the authorize response") + if (typeof body.allowed !== "boolean" || !Array.isArray(body.capabilities)) { + throw badResponse(path, "missing allowed or capabilities") + } + if (body.principal !== null && body.principal !== undefined) checkPrincipal(path, body.principal) + if (body.workspace !== null && body.workspace !== undefined) checkWorkspace(path, body.workspace, "the workspace") + return body as unknown as AuthorizeResponse + }, + + async resolvePrincipal(bearerToken) { + const path = `${API_PREFIX}/principal` + const raw = await call( + "POST", + path, + {token: bearerToken}, + (status, error) => status === 401 && error === INVALID_TOKEN_ERROR, + ) + if (raw === null) return null + if (!isRecord(raw) || !Array.isArray(raw.workspaces)) throw badResponse(path, "missing principal or workspaces") + checkPrincipal(path, raw.principal) + for (const workspace of raw.workspaces) checkWorkspace(path, workspace, "a workspace") + return raw as unknown as PrincipalResponse + }, + + async checkMemberships(mentraUserId, workspaceIds) { + const path = `${API_PREFIX}/memberships/check` + const raw = checkRecord(path, await call("POST", path, {mentraUserId, workspaceIds}), "the membership check") + if (!isRecord(raw.memberships)) throw badResponse(path, "the memberships are not an object") + return raw.memberships as Record + }, + + async getWorkspace(workspaceId) { + const path = `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}` + const raw = await call( + "GET", + path, + undefined, + (status, error) => status === 404 && error === WORKSPACE_NOT_FOUND_ERROR, + ) + if (raw === null) return null + return checkWorkspace(path, raw, "the workspace") as unknown as WorkspaceSummary + }, + + async listChanges(input) { + const query = new URLSearchParams() + if (input.after !== undefined && input.after !== null) query.set("after", input.after) + if (input.limit !== undefined) query.set("limit", String(input.limit)) + const queryString = query.toString() + const path = `${API_PREFIX}/changes${queryString ? `?${queryString}` : ""}` + const raw = checkRecord(path, await call("GET", path), "the change page") + if (!Array.isArray(raw.events)) throw badResponse(path, "missing events") + if (raw.next !== null && (typeof raw.next !== "string" || !CURSOR.test(raw.next))) { + throw badResponse(path, "next is neither a sequence number nor null") + } + let previous = 0 + for (const event of raw.events) { + const checked = checkChangeEvent(path, event) + if (checked.seq <= previous) throw badResponse(path, "events are not in strictly increasing seq order") + previous = checked.seq + } + // The cursor a poller stores is the last event's seq: one that points anywhere else skips or repeats events. + const last = raw.events[raw.events.length - 1] as WorkspaceChangeEvent | undefined + if (raw.next !== null && String(last?.seq) !== raw.next) { + throw badResponse(path, "next is not the seq of the last event") + } + return {events: raw.events as WorkspaceChangeEvent[], next: raw.next} + }, + + async listWorkspaceMembers(workspaceId) { + const path = `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/members` + const raw = checkRecord(path, await call("GET", path), "the member list") + if (!Array.isArray(raw.members)) throw badResponse(path, "missing members") + for (const entry of raw.members) { + const member = checkRecord(path, entry, "a member") + if (typeof member.membershipId !== "string" || !member.membershipId) throw badResponse(path, "a member has no membershipId") + if (typeof member.role !== "string" || !member.role) throw badResponse(path, "a member has no role") + for (const field of ["mentraUserId", "email"] as const) { + if (member[field] !== null && typeof member[field] !== "string") throw badResponse(path, `a member's ${field} is not text or null`) + } + if (member.name !== undefined && member.name !== null && typeof member.name !== "string") { + throw badResponse(path, "a member's name is not text or null") + } + } + return {members: raw.members as WorkspaceMembersResponse["members"]} + }, + + async listMembershipIntervals(input) { + const query = new URLSearchParams() + if (input.after !== undefined && input.after !== null) query.set("after", input.after) + if (input.limit !== undefined) query.set("limit", String(input.limit)) + const queryString = query.toString() + const path = `${API_PREFIX}/membership-intervals${queryString ? `?${queryString}` : ""}` + const raw = checkRecord(path, await call("GET", path), "the interval page") + if (typeof raw.lookbackDays !== "number" || !Number.isSafeInteger(raw.lookbackDays) || raw.lookbackDays < 1) { + throw badResponse(path, "lookbackDays is not a positive whole number") + } + if (typeof raw.windowStart !== "string" || Number.isNaN(Date.parse(raw.windowStart))) { + throw badResponse(path, "windowStart is not a time") + } + if (typeof raw.feedSeq !== "number" || !Number.isSafeInteger(raw.feedSeq) || raw.feedSeq < 0) { + throw badResponse(path, "feedSeq is not a whole number") + } + if (!Array.isArray(raw.intervals)) throw badResponse(path, "missing intervals") + if (raw.next !== null && (typeof raw.next !== "string" || raw.next.length === 0)) { + throw badResponse(path, "next is neither a cursor nor null") + } + const intervals = raw.intervals.map(value => checkInterval(path, value)) + return { + lookbackDays: raw.lookbackDays, + windowStart: raw.windowStart, + feedSeq: raw.feedSeq, + intervals, + next: raw.next, + } + }, + + async mintServiceCredential(input) { + const path = `${API_PREFIX}/credentials` + const raw = checkRecord(path, await call("POST", path, input), "the credential") + if (typeof raw.credentialId !== "string" || typeof raw.token !== "string") { + throw badResponse(path, "missing credentialId or token") + } + return {credentialId: raw.credentialId, token: raw.token} + }, + + async resolveEmail(email) { + const path = `${API_PREFIX}/users/resolve-email` + const raw = await call("POST", path, {email}, (status, error) => status === 404 && error === USER_NOT_FOUND_ERROR) + if (raw === null) return null + if (!isRecord(raw) || typeof raw.mentraUserId !== "string" || !raw.mentraUserId) { + throw badResponse(path, "missing mentraUserId") + } + return raw.mentraUserId + }, + + async setDeletionHold(workspaceId, hold) { + const path = deletionHoldPath(workspaceId) + const asOf = hold.asOf.toISOString() + // Only what was given: an absent count is "no count", never a null Core would have to read. + const body = hold.count === undefined ? {reason: hold.reason, asOf} : {reason: hold.reason, count: hold.count, asOf} + return checkHolds(path, await call("PUT", path, body)) + }, + + async clearDeletionHold(workspaceId, update) { + const path = deletionHoldPath(workspaceId) + const body: DeletionHoldUpdate = {asOf: update.asOf.toISOString()} + return checkHolds(path, await call("DELETE", path, body)) + }, + + async putLicense(write) { + const path = `${LICENSES_PREFIX}/${encodeURIComponent(write.licenseId)}` + const raw = checkRecord(path, await call("PUT", path, write), "the license write") + if (typeof raw.applied !== "boolean" || typeof raw.revision !== "number" || !Number.isSafeInteger(raw.revision)) { + throw badResponse(path, "missing applied or a whole revision") + } + return {applied: raw.applied, revision: raw.revision, ...(raw.ended === true ? {ended: true as const} : {})} + }, + + async listLicenses(workspaceId) { + const query = new URLSearchParams({ownerType: "workspace", ownerId: workspaceId}) + const path = `${LICENSES_PREFIX}?${query.toString()}` + const raw = checkRecord(path, await call("GET", path), "the license list") + if (!Array.isArray(raw.licenses)) throw badResponse(path, "licenses is not a list") + return {licenses: raw.licenses.map(license => checkLicense(path, license))} + }, + + async checkRegistry(input) { + const path = `${REGISTRY_PREFIX}/check` + const body: RegistryCheckRequest = {urls: input.urls, workspaceId: input.workspaceId, mentraUserId: input.mentraUserId} + // Core takes up to 10 seconds to answer a check, longer than the client's usual timeout. + const answer = await call("POST", path, body, undefined, Math.max(timeoutMs, REGISTRY_CHECK_TIMEOUT_MS)) + const raw = checkRecord(path, answer, "the check") + if (!Array.isArray(raw.results) || raw.results.length !== input.urls.length) { + throw badResponse(path, "results is not one result per URL") + } + return raw.results.map((result, index) => checkCheckResult(path, result, input.urls[index]!)) + }, + + async lookupRegistry(input) { + const path = `${REGISTRY_PREFIX}/lookup` + const body: RegistryLookupRequest = {workspaceId: input.workspaceId, packageNames: input.packageNames} + const raw = checkRecord(path, await call("POST", path, body), "the lookup") + const entries = checkRecord(path, raw.entries, "the lookup's entries") + // Built from the names asked about, so a name such as `__proto__` is an own entry like any other. + return Object.fromEntries( + input.packageNames.map(packageName => { + if (!Object.prototype.hasOwnProperty.call(entries, packageName)) { + throw badResponse(path, "the lookup leaves out a package asked about") + } + return [packageName, checkLookupEntry(path, entries[packageName])] + }), + ) + }, + + async getRegistryEntry(url) { + const path = `${REGISTRY_PREFIX}/entries?${new URLSearchParams({url}).toString()}` + const raw = await call( + "GET", + path, + undefined, + (status, error) => status === 404 && error === REGISTRY_ENTRY_NOT_FOUND_ERROR, + ) + if (raw === null) return null + return checkRegistryEntry(path, checkRecord(path, raw, "the entry response").entry) + }, + + async archiveRegistry(input) { + const path = `${REGISTRY_PREFIX}/archive` + const body: RegistryArchiveRequest = {rule: input.rule, reason: input.reason, actorEmail: input.actorEmail} + const raw = checkRecord(path, await call("POST", path, body), "the archive answer") + const rule = checkRecord(path, raw.rule, "the archive rule") + if (!REGISTRY_RULE_KINDS.includes(rule.kind as RegistryArchiveRuleKind) || typeof rule.value !== "string") { + throw badResponse(path, "the archive rule has no known kind or value") + } + if (typeof raw.created !== "boolean") throw badResponse(path, "created is not a boolean") + if (typeof raw.entriesArchived !== "number" || !Number.isSafeInteger(raw.entriesArchived) || raw.entriesArchived < 0) { + throw badResponse(path, "entriesArchived is not a whole number") + } + return { + rule: {kind: rule.kind as RegistryArchiveRuleKind, value: rule.value}, + created: raw.created, + entriesArchived: raw.entriesArchived, + } + }, + } + + /** This service's own hold on a workspace: the service in the path is always the one that signs. */ + function deletionHoldPath(workspaceId: string): string { + return `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/deletion-holds/${encodeURIComponent(opts.service)}` + } +} diff --git a/cloud-v2/packages/workspace-contract/src/deletion-holds.test.ts b/cloud-v2/packages/workspace-contract/src/deletion-holds.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..216c7a749915a6fa0de606271745a8837e4cdcf3 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/deletion-holds.test.ts @@ -0,0 +1,68 @@ +import {describe, expect, test} from "bun:test" +import {describeDeletionHold, describeDeletionHolds, isWorkspaceDeletionHold} from "./deletion-holds" +import {DELETION_HOLD_REASON_PATTERN, OWNS_MINIAPPS_HOLD_REASON} from "./types" + +describe("describeDeletionHold", () => { + test("the Store's miniapps hold names how many miniapps, and where to delete them", () => { + const store = (count?: number) => describeDeletionHold({service: "store", reason: OWNS_MINIAPPS_HOLD_REASON, count}) + expect(store(3)).toBe("This workspace still owns 3 miniapps. Delete them in the Developer Console first.") + expect(store(1)).toBe("This workspace still owns 1 miniapp. Delete it in the Developer Console first.") + expect(store()).toBe("This workspace still owns miniapps. Delete them in the Developer Console first.") + }) + + test("any other hold names the service and its reason in words", () => { + expect(describeDeletionHold({service: "fleet", reason: "manages_devices", count: 4})).toBe( + "The fleet service still needs this workspace (manages devices: 4). Resolve that before deleting it.", + ) + expect(describeDeletionHold({service: "fleet", reason: "manages_devices"})).toBe( + "The fleet service still needs this workspace (manages devices). Resolve that before deleting it.", + ) + // The reason is the Store's only together with the Store. + expect(describeDeletionHold({service: "fleet", reason: OWNS_MINIAPPS_HOLD_REASON, count: 2})).toBe( + "The fleet service still needs this workspace (owns miniapps: 2). Resolve that before deleting it.", + ) + }) + + test("several holds read as one sentence after another", () => { + expect( + describeDeletionHolds([ + {service: "fleet", reason: "manages_devices"}, + {service: "store", reason: OWNS_MINIAPPS_HOLD_REASON, count: 2}, + ]), + ).toBe( + "The fleet service still needs this workspace (manages devices). Resolve that before deleting it. " + + "This workspace still owns 2 miniapps. Delete them in the Developer Console first.", + ) + }) +}) + +describe("isWorkspaceDeletionHold", () => { + test("accepts the wire shape and nothing else", () => { + expect(isWorkspaceDeletionHold({service: "store", reason: "owns_miniapps", count: 3})).toBe(true) + expect(isWorkspaceDeletionHold({service: "store", reason: "owns_miniapps"})).toBe(true) + for (const value of [ + null, + "store", + [], + {reason: "owns_miniapps"}, + {service: "", reason: "owns_miniapps"}, + {service: "store"}, + {service: "store", reason: ""}, + {service: "store", reason: "owns_miniapps", count: 0}, + {service: "store", reason: "owns_miniapps", count: 1.5}, + {service: "store", reason: "owns_miniapps", count: "3"}, + {service: "store", reason: "owns_miniapps", count: null}, + ]) { + expect({value, ok: isWorkspaceDeletionHold(value)}).toEqual({value, ok: false}) + } + }) +}) + +describe("DELETION_HOLD_REASON_PATTERN", () => { + test("is a lowercase code of at most 64 characters starting with a letter", () => { + for (const ok of ["owns_miniapps", "a", "x".repeat(64), "v2_devices"]) expect(DELETION_HOLD_REASON_PATTERN.test(ok)).toBe(true) + for (const bad of ["", "Owns", "owns miniapps", "_x", "1x", "owns-miniapps", "x".repeat(65), "owns_miniapps\n"]) { + expect({bad, ok: DELETION_HOLD_REASON_PATTERN.test(bad)}).toEqual({bad, ok: false}) + } + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/deletion-holds.ts b/cloud-v2/packages/workspace-contract/src/deletion-holds.ts new file mode 100644 index 0000000000000000000000000000000000000000..713ba2fa23910605eba3941bf1f94a796032a0f3 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/deletion-holds.ts @@ -0,0 +1,30 @@ +/** + * Deletion holds in words, for everyone who shows one: Core's 409 `workspace_has_holds`, the workspace + * portal, the admin portal and the Developer Console all say the same thing. Browser-safe. + */ +import {OWNS_MINIAPPS_HOLD_REASON, type WorkspaceDeletionHold} from "./types" + +/** What one hold means for the person trying to delete the workspace, as a sentence or two. */ +export function describeDeletionHold(hold: WorkspaceDeletionHold): string { + const count = typeof hold.count === "number" ? hold.count : undefined + if (hold.service === "store" && hold.reason === OWNS_MINIAPPS_HOLD_REASON) { + if (count === 1) return "This workspace still owns 1 miniapp. Delete it in the Developer Console first." + const owned = count === undefined ? "miniapps" : `${count} miniapps` + return `This workspace still owns ${owned}. Delete them in the Developer Console first.` + } + const reason = hold.reason.replace(/_/g, " ") + return `The ${hold.service} service still needs this workspace (${reason}${count === undefined ? "" : `: ${count}`}). Resolve that before deleting it.` +} + +/** Every hold in words, one after another. */ +export function describeDeletionHolds(holds: readonly WorkspaceDeletionHold[]): string { + return holds.map(describeDeletionHold).join(" ") +} + +/** Whether `value` has the wire shape of a hold: a service and a reason, and a positive whole `count` when it has one. */ +export function isWorkspaceDeletionHold(value: unknown): value is WorkspaceDeletionHold { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false + const hold = value as Record + if (typeof hold.service !== "string" || !hold.service || typeof hold.reason !== "string" || !hold.reason) return false + return hold.count === undefined || (typeof hold.count === "number" && Number.isSafeInteger(hold.count) && hold.count >= 1) +} diff --git a/cloud-v2/packages/workspace-contract/src/fleet-ui.test.ts b/cloud-v2/packages/workspace-contract/src/fleet-ui.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..146fa294eda5a163cc9baf55fe26f48c99621f92 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/fleet-ui.test.ts @@ -0,0 +1,82 @@ +import {describe, expect, test} from "bun:test" +import {readFileSync} from "node:fs" +import {join} from "node:path" +import {FLEET_UI_CONTRACT_VERSION, type FleetUiContext, type FleetUiMe, type FleetUiModule} from "./fleet-ui" +import * as root from "./index" + +const me: FleetUiMe = { + authenticated: true, + user: {mentraUserId: "mu_1", email: null}, + organization: {capabilities: ["organization.fleet.administer"]}, + fleet: {installed: true}, +} + +describe("Fleet UI module contract", () => { + test("is version 1", () => { + expect(FLEET_UI_CONTRACT_VERSION).toBe(1) + }) + + test("is reached through the ./fleet-ui subpath, not the package root, and bundles for the browser", async () => { + const manifest = JSON.parse(readFileSync(join(import.meta.dir, "..", "package.json"), "utf8")) + expect(manifest.exports["./fleet-ui"]).toBe("./src/fleet-ui.ts") + expect(Object.keys(root)).not.toContain("FLEET_UI_CONTRACT_VERSION") + const entrypoint = Bun.resolveSync("./fleet-ui", import.meta.dir) + const result = await Bun.build({entrypoints: [entrypoint], target: "browser"}) + expect(result.logs.filter((log) => log.level === "error").map((log) => log.message)).toEqual([]) + expect(result.success).toBe(true) + }) + + test("a module mounts into a host element with the host's context and unmounts", () => { + const calls: string[] = [] + const mod: FleetUiModule = { + contractVersion: FLEET_UI_CONTRACT_VERSION, + mount(element, ctx) { + calls.push(`mount ${ctx.apiBase} ${ctx.route.path}${ctx.route.query}`) + ctx.navigate("/fleet/devices", {replace: true}) + ctx.onSessionExpired() + return {unmount: () => calls.push("unmount")} + }, + } + const ctx: FleetUiContext = { + contractVersion: 1, + apiBase: "/api/admin/fleet", + me, + route: {path: "/fleet", query: "?range=7d"}, + navigate: (path, opts) => calls.push(`navigate ${path} ${opts?.replace === true}`), + onSessionExpired: () => calls.push("expired"), + } + const handle = mod.mount({} as unknown as HTMLElement, ctx) + handle.unmount() + expect(calls).toEqual(["mount /api/admin/fleet /fleet?range=7d", "navigate /fleet/devices true", "expired", "unmount"]) + }) + + test("a module's handle may offer setRoute, which a host calls instead of mounting again; it is optional", () => { + const calls: string[] = [] + const ctx: FleetUiContext = { + contractVersion: 1, + apiBase: "/api/admin/fleet", + me, + route: {path: "/", query: ""}, + navigate: () => {}, + onSessionExpired: () => {}, + } + const redrawing: FleetUiModule = { + contractVersion: FLEET_UI_CONTRACT_VERSION, + mount: () => ({ + unmount: () => calls.push("unmount"), + setRoute: (route) => calls.push(`route ${route.path}${route.query}`), + }), + } + const remounting: FleetUiModule = { + contractVersion: FLEET_UI_CONTRACT_VERSION, + mount: () => ({unmount: () => calls.push("unmount")}), + } + const withSetRoute = redrawing.mount({} as unknown as HTMLElement, ctx) + withSetRoute.setRoute?.({path: "/devices", query: "?tab=phones"}) + const withoutSetRoute = remounting.mount({} as unknown as HTMLElement, ctx) + withoutSetRoute.setRoute?.({path: "/devices", query: "?tab=phones"}) + expect(typeof withSetRoute.setRoute).toBe("function") + expect(withoutSetRoute.setRoute).toBeUndefined() + expect(calls).toEqual(["route /devices?tab=phones"]) + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/fleet-ui.ts b/cloud-v2/packages/workspace-contract/src/fleet-ui.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9255eb1d47198d7ba7b007b241c6c86705b43df --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/fleet-ui.ts @@ -0,0 +1,59 @@ +/// +/** + * The contract between a host page and the Fleet UI module that the Fleet integration serves + * (`/api/admin/fleet/ui/entry.js`). The host, an admin portal page, imports the module, checks + * `contractVersion`, and calls `mount` with a {@link FleetUiContext}. Types and one constant only, + * so the host and the module can both import it in the browser. + * + * Import it from `@mentra/workspace-contract/fleet-ui`, not the package root: the contract names DOM + * types, which server packages do not have. + */ + +/** The version of this contract. A host and a module that disagree on it must not be mounted together. */ +export const FLEET_UI_CONTRACT_VERSION = 1 + +/** What the host knows about the caller. */ +export interface FleetUiMe { + authenticated: true + /** The signed-in Mentra user, or null when the caller is not signed in as one. */ + user: {mentraUserId: string; email: string | null} | null + organization: {capabilities: string[]} + /** + * The workspaces the caller may use Fleet Management in, each with the caller's capabilities there. A person + * belongs to at most one workspace, so this has at most one entry, except for an Organization Admin: on the + * workspace portal it names exactly the workspace the page is open on, whether or not they are a member. + * Optional for a host that predates it (the admin portal's organization view). + */ + workspaces?: Array<{workspaceId: string; name: string; capabilities: string[]}> + fleet: {installed: boolean} +} + +/** Everything the host hands the module when it mounts. */ +export interface FleetUiContext { + contractVersion: 1 + /** Where the module sends its API requests, e.g. `/api/admin/fleet`. */ + apiBase: string + me: FleetUiMe + /** The host's route when the module mounts. Later changes reach the module as the {@link FleetUiModule.mount} doc says. */ + route: {path: string; query: string} + /** Asks the host to go to `path`; with `replace`, the current history entry is replaced instead of a new one added. */ + navigate(path: string, opts?: {replace?: boolean}): void + /** Tells the host the caller's session has ended (the API answered 401), so it can send them to sign in. */ + onSessionExpired(): void +} + +/** What the Fleet UI entry exports. */ +export interface FleetUiModule { + contractVersion: number + /** + * Renders into `element`; the returned handle removes everything the module added. + * + * `ctx.route` is the route at mount. If the handle provides `setRoute`, the host calls it on every later + * route change (including after the module's own `navigate` and Back/Forward) instead of remounting; + * otherwise the host unmounts and mounts again. + */ + mount( + element: HTMLElement | ShadowRoot, + ctx: FleetUiContext, + ): {unmount(): void; setRoute?(route: {path: string; query: string}): void} +} diff --git a/cloud-v2/packages/workspace-contract/src/forwarded-principal.test.ts b/cloud-v2/packages/workspace-contract/src/forwarded-principal.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..04b90009d9a4ee6efad65d9645fdf54ce8d326d9 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/forwarded-principal.test.ts @@ -0,0 +1,408 @@ +import {describe, expect, test} from "bun:test" +import {createHmac} from "node:crypto" +import { + parseForwardedPrincipal, + signForwardedPrincipal, + verifyForwardedPrincipal, + type ForwardedRequest, +} from "./forwarded-principal" +import {SERVICE_HEADERS, signServiceRequest} from "./service-signature" +import {FORWARDED_PRINCIPAL_HEADERS, type ForwardedPrincipal} from "./types" + +const SECRET = "fleet-secret" +const NOW = 1_760_000_000_000 + +const phone: ForwardedPrincipal = { + kind: "phone", + mentraUserId: "mu_1", + tenantId: "mentra", + sessionId: "sess_1", + email: "phone@example.com", +} +const phoneWithoutEmail: ForwardedPrincipal = {...phone, email: null} +const user: ForwardedPrincipal = { + kind: "user", + mentraUserId: "mu_2", + email: null, + emailVerified: false, + isOrganizationAdmin: true, + organizationCapabilities: ["organization.fleet.administer", "organization.incidents.read"], + scope: {kind: "organization"}, +} +const workspaceUser: ForwardedPrincipal = { + ...user, + email: "admin@example.com", + emailVerified: true, + isOrganizationAdmin: false, + organizationCapabilities: [], + scope: {kind: "workspace", workspaceId: "ws_1"}, +} +const personUser: ForwardedPrincipal = { + ...workspaceUser, + scope: {kind: "person"}, +} +const anyone: ForwardedPrincipal = {kind: "public", scope: {kind: "public"}} + +/** A request whose headers are a plain string map, so a test can add, drop or replace one. */ +type SignedRequest = Omit & {headers: Record} + +/** A request signed the way Core's forwarder signs it. */ +function forwarded( + principal: ForwardedPrincipal, + options: {secret?: string; timestampMs?: number; method?: string; pathWithQuery?: string; body?: string} = {}, +): SignedRequest { + const secret = options.secret ?? SECRET + const timestampMs = options.timestampMs ?? NOW + const method = options.method ?? "POST" + const pathWithQuery = options.pathWithQuery ?? "/v1/client/observations?batch=1" + const body = options.body ?? '{"records":[]}' + const signed = signForwardedPrincipal({secret, timestampMs, principal}) + return { + method, + pathWithQuery, + body, + headers: { + [SERVICE_HEADERS.service]: "core", + [SERVICE_HEADERS.timestamp]: String(timestampMs), + [SERVICE_HEADERS.signature]: signServiceRequest({secret, method, pathWithQuery, body, timestampMs}), + [FORWARDED_PRINCIPAL_HEADERS.principal]: signed.principal, + [FORWARDED_PRINCIPAL_HEADERS.principalSignature]: signed.principalSignature, + }, + } +} + +/** The same request with a different principal header, signed correctly by `secret` at `NOW`. */ +function withSignedPrincipalBody(request: SignedRequest, body: unknown): SignedRequest { + const header = Buffer.from(JSON.stringify(body)).toString("base64url") + const signature = createHmac("sha256", SECRET).update(`${NOW}\n${header}`).digest("base64url") + return { + ...request, + headers: { + ...request.headers, + [FORWARDED_PRINCIPAL_HEADERS.principal]: header, + [FORWARDED_PRINCIPAL_HEADERS.principalSignature]: signature, + }, + } +} + +const verify = (request: ForwardedRequest, secrets: readonly string[] = [SECRET], nowMs = NOW) => + verifyForwardedPrincipal(request, secrets, {nowMs}) + +describe("verifyForwardedPrincipal", () => { + test("returns each principal kind Core signs", () => { + expect(verify(forwarded(phone))).toEqual(phone) + expect(verify(forwarded(phoneWithoutEmail))).toEqual(phoneWithoutEmail) + expect(verify(forwarded(user))).toEqual(user) + expect(verify(forwarded(workspaceUser))).toEqual(workspaceUser) + expect(verify(forwarded(personUser))).toEqual(personUser) + expect(verify(forwarded(anyone, {method: "GET", pathWithQuery: "/v1/portal/public/products/mentra.call.unlimited", body: ""}))).toEqual( + anyone, + ) + }) + + test("the principal header is base64url JSON and its signature is HMAC-SHA256 over `\\n
`", () => { + const signed = signForwardedPrincipal({secret: SECRET, timestampMs: NOW, principal: phone}) + expect(Object.keys(signed).sort()).toEqual(["principal", "principalSignature"]) + expect(JSON.parse(Buffer.from(signed.principal, "base64url").toString())).toEqual(phone) + expect(signed.principalSignature).toBe( + createHmac("sha256", SECRET).update(`${NOW}\n${signed.principal}`).digest("base64url"), + ) + }) + + test("refuses to sign with an empty secret", () => { + expect(() => signForwardedPrincipal({secret: " ", timestampMs: NOW, principal: phone})).toThrow() + }) + + test("accepts a Headers object and any header-name case, and a rotated secret list", () => { + const request = forwarded(user, {secret: "old"}) + expect(verify({...request, headers: new Headers(request.headers)}, ["new", "old"])).toEqual(user) + const upper = Object.fromEntries( + Object.entries(request.headers).map(([name, value]) => [name.toUpperCase(), value]), + ) + expect(verify({...request, headers: upper}, ["old"])).toEqual(user) + }) + + test("refuses a request whose service signature does not match what was received", () => { + const request = forwarded(phone) + expect(verify({...request, body: '{"records":[1]}'})).toBeNull() + expect(verify({...request, pathWithQuery: "/v1/client/observations?batch=2"})).toBeNull() + expect(verify({...request, method: "PUT"})).toBeNull() + expect(verify(request, ["another-secret"])).toBeNull() + }) + + test("refuses a swapped principal or a principal signed for another timestamp", () => { + const a = forwarded(phone) + const b = forwarded(user) + expect( + verify({ + ...a, + headers: {...a.headers, [FORWARDED_PRINCIPAL_HEADERS.principal]: b.headers[FORWARDED_PRINCIPAL_HEADERS.principal]!}, + }), + ).toBeNull() + expect( + verify({ + ...a, + headers: { + ...a.headers, + [FORWARDED_PRINCIPAL_HEADERS.principal]: b.headers[FORWARDED_PRINCIPAL_HEADERS.principal]!, + [FORWARDED_PRINCIPAL_HEADERS.principalSignature]: b.headers[FORWARDED_PRINCIPAL_HEADERS.principalSignature]!, + }, + }), + ).toEqual(user) + const later = signForwardedPrincipal({secret: SECRET, timestampMs: NOW + 1, principal: phone}) + expect( + verify({...a, headers: {...a.headers, [FORWARDED_PRINCIPAL_HEADERS.principalSignature]: later.principalSignature}}), + ).toBeNull() + }) + + test("a tampered principal fails even when its fields still parse", () => { + const request = forwarded(workspaceUser) + const escalated = Buffer.from(JSON.stringify({...workspaceUser, scope: {kind: "organization"}})).toString("base64url") + expect(verify({...request, headers: {...request.headers, [FORWARDED_PRINCIPAL_HEADERS.principal]: escalated}})).toBeNull() + // A person's own scope cannot be widened to a workspace's or the organization's either. + const personal = forwarded(personUser) + for (const scope of [{kind: "organization"}, {kind: "workspace", workspaceId: "ws_1"}]) { + const widened = Buffer.from(JSON.stringify({...personUser, scope})).toString("base64url") + expect(verify({...personal, headers: {...personal.headers, [FORWARDED_PRINCIPAL_HEADERS.principal]: widened}})).toBeNull() + } + }) + + test("requires both signatures from the same secret", () => { + const request = forwarded(phone, {secret: "s1"}) + const other = signForwardedPrincipal({secret: "s2", timestampMs: NOW, principal: phone}) + const mixed = { + ...request, + headers: {...request.headers, [FORWARDED_PRINCIPAL_HEADERS.principalSignature]: other.principalSignature}, + } + expect(verify(mixed, ["s1", "s2"])).toBeNull() + }) + + test("refuses a stale or future timestamp, honouring maxSkewMs", () => { + const request = forwarded(phone) + expect(verify(request, [SECRET], NOW + 61_000)).toBeNull() + expect(verify(request, [SECRET], NOW - 61_000)).toBeNull() + expect(verify(request, [SECRET], NOW + 30_000)).toEqual(phone) + expect(verifyForwardedPrincipal(request, [SECRET], {nowMs: NOW + 30_000, maxSkewMs: 10_000})).toBeNull() + }) + + test("refuses a missing header, another service name, a malformed timestamp or blank secrets", () => { + const request = forwarded(phone) + for (const name of [ + SERVICE_HEADERS.service, + SERVICE_HEADERS.timestamp, + SERVICE_HEADERS.signature, + FORWARDED_PRINCIPAL_HEADERS.principal, + FORWARDED_PRINCIPAL_HEADERS.principalSignature, + ]) { + const headers = {...request.headers} + delete headers[name] + expect(verify({...request, headers})).toBeNull() + } + expect(verify({...request, headers: {...request.headers, [SERVICE_HEADERS.service]: "store"}})).toBeNull() + expect(verify({...request, headers: {...request.headers, [SERVICE_HEADERS.timestamp]: `0${NOW}`}})).toBeNull() + expect(verify({...request, headers: {...request.headers, [SERVICE_HEADERS.timestamp]: `${NOW}.0`}})).toBeNull() + expect(verify(request, ["", " "])).toBeNull() + expect(verify(request, [])).toBeNull() + }) + + test("a repeated header counts as missing", () => { + const request = forwarded(phone) + const principal = request.headers[FORWARDED_PRINCIPAL_HEADERS.principal]! + expect( + verify({...request, headers: {...request.headers, [FORWARDED_PRINCIPAL_HEADERS.principal]: [principal, principal]}}), + ).toBeNull() + }) + + test("refuses a correctly signed principal that is not one of the documented shapes", () => { + const request = forwarded(phone) + for (const body of [{kind: "admin", mentraUserId: "mu_1"}, {kind: "phone", mentraUserId: ""}, ["phone"]]) { + expect(verify(withSignedPrincipalBody(request, body))).toBeNull() + } + }) + + test("accepts a correctly signed principal from a newer Core that knows more capabilities and fields", () => { + const newer = { + ...user, + organizationCapabilities: ["organization.fleet.administer", "organization.future.thing"], + futureField: true, + scope: {kind: "organization", futureDetail: 1}, + } + expect(verify(withSignedPrincipalBody(forwarded(phone), newer))).toEqual({ + ...user, + organizationCapabilities: ["organization.fleet.administer"], + }) + }) + + test("refuses a correctly signed credential principal", () => { + const credential = { + kind: "credential", + credentialId: "01HZKEY", + credentialKind: "workspace", + workspaceId: "ws_1", + scopes: ["miniapps.publish"], + packageNames: ["com.example.app"], + } + expect(verify(withSignedPrincipalBody(forwarded(phone), credential))).toBeNull() + }) +}) + +describe("parseForwardedPrincipal", () => { + test("accepts exactly the documented fields of each kind", () => { + expect(parseForwardedPrincipal(phone)).toEqual(phone) + expect(parseForwardedPrincipal(phoneWithoutEmail)).toEqual(phoneWithoutEmail) + expect(parseForwardedPrincipal(user)).toEqual(user) + expect(parseForwardedPrincipal(workspaceUser)).toEqual(workspaceUser) + expect(parseForwardedPrincipal(personUser)).toEqual(personUser) + expect(parseForwardedPrincipal(anyone)).toEqual(anyone) + }) + + test("returns a copy, not the object it was given", () => { + const capabilities = ["organization.fleet.administer"] + const input = {...user, organizationCapabilities: capabilities} + const parsed = parseForwardedPrincipal(input) + expect(parsed).toEqual(input as ForwardedPrincipal) + expect(parsed).not.toBe(input) + expect(parsed?.kind === "user" && parsed.organizationCapabilities).not.toBe(capabilities) + }) + + test("ignores fields the kind does not document and returns only the known ones", () => { + const withExtra = parseForwardedPrincipal({...user, extra: "ignored"}) + expect(withExtra).toEqual(user) + expect(Object.keys(withExtra!).sort()).toEqual(Object.keys(user).sort()) + const phoneWithExtra = parseForwardedPrincipal({...phone, extra: "ignored"}) + expect(phoneWithExtra).toEqual(phone) + expect(Object.keys(phoneWithExtra!).sort()).toEqual(Object.keys(phone).sort()) + const organizationScope = parseForwardedPrincipal({...user, scope: {kind: "organization", workspaceId: "ws_1"}}) + expect(organizationScope).toEqual(user) + expect(Object.keys((organizationScope as {scope: object}).scope)).toEqual(["kind"]) + const workspaceScope = parseForwardedPrincipal({...workspaceUser, scope: {kind: "workspace", workspaceId: "ws_1", extra: 1}}) + expect(workspaceScope).toEqual(workspaceUser) + expect(Object.keys((workspaceScope as {scope: object}).scope).sort()).toEqual(["kind", "workspaceId"]) + // A person's scope names nobody else: a workspace id beside `person` is not read. + const personScope = parseForwardedPrincipal({...personUser, scope: {kind: "person", workspaceId: "ws_1", extra: 1}}) + expect(personScope).toEqual(personUser) + expect(Object.keys((personScope as {scope: object}).scope)).toEqual(["kind"]) + }) + + test("reads only a value's own properties, so a prototype can neither supply nor pollute a field", () => { + const polluted = JSON.parse( + '{"kind":"phone","mentraUserId":"mu_1","tenantId":"mentra","sessionId":"sess_1","email":null,"__proto__":{"kind":"user","isOrganizationAdmin":true}}', + ) + const parsed = parseForwardedPrincipal(polluted) + expect(parsed).toEqual({...phone, email: null}) + expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype) + expect(Object.keys(parsed!)).not.toContain("isOrganizationAdmin") + expect(({} as Record).isOrganizationAdmin).toBeUndefined() + // Fields that exist only on the prototype do not count. + expect(parseForwardedPrincipal(Object.create(phone))).toBeNull() + expect(parseForwardedPrincipal({...user, scope: Object.create({kind: "organization"})})).toBeNull() + }) + + test("refuses fields of the wrong type", () => { + expect(parseForwardedPrincipal({...user, emailVerified: "yes"})).toBeNull() + expect(parseForwardedPrincipal({...user, email: 7})).toBeNull() + expect(parseForwardedPrincipal({...user, isOrganizationAdmin: 1})).toBeNull() + expect(parseForwardedPrincipal({...phone, sessionId: null})).toBeNull() + expect(parseForwardedPrincipal({...phone, tenantId: 1})).toBeNull() + expect(parseForwardedPrincipal({...phone, email: 7})).toBeNull() + expect(parseForwardedPrincipal({...phone, mentraUserId: " "})).toBeNull() + expect(parseForwardedPrincipal(null)).toBeNull() + expect(parseForwardedPrincipal("phone")).toBeNull() + expect(parseForwardedPrincipal([phone])).toBeNull() + }) + + test("a phone principal needs its email field, null or a string", () => { + const {email: _email, ...withoutEmail} = phone as Extract + expect(parseForwardedPrincipal(withoutEmail)).toBeNull() + expect(parseForwardedPrincipal({...phone, email: null})).toEqual(phoneWithoutEmail) + }) + + test("a credential-shaped principal is not a principal", () => { + expect( + parseForwardedPrincipal({ + kind: "credential", + credentialId: "01HZKEY", + credentialKind: "workspace", + workspaceId: "ws_1", + scopes: ["miniapps.publish"], + packageNames: ["com.example.app"], + }), + ).toBeNull() + }) + + test("a user principal needs a known scope", () => { + const {scope: _scope, ...withoutScope} = user as Extract + expect(parseForwardedPrincipal(withoutScope)).toBeNull() + expect(parseForwardedPrincipal({...user, scope: null})).toBeNull() + expect(parseForwardedPrincipal({...user, scope: "organization"})).toBeNull() + expect(parseForwardedPrincipal({...user, scope: {kind: "team"}})).toBeNull() + expect(parseForwardedPrincipal({...user, scope: {}})).toBeNull() + expect(parseForwardedPrincipal({...user, scope: {kind: "workspace"}})).toBeNull() + expect(parseForwardedPrincipal({...user, scope: {kind: "workspace", workspaceId: ""}})).toBeNull() + expect(parseForwardedPrincipal({...user, scope: {kind: "workspace", workspaceId: 7}})).toBeNull() + }) + + test("a public principal names no person: it is the public scope and nothing else", () => { + // Whatever a person's fields say beside it, a public principal is only its kind and scope. + const parsed = parseForwardedPrincipal({ + kind: "public", + scope: {kind: "public", workspaceId: "ws_1"}, + mentraUserId: "mu_1", + email: "someone@example.com", + emailVerified: true, + isOrganizationAdmin: true, + organizationCapabilities: ["organization.fleet.administer"], + }) + expect(parsed).toEqual(anyone) + expect(Object.keys(parsed!).sort()).toEqual(["kind", "scope"]) + expect(Object.keys((parsed as {scope: object}).scope)).toEqual(["kind"]) + // Its scope is the public one, present and its own. + expect(parseForwardedPrincipal({kind: "public"})).toBeNull() + expect(parseForwardedPrincipal({kind: "public", scope: null})).toBeNull() + expect(parseForwardedPrincipal({kind: "public", scope: "public"})).toBeNull() + expect(parseForwardedPrincipal({kind: "public", scope: Object.create({kind: "public"})})).toBeNull() + for (const scope of [{kind: "organization"}, {kind: "person"}, {kind: "workspace", workspaceId: "ws_1"}, {kind: "team"}]) { + expect([scope, parseForwardedPrincipal({kind: "public", scope})]).toEqual([scope, null]) + } + }) + + test("a person's request is never public: a user principal with the public scope is refused", () => { + expect(parseForwardedPrincipal({...user, scope: {kind: "public"}})).toBeNull() + expect(parseForwardedPrincipal({...workspaceUser, scope: {kind: "public"}})).toBeNull() + expect(verify(withSignedPrincipalBody(forwarded(user), {...user, scope: {kind: "public"}}))).toBeNull() + }) + + test("a phone principal that carries organizationCapabilities or a scope is a phone principal without them", () => { + for (const extra of [ + {organizationCapabilities: []}, + {organizationCapabilities: ["organization.fleet.administer"]}, + {scope: {kind: "organization"}}, + ]) { + const parsed = parseForwardedPrincipal({...phone, ...extra}) + expect(parsed).toEqual(phone) + expect(Object.keys(parsed!)).not.toContain("organizationCapabilities") + expect(Object.keys(parsed!)).not.toContain("scope") + } + }) + + test("a user principal needs an organizationCapabilities array of strings, and drops the ones it does not know", () => { + const {organizationCapabilities: _caps, ...withoutCapabilities} = user as Extract + expect(parseForwardedPrincipal(withoutCapabilities)).toBeNull() + expect(parseForwardedPrincipal({...user, organizationCapabilities: "organization.fleet.administer"})).toBeNull() + expect(parseForwardedPrincipal({...user, organizationCapabilities: null})).toBeNull() + expect(parseForwardedPrincipal({...user, organizationCapabilities: [7]})).toBeNull() + expect(parseForwardedPrincipal({...user, organizationCapabilities: ["organization.fleet.administer", null]})).toBeNull() + expect(parseForwardedPrincipal({...user, organizationCapabilities: []})).toEqual({...user, organizationCapabilities: []}) + // A capability this build does not know is dropped, not a reason to refuse the person. + expect( + parseForwardedPrincipal({ + ...user, + organizationCapabilities: ["organization.future.thing", "organization.fleet.administer", "workspace.read"], + }), + ).toEqual({...user, organizationCapabilities: ["organization.fleet.administer"]}) + expect(parseForwardedPrincipal({...user, organizationCapabilities: ["organization.future.thing"]})).toEqual({ + ...user, + organizationCapabilities: [], + }) + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/forwarded-principal.ts b/cloud-v2/packages/workspace-contract/src/forwarded-principal.ts new file mode 100644 index 0000000000000000000000000000000000000000..49584368c3e38452bc15fc8d8706536036d1cb43 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/forwarded-principal.ts @@ -0,0 +1,200 @@ +/** + * Signing and verifying the principal Core attaches to a request it forwards to the Fleet + * integration or to a portal module. Core signs with {@link signForwardedPrincipal}; the receiver verifies with + * {@link verifyForwardedPrincipal}, which checks the service signature and the principal signature + * against the same timestamp and secret before it decodes the principal. + */ +import {createHmac, timingSafeEqual} from "node:crypto" +import {ORGANIZATION_CAPABILITIES, type OrganizationCapability} from "./capabilities" +import {SERVICE_HEADERS, verifyServiceRequest} from "./service-signature" +import {FORWARDED_PRINCIPAL_HEADERS, FORWARDING_SERVICE, type ForwardedPrincipal, type ForwardedScope} from "./types" + +const isBlank = (secret: string) => secret.trim().length === 0 + +/** base64url HMAC-SHA256 of `\n`. Throws on an empty secret. */ +function principalSignature(secret: string, timestampMs: number | string, principalHeader: string): string { + if (isBlank(secret)) throw new Error("A service secret must not be empty") + return createHmac("sha256", secret).update(`${timestampMs}\n${principalHeader}`).digest("base64url") +} + +/** + * The two principal headers for `principal`: its base64url JSON (`x-mentra-principal`) and the + * signature binding it to the request's service-signature timestamp (`x-mentra-principal-signature`). + * Use the same `timestampMs` and secret as the request's `signServiceRequest`. + */ +export function signForwardedPrincipal(input: {secret: string; timestampMs: number; principal: ForwardedPrincipal}): { + principal: string + principalSignature: string +} { + const principal = Buffer.from(JSON.stringify(input.principal)).toString("base64url") + return {principal, principalSignature: principalSignature(input.secret, input.timestampMs, principal)} +} + +export interface ForwardedRequest { + method: string + /** The URL path and query exactly as received; Core signs the path it sent, any path prefix of the service's URL included. */ + pathWithQuery: string + /** The body text exactly as received; `""` when there is none. */ + body: string + /** The request headers: a `Headers`, or a plain object such as Node's `IncomingHttpHeaders`. */ + headers: Headers | Readonly> +} + +export interface VerifyForwardedPrincipalOptions { + /** Defaults to `Date.now()`. */ + nowMs?: number + /** Allowed clock skew; defaults to the service signature's 60 seconds. */ + maxSkewMs?: number +} + +/** + * The principal of a request Core forwarded, or null unless all of this holds: `x-mentra-service` is + * `core`; the service signature verifies (method, path with query, body, timestamp within the skew) + * with one of `secrets`; the principal signature verifies with that same secret and timestamp; and + * the principal decodes to one of the {@link ForwardedPrincipal} shapes. Empty or whitespace-only + * secrets are ignored. + * + * Which kinds a route accepts is the caller's decision: Fleet's `/v1/client` serves phones, its + * `/v1/admin` and a portal module's `/v1/portal` users, and a module's public read the `public` principal only. + */ +export function verifyForwardedPrincipal( + request: ForwardedRequest, + secrets: readonly string[], + options: VerifyForwardedPrincipalOptions = {}, +): ForwardedPrincipal | null { + const header = headerReader(request.headers) + const service = header(SERVICE_HEADERS.service) + const timestamp = header(SERVICE_HEADERS.timestamp) + const serviceSignature = header(SERVICE_HEADERS.signature) + const principalHeader = header(FORWARDED_PRINCIPAL_HEADERS.principal) + const givenPrincipalSignature = header(FORWARDED_PRINCIPAL_HEADERS.principalSignature) + if (service !== FORWARDING_SERVICE || !timestamp || !serviceSignature || !principalHeader || !givenPrincipalSignature) { + return null + } + // The timestamp both signatures cover, spelled exactly as Core sent it. + if (!/^[1-9]\d{0,15}$/.test(timestamp)) return null + const timestampMs = Number(timestamp) + + const given = Buffer.from(givenPrincipalSignature) + let verified = false + for (const secret of secrets.filter((candidate) => !isBlank(candidate))) { + const serviceOk = verifyServiceRequest({ + method: request.method, + pathWithQuery: request.pathWithQuery, + body: request.body, + timestampMs, + signature: serviceSignature, + secrets: [secret], + nowMs: options.nowMs ?? Date.now(), + maxSkewMs: options.maxSkewMs, + }) + const expected = Buffer.from(principalSignature(secret, timestamp, principalHeader)) + const principalOk = expected.length === given.length && timingSafeEqual(expected, given) + if (serviceOk && principalOk) verified = true + } + if (!verified) return null + + let decoded: unknown + try { + decoded = JSON.parse(Buffer.from(principalHeader, "base64url").toString("utf8")) + } catch { + return null + } + return parseForwardedPrincipal(decoded) +} + +/** + * `value` as a {@link ForwardedPrincipal}, or null when it is not one. The result holds only the + * documented fields of its kind, read from the value's own properties: a field the kind does not + * document (another kind's field, or one a newer Core adds) is ignored, so Core and the receiver + * need not deploy in step. A missing or unknown `kind`, a missing or wrongly typed documented field, + * a missing or unknown `scope.kind`, and a workspace scope without a `workspaceId` refuse the + * principal. `organizationCapabilities` must be an array of strings; the entries this build does not + * know are dropped. A `public` principal is its kind and the `public` scope, nothing else: any other scope refuses + * it, and a person's fields beside it are not read. A `user` principal with the `public` scope is refused, since + * a person's request is never public. + */ +export function parseForwardedPrincipal(value: unknown): ForwardedPrincipal | null { + if (!isRecord(value)) return null + switch (own(value, "kind")) { + case "phone": { + const mentraUserId = own(value, "mentraUserId") + const tenantId = own(value, "tenantId") + const sessionId = own(value, "sessionId") + const email = own(value, "email") + if (!isId(mentraUserId) || typeof tenantId !== "string" || typeof sessionId !== "string" || !isNullableString(email)) { + return null + } + return {kind: "phone", mentraUserId, tenantId, sessionId, email} + } + case "user": { + const mentraUserId = own(value, "mentraUserId") + const email = own(value, "email") + const emailVerified = own(value, "emailVerified") + const isOrganizationAdmin = own(value, "isOrganizationAdmin") + const organizationCapabilities = parseOrganizationCapabilities(own(value, "organizationCapabilities")) + const scope = parseForwardedScope(own(value, "scope")) + if ( + !scope || + scope.kind === "public" || + !isId(mentraUserId) || + !isNullableString(email) || + typeof emailVerified !== "boolean" || + typeof isOrganizationAdmin !== "boolean" || + !organizationCapabilities + ) { + return null + } + return {kind: "user", mentraUserId, email, emailVerified, isOrganizationAdmin, organizationCapabilities, scope} + } + case "public": + return parseForwardedScope(own(value, "scope"))?.kind === "public" ? {kind: "public", scope: {kind: "public"}} : null + default: + return null + } +} + +function parseForwardedScope(value: unknown): ForwardedScope | null { + if (!isRecord(value)) return null + switch (own(value, "kind")) { + case "organization": + return {kind: "organization"} + case "person": + return {kind: "person"} + case "public": + return {kind: "public"} + case "workspace": { + const workspaceId = own(value, "workspaceId") + return isId(workspaceId) ? {kind: "workspace", workspaceId} : null + } + default: + return null + } +} + +/** The entries of `value` that are organization capabilities this build knows, or null unless `value` is an array of strings. */ +function parseOrganizationCapabilities(value: unknown): OrganizationCapability[] | null { + if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string")) return null + return value.filter((entry): entry is OrganizationCapability => KNOWN_ORGANIZATION_CAPABILITIES.has(entry)) +} + +type Json = Record + +const KNOWN_ORGANIZATION_CAPABILITIES: ReadonlySet = new Set(ORGANIZATION_CAPABILITIES) + +const isRecord = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value) +const isId = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0 +const isNullableString = (value: unknown): value is string | null => value === null || typeof value === "string" +/** `value[key]` when it is an own property, so a field can never come from a prototype. */ +const own = (value: Json, key: string): unknown => (Object.hasOwn(value, key) ? value[key] : undefined) + +/** A case-insensitive single-value header lookup; a repeated header counts as missing. */ +function headerReader(headers: ForwardedRequest["headers"]): (name: string) => string | undefined { + if (headers instanceof Headers) return (name) => headers.get(name) ?? undefined + const lowered = new Map() + for (const [name, value] of Object.entries(headers)) lowered.set(name.toLowerCase(), value) + return (name) => { + const value = lowered.get(name) + return typeof value === "string" ? value : undefined + } +} diff --git a/cloud-v2/packages/workspace-contract/src/index.test.ts b/cloud-v2/packages/workspace-contract/src/index.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..75dac8c1a184c07345ff6f267cf83134abc406c5 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/index.test.ts @@ -0,0 +1,104 @@ +import {describe, expect, test} from "bun:test" +import {readFileSync} from "node:fs" +import {join} from "node:path" +import * as root from "./index" +import * as server from "./server" + +describe("package entry points", () => { + test("the package root bundles for the browser", async () => { + // Resolved rather than hard-coded so the compiled copy under dist/ finds its own index.js. + const entrypoint = Bun.resolveSync("./index", import.meta.dir) + const result = await Bun.build({entrypoints: [entrypoint], target: "browser"}) + expect(result.logs.filter((log) => log.level === "error").map((log) => log.message)).toEqual([]) + expect(result.success).toBe(true) + }) + + test("the package root exposes only capabilities and types, not the server helpers", () => { + expect(typeof root.capabilitiesForRole).toBe("function") + expect(typeof root.canChangeRole).toBe("function") + expect(root.WORKSPACE_ROLES).toContain("owner") + expect(root.INVALID_TOKEN_ERROR).toBe("invalid_token") + expect(root.SERVICE_UNAUTHORIZED_ERROR).toBe("service_unauthorized") + expect(root.WORKSPACE_NOT_FOUND_ERROR).toBe("workspace_not_found") + expect(root.USER_NOT_FOUND_ERROR).toBe("user_not_found") + expect(root.WORKSPACE_HAS_HOLDS_ERROR).toBe("workspace_has_holds") + expect(root.OWNS_MINIAPPS_HOLD_REASON).toBe("owns_miniapps") + // The portals put holds in words with the same function Core uses for its 409. + expect(typeof root.describeDeletionHold).toBe("function") + expect(typeof root.describeDeletionHolds).toBe("function") + expect(root.FORWARDED_PRINCIPAL_HEADERS).toEqual({ + principal: "x-mentra-principal", + principalSignature: "x-mentra-principal-signature", + }) + expect(root.FORWARDING_SERVICE).toBe("core") + // The license types and their error codes, for the portals and billing alike. + expect(root.STALE_REVISION_ERROR).toBe("stale_revision") + expect(root.OWNER_NOT_FOUND_ERROR).toBe("owner_not_found") + // A license is a workspace's: there is no other owner. + expect(root.LICENSE_OWNER_TYPES).toEqual(["workspace"]) + expect(root.LICENSE_ENDED_REASONS).toEqual(["workspace_deleted", "lapsed", "admin_reset"]) + expect(root.LICENSE_WRITE_ENDED_REASONS).toEqual(["lapsed"]) + // The admin portal's registry page and Core's admin routes share the rule kinds and the limits. + expect(root.ADMIN_REGISTRY_RULE_KINDS).toEqual(["url", "package", "domain", "account"]) + expect(root.ADMIN_REGISTRY_REGISTER_MAX_URLS).toBe(50) + expect(Object.keys(root)).not.toContain("signServiceRequest") + expect(Object.keys(root)).not.toContain("createCoreWorkspaceClient") + // The Fleet UI contract names DOM types, so it has its own subpath and server packages never see it. + expect(Object.keys(root)).not.toContain("FLEET_UI_CONTRACT_VERSION") + expect(Object.keys(root)).not.toContain("PORTAL_MODULE_CONTRACT_VERSION") + for (const name of ["signForwardedPrincipal", "verifyForwardedPrincipal", "parseForwardedPrincipal"]) { + expect(Object.keys(root)).not.toContain(name) + } + }) + + test("a license write may carry a seat request, and a license view never shows one", () => { + const write: root.LicenseWrite = { + licenseId: "01JZWY3V8N0F2E9GQ4T6KXH5RD", + revision: 2, + owner: {type: "workspace", workspaceId: "ws_1"}, + product: "mentra.call.unlimited", + features: [{key: "call.unlimited", packages: ["com.mentra.call"]}], + quantity: 6, + validFrom: "2026-10-01T00:00:00Z", + paidThrough: "2026-11-01T00:00:00Z", + seatRequest: {requestId: "01JZWY3V8N0F2E9GQ4T6KXH5RE", mentraUserId: "mu_1", quantity: 6}, + } + const {licenseId, seatRequest: _seatRequest, assignTo: _assignTo, ...rest} = write + const view: root.LicenseView = {...rest, licenseId, seatsUsed: 6, endedAt: null} + // @ts-expect-error A view leaves the seat request out, as it leaves out the buyer. + const withRequest: root.LicenseView = {...view, seatRequest: write.seatRequest} + // @ts-expect-error + const withBuyer: root.LicenseView = {...view, assignTo: {mentraUserId: "mu_1"}} + expect(write.seatRequest).toEqual({requestId: "01JZWY3V8N0F2E9GQ4T6KXH5RE", mentraUserId: "mu_1", quantity: 6}) + expect([withRequest.licenseId, withBuyer.licenseId]).toEqual([licenseId, licenseId]) + }) + + test("the server entry exposes signing and the Core client", () => { + expect(typeof server.signServiceRequest).toBe("function") + expect(typeof server.verifyServiceRequest).toBe("function") + expect(typeof server.createCoreWorkspaceClient).toBe("function") + expect(typeof server.CoreWorkspaceClientError).toBe("function") + expect(typeof server.signForwardedPrincipal).toBe("function") + expect(typeof server.verifyForwardedPrincipal).toBe("function") + expect(typeof server.parseForwardedPrincipal).toBe("function") + expect(server.FORWARDING_SERVICE).toBe("core") + expect(server.SERVICE_HEADERS.service).toBe("x-mentra-service") + expect(server.INVALID_TOKEN_ERROR).toBe("invalid_token") + expect(server.WORKSPACE_HAS_HOLDS_ERROR).toBe("workspace_has_holds") + expect(typeof server.describeDeletionHolds).toBe("function") + expect(server.STALE_REVISION_ERROR).toBe("stale_revision") + expect(server.OWNER_NOT_FOUND_ERROR).toBe("owner_not_found") + }) + + test("package.json maps the root to the browser-safe entry and ./server to the Node entry", () => { + const manifest = JSON.parse(readFileSync(join(import.meta.dir, "..", "package.json"), "utf8")) + expect(manifest.exports).toEqual({ + ".": "./src/index.ts", + "./server": "./src/server.ts", + "./fleet-ui": "./src/fleet-ui.ts", + "./portal-module-ui": "./src/portal-module-ui.ts", + "./portal-billing": "./src/portal-billing.ts", + "./portal-billing-icons": "./src/portal-billing-icons.ts", + }) + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/index.ts b/cloud-v2/packages/workspace-contract/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f50b4803f6b1fae2cb459c357dbcbb7ca92c4bc --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/index.ts @@ -0,0 +1,10 @@ +// Browser-safe entry point: types, the capability map, deletion holds in words, the license types and the admin +// portal's registry types, with no Node built-ins. +// Servers import the signature helpers and the Core client from "@mentra/workspace-contract/server". +// The Fleet UI and portal module UI contracts name DOM types, so they live at "@mentra/workspace-contract/fleet-ui" +// and "@mentra/workspace-contract/portal-module-ui". +export * from "./capabilities" +export * from "./deletion-holds" +export * from "./licenses" +export * from "./registry-admin" +export * from "./types" diff --git a/cloud-v2/packages/workspace-contract/src/licenses.ts b/cloud-v2/packages/workspace-contract/src/licenses.ts new file mode 100644 index 0000000000000000000000000000000000000000..e093c64b2f6f152684be89c08d30eb85e0afc9a6 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/licenses.ts @@ -0,0 +1,204 @@ +/** + * Licenses: what billing writes into Core (`PUT /api/internal/licenses/:licenseId`, the Store only) and + * what Core shows of them, to billing (`GET /api/internal/licenses`), to people (the workspace routes' + * `GET /:workspaceId/licenses`) and to Organization Admins (the admin portal's `GET /api/admin/licenses`). + * See Core's `docs/licenses.md`. + * + * A license is a quantity of one product for a term, held by a workspace: its Admins and Owners assign the + * seats to members, and a person has a license only through a seat. Core keeps a copy of each license as + * billing last wrote it, and who holds each seat. + */ + +/** The owners a license can have: a workspace, and nothing else. A typed field, so another could be added. */ +export const LICENSE_OWNER_TYPES = ["workspace"] as const + +/** Who holds a license: a workspace. */ +export type LicenseOwner = {type: "workspace"; workspaceId: string} + +/** + * A feature a license unlocks (`call.unlimited`) and the packages it is for (`com.mentra.call`). + * `packages` may be empty: a feature a service checks rather than a miniapp. + */ +export interface LicenseFeature { + key: string + packages: string[] +} + +/** + * One license as billing last computed it. Core applies it only if `revision` is newer than the one it + * has: an equal revision is a repeat (200, nothing changes) and an older one is refused (409 + * {@link STALE_REVISION_ERROR}), so a write may be sent again until Core accepts it, in any order. + */ +export interface LicenseWrite { + /** Billing's id for the license, a ULID. */ + licenseId: string + /** A whole number above zero that grows with every change billing makes. */ + revision: number + /** Never changes for a license. */ + owner: LicenseOwner + /** The product, e.g. `mentra.call.unlimited`. */ + product: string + features: LicenseFeature[] + /** Seats, for the workspace's Admins and Owners to assign. */ + quantity: number + /** RFC 3339, UTC (`Z`). */ + validFrom: string + /** RFC 3339, UTC (`Z`). The features stop after it. */ + paidThrough: string + /** + * The purchase's buyer, by Core user ID, on every write of a subscription billing checked out, so the + * first write to reach Core carries it whatever order they come in. Core gives them one seat only on the + * write that creates the license, and only when they are an active member of the owner workspace, the + * license has a seat to give (`quantity` of 1 or more), and they hold no seat of an in-term license of the + * same product in that workspace; otherwise, and on every later write, it assigns nothing. A Core that + * predates it ignores it. + */ + assignTo?: {mentraUserId: string} + /** + * A person's request for one more seat for themselves: the request's id, their Core user ID, and the + * quantity the license reaches once it is added. Billing names it on the write whose quantity reaches it, + * and on every later write until Core accepts one that carries it. Core decides each request once, on the + * first applied write (a new license or a newer revision) that carries an id it hasn't recorded: it records + * the id whatever it decides, and gives the person one seat only when that write raises the quantity to the + * request's (the quantity Core had, 0 for a new license, is below it, and the write's is at least it), the + * person is an active member of the owner workspace, the license has a seat to give, and they hold no seat + * of an in-term license of the same product in that workspace. Otherwise it assigns nothing, and a repeat or + * an older revision decides nothing. A Core that predates it ignores it. + */ + seatRequest?: {requestId: string; mentraUserId: string; quantity: number} + /** + * Present exactly when the subscription is cancelled and `paidThrough` has passed: the license is over and drops + * off the Licenses page. Core ends it (`endedAt` set, `endedReason` this, its seats freed with reason + * `license_ended`) on the first applied write that carries it, and a repeat of that revision changes nothing. A + * later, newer write without it makes the license stand again (a lapsed license is a fact about its subscription, + * not a one-way door), which a cancelled subscription never does. A Core that predates it ignores it and does not + * answer `ended: true`. Core also ends a license that has not ended when the write repeats the revision it has. + */ + endedReason?: LicenseWriteEndedReason +} + +/** + * Core's answer to a license write that it accepted: whether it changed anything, and the revision it has. + * `ended` is true exactly when the write carried `endedReason` and Core has the license ended by it, so billing + * can tell a Core that ended the license from one that predates the ending, which stores the revision and + * drops the field: billing keeps sending such a write until it is answered with `ended: true`. + */ +export interface LicenseWriteResponse { + applied: boolean + revision: number + ended?: true +} + +/** One seat of a workspace license: the membership that holds it. Times are ISO 8601 UTC. */ +export interface LicenseSeatView { + membershipId: string + mentraUserId: string + assignedAt: string +} + +/** + * A license as Core holds it. `seatsUsed` is how many seats are assigned, and may exceed `quantity` after a + * write lowered it: Core frees no seat on its own. `endedAt` is set when its workspace was deleted (Core then + * refuses further writes for it) or when billing wrote that it lapsed (`LicenseWrite.endedReason`). + * `seats` is present where Core lists who holds them (the workspace routes). + */ +export interface LicenseView extends Omit { + licenseId: string + seatsUsed: number + endedAt: string | null + seats?: LicenseSeatView[] +} + +/** Response of `GET /api/internal/licenses?ownerType=workspace&ownerId=`: one workspace's licenses, ended ones included. */ +export interface LicensesResponse { + licenses: LicenseView[] +} + +/** + * Who holds a license, as the admin portal's list shows it: the workspace, by its name. The name is null when + * Core has no record of the workspace, and the portal then shows the id. + */ +export type AdminLicenseOwner = {type: "workspace"; workspaceId: string; name: string | null} + +/** One license in the admin portal's list. Times are ISO 8601 UTC; `endedAt` and `endedReason` are null while it stands. */ +export interface AdminLicenseView { + licenseId: string + owner: AdminLicenseOwner + product: string + quantity: number + seatsUsed: number + validFrom: string + paidThrough: string + endedAt: string | null + endedReason: LicenseEndedReason | null +} + +/** + * Response of `GET /api/admin/licenses?query=&cursor=`: a page of every license, newest first. `next` is the `cursor` of the page after this one, or null on the last page. + */ +export interface AdminLicensesResponse { + items: AdminLicenseView[] + next: string | null +} + +/** Why a seat was freed, in a `seat.released` event's `after.reason`. */ +export const SEAT_RELEASE_REASONS = [ + "unassigned", + "member_removed", + "member_left", + "account_deleted", + "workspace_deleted", + "license_ended", + "admin_reset", +] as const +export type SeatReleaseReason = (typeof SEAT_RELEASE_REASONS)[number] + +/** + * Why a license ended, in `license.ended`'s `after.reason`: its workspace was deleted (`workspace_deleted`), or its + * subscription was cancelled and its paid term has run out (`lapsed`, which billing writes: see + * {@link LicenseWrite.endedReason}). + */ +export const LICENSE_ENDED_REASONS = ["workspace_deleted", "lapsed", "admin_reset"] as const +export type LicenseEndedReason = (typeof LICENSE_ENDED_REASONS)[number] + +/** The reasons billing can end a license with, in a write: Core ends the rest itself. */ +export const LICENSE_WRITE_ENDED_REASONS = ["lapsed"] as const +export type LicenseWriteEndedReason = (typeof LICENSE_WRITE_ENDED_REASONS)[number] + +/** `error` of the 409 a license write older than the one Core has gets. The body's `revision` is Core's. */ +export const STALE_REVISION_ERROR = "stale_revision" + +/** `error` of the 404 a license write gets when its workspace is deleted or never existed. Retrying cannot help. */ +export const OWNER_NOT_FOUND_ERROR = "owner_not_found" + +/** The most pairs one `POST /api/portal/workspaces/:workspaceId/seat-assignments` takes. */ +export const MAX_SEAT_ASSIGNMENTS = 500 + +/** + * Body of `POST /api/portal/workspaces/:workspaceId/seat-assignments`: seats to give out at once, each a + * license of that workspace and the membership that gets it, for 1 to {@link MAX_SEAT_ASSIGNMENTS} pairs. + * Core assigns all of them or none: a pair that is repeated, or whose membership already holds that + * license's seat, is dropped rather than refused. + */ +export interface SeatAssignmentsRequest { + assignments: {licenseId: string; membershipId: string}[] +} + +/** Response of `POST /api/portal/workspaces/:workspaceId/seat-assignments` (200): every license it touched, as Core now holds it. */ +export interface SeatAssignmentsResponse { + licenses: LicenseView[] +} + +/** + * How short one license is for a bulk assignment: `needed` new seats were asked for and `free` are left. The + * 409 {@link NO_SEATS_AVAILABLE_ERROR} of the bulk route lists one per license that falls short, as `licenses`; + * when it answers, nothing was assigned. + */ +export interface SeatShortfall { + licenseId: string + needed: number + free: number +} + +/** `error` of the 409 an assignment gets when a license has no free seat for it. */ +export const NO_SEATS_AVAILABLE_ERROR = "no_seats_available" diff --git a/cloud-v2/packages/workspace-contract/src/membership-intervals.test.ts b/cloud-v2/packages/workspace-contract/src/membership-intervals.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..61fb3acd988b29d9b9a3074888993cfd96e8342f --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/membership-intervals.test.ts @@ -0,0 +1,257 @@ +import {describe, expect, test} from "bun:test" +import {CoreWorkspaceClientError, createCoreWorkspaceClient} from "./client" +import {SERVICE_HEADERS, verifyServiceRequest} from "./service-signature" +import { + CLIENT_WORKSPACE_ERRORS, + INVITATION_DECLINED_ACTION, + type MembershipInterval, + type MembershipIntervalsResponse, +} from "./types" + +const SECRET = "client-secret" +const BASE = "https://core.test" + +function clientFor(handler: (url: string) => unknown, status = 200) { + const calls: Array<{url: string; method: string; headers: Headers}> = [] + const fetchImpl = async (input: string | URL | Request, init: RequestInit = {}) => { + calls.push({url: String(input), method: init.method ?? "GET", headers: new Headers(init.headers)}) + return new Response(JSON.stringify(handler(String(input))), { + status, + headers: {"content-type": "application/json"}, + }) + } + const client = createCoreWorkspaceClient({ + baseUrl: BASE, + service: "fleet", + secret: SECRET, + fetch: fetchImpl as unknown as typeof fetch, + }) + return {client, calls} +} + +const open = (overrides: Partial = {}): MembershipInterval => { + const interval = { + membershipId: "wm_1", + workspaceId: "ws_1", + mentraUserId: "mu_1", + role: "member" as const, + start: "2026-01-02T03:04:05.000Z", + end: null, + endReason: null, + ...overrides, + } + return {roles: [{role: interval.role, start: interval.start, end: interval.end}], ...interval} +} + +const page = (overrides: Partial = {}): MembershipIntervalsResponse => ({ + lookbackDays: 120, + windowStart: "2026-06-23T00:00:00.000Z", + feedSeq: 412, + intervals: [open(), open({membershipId: "wm_2", end: "2026-09-01T10:00:00.000Z", endReason: "left"})], + next: null, + ...overrides, +}) + +async function expectBadResponse(promise: Promise) { + const error = await promise.then( + () => null, + (caught: unknown) => caught, + ) + expect(error).toBeInstanceOf(CoreWorkspaceClientError) + expect((error as CoreWorkspaceClientError).code).toBe("bad_response") +} + +describe("listMembershipIntervals", () => { + test("reads a page, signed over the exact path and query", async () => { + const body = page({next: "cursor-2"}) + const {client, calls} = clientFor(() => body) + + expect(await client.listMembershipIntervals({after: "cursor-1", limit: 200})).toEqual(body) + + expect(calls).toHaveLength(1) + expect(calls[0]!.method).toBe("GET") + expect(calls[0]!.url).toBe(`${BASE}/api/internal/workspaces/membership-intervals?after=cursor-1&limit=200`) + const url = new URL(calls[0]!.url) + expect( + verifyServiceRequest({ + secrets: [SECRET], + method: "GET", + pathWithQuery: `${url.pathname}${url.search}`, + body: "", + timestampMs: Number(calls[0]!.headers.get(SERVICE_HEADERS.timestamp)), + signature: calls[0]!.headers.get(SERVICE_HEADERS.signature) ?? "", + nowMs: Date.now(), + }), + ).toBe(true) + }) + + test("no cursor starts from the beginning and sends nothing it was not given", async () => { + const {client, calls} = clientFor(() => page()) + await client.listMembershipIntervals({}) + await client.listMembershipIntervals({after: null}) + expect(calls.map(call => call.url.slice(BASE.length))).toEqual([ + "/api/internal/workspaces/membership-intervals", + "/api/internal/workspaces/membership-intervals", + ]) + }) + + test("returns an open interval older than the lookback with its real start and no end", async () => { + const old = open({start: "2025-01-01T00:00:00.000Z"}) + const {client} = clientFor(() => page({intervals: [old]})) + const result = await client.listMembershipIntervals({}) + expect(result.intervals).toEqual([old]) + expect(Date.parse(result.intervals[0]!.start)).toBeLessThan(Date.parse(result.windowStart)) + expect(result.intervals[0]!.end).toBeNull() + }) + + test("returns the role intervals inside each membership interval", async () => { + const promoted = open({ + role: "admin", + roles: [ + {role: "member", start: "2026-01-02T03:04:05.000Z", end: "2026-02-01T00:00:00.000Z"}, + {role: "admin", start: "2026-02-01T00:00:00.000Z", end: null}, + ], + }) + const left = open({ + membershipId: "wm_2", + role: "member", + end: "2026-09-01T00:00:00.000Z", + endReason: "left", + roles: [ + {role: "developer", start: "2026-01-02T03:04:05.000Z", end: "2026-03-01T00:00:00.000Z"}, + {role: "member", start: "2026-03-01T00:00:00.000Z", end: "2026-09-01T00:00:00.000Z"}, + ], + }) + const {client} = clientFor(() => page({intervals: [promoted, left]})) + expect((await client.listMembershipIntervals({})).intervals).toEqual([promoted, left]) + }) + + test("accepts every end reason", async () => { + for (const endReason of ["left", "removed", "workspace_deleted", "account_deleted"] as const) { + const {client} = clientFor(() => page({intervals: [open({end: "2026-09-01T00:00:00.000Z", endReason})]})) + expect((await client.listMembershipIntervals({})).intervals[0]!.endReason).toBe(endReason) + } + }) + + test("refuses a response that is not the documented shape", async () => { + const bad: unknown[] = [ + {...page(), lookbackDays: 0}, + {...page(), lookbackDays: "90"}, + {...page(), windowStart: "not a time"}, + {...page(), feedSeq: -1}, + {...page(), intervals: "none"}, + {...page(), next: 5}, + {...page(), next: ""}, + page({intervals: [open({mentraUserId: ""})]}), + page({intervals: [open({start: "nope"})]}), + page({intervals: [open({endReason: "left"})]}), + page({intervals: [open({end: "2026-09-01T00:00:00.000Z", endReason: null})]}), + page({intervals: [open({end: "2026-09-01T00:00:00.000Z", endReason: "evicted" as never})]}), + page({intervals: [open({start: "2026-09-02T00:00:00.000Z", end: "2026-09-01T00:00:00.000Z", endReason: "left"})]}), + page({intervals: [open({roles: []})]}), + page({intervals: [{...open(), roles: undefined as never}]}), + page({intervals: [open({roles: [{role: "boss" as never, start: "2026-01-02T03:04:05.000Z", end: null}]})]}), + page({intervals: [open({roles: [{role: "member", start: "2025-12-01T00:00:00.000Z", end: null}]})]}), + page({intervals: [open({roles: [{role: "member", start: "2026-01-02T03:04:05.000Z", end: "2026-02-01T00:00:00.000Z"}]})]}), + page({ + intervals: [ + open({ + roles: [ + {role: "member", start: "2026-01-02T03:04:05.000Z", end: null}, + {role: "admin", start: "2026-02-01T00:00:00.000Z", end: null}, + ], + }), + ], + }), + page({ + intervals: [ + open({ + end: "2026-03-01T00:00:00.000Z", + endReason: "left", + roles: [{role: "member", start: "2026-01-02T03:04:05.000Z", end: "2026-04-01T00:00:00.000Z"}], + }), + ], + }), + [], + ] + for (const body of bad) { + const {client} = clientFor(() => body) + await expectBadResponse(client.listMembershipIntervals({})) + } + }) + + test("an interval never ends with the retired reasons", async () => { + for (const endReason of ["replaced", "user_deleted"]) { + const {client} = clientFor(() => + page({intervals: [open({end: "2026-09-01T00:00:00.000Z", endReason: endReason as never})]}), + ) + await expectBadResponse(client.listMembershipIntervals({})) + } + }) + + test("a 403 (a service that may not read history) is forbidden, and a 5xx is core_unavailable", async () => { + const forbidden = clientFor(() => ({error: "forbidden"}), 403) + const err = await forbidden.client.listMembershipIntervals({}).catch((e: unknown) => e) + expect((err as CoreWorkspaceClientError).code).toBe("forbidden") + const down = clientFor(() => ({error: "boom"}), 503) + const err2 = await down.client.listMembershipIntervals({}).catch((e: unknown) => e) + expect((err2 as CoreWorkspaceClientError).code).toBe("core_unavailable") + }) +}) + +describe("client workspace contract constants", () => { + test("the decline action is the change-feed name W1 emits", () => { + expect(INVITATION_DECLINED_ACTION).toBe("invitation.declined") + }) + + test("the codes the Mentra App maps to words", () => { + expect(CLIENT_WORKSPACE_ERRORS).toEqual({ + alreadyInWorkspace: "already_in_workspace", + lastOwner: "last_owner", + invitationExpired: "invitation_expired", + invitationNotFound: "invitation_not_found", + emailUnverified: "email_unverified", + membershipChanged: "membership_changed", + }) + }) +}) + +describe("listWorkspaceMembers", () => { + const member = (overrides: Record = {}) => ({ + membershipId: "wm_1", + mentraUserId: "mu_1", + email: "a@example.test", + name: "Ada", + role: "member" as const, + startedAt: "2026-01-01T00:00:00.000Z", + pending: false, + ...overrides, + }) + + test("reads the workspace's members from its own path, signed", async () => { + const body = {members: [member(), member({membershipId: "wm_2", name: null, pending: true, mentraUserId: null})]} + const {client, calls} = clientFor(() => body) + expect(await client.listWorkspaceMembers("ws_1")).toEqual(body) + expect(calls[0]!.url).toBe(`${BASE}/api/internal/workspaces/workspaces/ws_1/members`) + expect(calls[0]!.headers.get(SERVICE_HEADERS.signature)).toBeTruthy() + }) + + test("a server that predates names is accepted: name is optional", async () => { + const {name: _name, ...bare} = member() + const {client} = clientFor(() => ({members: [bare]})) + expect((await client.listWorkspaceMembers("ws_1")).members).toHaveLength(1) + }) + + test("refuses a response that is not a member list", async () => { + for (const body of [{}, {members: "none"}, {members: [member({role: ""})]}, {members: [member({name: 5})]}, {members: [member({email: 7})]}, {members: [{}]}]) { + const {client} = clientFor(() => body) + await expectBadResponse(client.listWorkspaceMembers("ws_1")) + } + }) + + test("an id is encoded into the path", async () => { + const {client, calls} = clientFor(() => ({members: []})) + await client.listWorkspaceMembers("a/b") + expect(calls[0]!.url).toBe(`${BASE}/api/internal/workspaces/workspaces/a%2Fb/members`) + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/portal-billing-icons.test.ts b/cloud-v2/packages/workspace-contract/src/portal-billing-icons.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9879a13f5d28f9be5f03d3bad7383c12a57a5019 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/portal-billing-icons.test.ts @@ -0,0 +1,95 @@ +import {describe, expect, test} from "bun:test" +import {readFileSync} from "node:fs" +import {dirname, join} from "node:path" +import * as root from "./index" +import {BILLING_ICON_FILE, BILLING_ICON_PATH_PREFIX, billingIconPath} from "./portal-billing-icons" +import * as billing from "./portal-billing" + +const here = import.meta.dir +// Resolved rather than hard-coded so the compiled copy under dist/ finds its own portal-billing-icons.js. +const iconsModule = Bun.resolveSync("./portal-billing-icons", here) + +/** Every specifier `file` names at run time, and those of each file it reaches through a relative import. */ +function runtimeImports(file: string): string[] { + const specifiers = new Set() + const seen = new Set() + const visit = (path: string) => { + if (seen.has(path)) return + seen.add(path) + const loader = path.endsWith(".ts") ? "ts" : "js" + for (const {path: specifier} of new Bun.Transpiler({loader}).scanImports(readFileSync(path, "utf8"))) { + specifiers.add(specifier) + if (specifier.startsWith(".")) visit(Bun.resolveSync(specifier, dirname(path))) + } + } + visit(file) + return [...specifiers] +} + +describe("portal-billing-icons", () => { + test("is the icon rule on its own: the prefix, the file pattern and billingIconPath", () => { + expect(BILLING_ICON_PATH_PREFIX).toBe("/api/portal/billing/ui/icons/") + expect(BILLING_ICON_FILE.test("mentra.call.unlimited.png")).toBe(true) + expect(BILLING_ICON_FILE.test("..")).toBe(false) + expect(billingIconPath("/api/portal/billing/ui/icons/mentra.call.unlimited.png")).toBe( + "/api/portal/billing/ui/icons/mentra.call.unlimited.png", + ) + for (const value of [ + "/api/portal/billing/ui/entry.js", + "/api/portal/billing/ui/icons/", + "/api/portal/billing/ui/icons/..", + "/api/portal/billing/ui/icons/x.png?a=b", + "/api/portal/billing/ui/icons/a b.png", + "https://evil.example/api/portal/billing/ui/icons/x.png", + null, + undefined, + 42, + ]) { + expect([value, billingIconPath(value)]).toEqual([value, null]) + } + }) + + test("portal-billing re-exports the very same values, so every existing import still works", () => { + expect(billing.BILLING_ICON_PATH_PREFIX).toBe(BILLING_ICON_PATH_PREFIX) + expect(billing.BILLING_ICON_FILE).toBe(BILLING_ICON_FILE) + expect(billing.billingIconPath).toBe(billingIconPath) + // And the prefix stays under billing's `ui/` path, which the schemas' module still names. + expect(BILLING_ICON_PATH_PREFIX).toBe(`${billing.BILLING_UI_PATH_PREFIX}icons/`) + }) + + test("is a subpath of the package, not part of the root", () => { + const manifest = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")) + expect(manifest.exports["./portal-billing-icons"]).toBe("./src/portal-billing-icons.ts") + expect(manifest.exports["./portal-billing"]).toBe("./src/portal-billing.ts") + expect(Object.keys(root)).not.toContain("billingIconPath") + }) + + test("imports no zod, and nothing that does", () => { + // What it names at run time, and what the files it reaches name in turn (a harmless import would be fine; zod, or + // the module that builds the schemas, would not). + const specifiers = runtimeImports(iconsModule) + expect(specifiers.filter((specifier) => /^zod(\/|$)/.test(specifier))).toEqual([]) + expect(specifiers.filter((specifier) => /portal-billing(?!-icons)/.test(specifier))).toEqual([]) + const manifest = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")) + // The package depends on zod for its schemas; this file isn't one of the places that uses it. + expect(manifest.dependencies.zod).toBeDefined() + expect(readFileSync(iconsModule, "utf8")).not.toMatch(/from\s*["']zod["']|require\(\s*["']zod["']\s*\)/) + }) + + test("bundles for the browser without zod's code", () => { + // Separate `bun build`s, as portal-billing's own bundle test does. A word in a comment is not code: look for what + // zod's code defines, and check the same markers are there in the bundle of the module that does use zod. + const bundle = (entry: string) => { + const result = Bun.spawnSync([process.execPath, "build", entry, "--target=browser"], {stdout: "pipe", stderr: "pipe"}) + expect(result.stderr.toString()).not.toContain("error") + expect(result.exitCode).toBe(0) + return result.stdout.toString() + } + const markers = ["ZodError", "ZodIssueCode", "invalid_type"] + const withSchemas = bundle(Bun.resolveSync("./portal-billing", here)) + for (const marker of markers) expect([marker, withSchemas.includes(marker)]).toEqual([marker, true]) + const icons = bundle(iconsModule) + expect(icons).toContain("billingIconPath") + for (const marker of markers) expect([marker, icons.includes(marker)]).toEqual([marker, false]) + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/portal-billing-icons.ts b/cloud-v2/packages/workspace-contract/src/portal-billing-icons.ts new file mode 100644 index 0000000000000000000000000000000000000000..95f71105bd525f5c3dceeffa3f2a12a43e81764d --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/portal-billing-icons.ts @@ -0,0 +1,27 @@ +/** + * The rule for a product icon's address, on its own. `portal-billing` re-exports it, but that module builds the + * contract's zod schemas, and importing it puts zod in a bundle. A screen that only draws a product's icon (the + * Members list is in the admin portal too) imports this one instead, which needs nothing: no zod, and no other + * module. Import it from `@mentra/workspace-contract/portal-billing-icons`. + */ + +/** Where billing serves product icons, under its `ui/`. */ +export const BILLING_ICON_PATH_PREFIX = "/api/portal/billing/ui/icons/" + +/** + * A product icon's file: letters, digits, `.`, `_` and `-`, 1 to 255 of them, and not only dots (`.` and `..` + * are directories). Nothing else can lead out of the icons directory or into a style or a script. + */ +export const BILLING_ICON_FILE = /^(?!\.+$)[A-Za-z0-9._-]{1,255}$/ + +/** + * The icon path billing sent, or null when it isn't `/api/portal/billing/ui/icons/` with a file + * {@link BILLING_ICON_FILE} allows: no query, fragment, slash, quote, parenthesis or space, and nothing else under + * `ui/` (the legacy `ui/entry.js` included). The portal shows an icon only from there, so its content security + * policy holds, no page loads another origin's address, and the path is one Core serves to everyone; a + * product with no acceptable icon gets a letter tile. + */ +export function billingIconPath(value: unknown): string | null { + if (typeof value !== "string" || !value.startsWith(BILLING_ICON_PATH_PREFIX)) return null + return BILLING_ICON_FILE.test(value.slice(BILLING_ICON_PATH_PREFIX.length)) ? value : null +} diff --git a/cloud-v2/packages/workspace-contract/src/portal-billing.test.ts b/cloud-v2/packages/workspace-contract/src/portal-billing.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2df2ae4be0df80328460b83d5d30f997aafcc9f --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/portal-billing.test.ts @@ -0,0 +1,923 @@ +import {describe, expect, test} from "bun:test" +import {readFileSync} from "node:fs" +import {join} from "node:path" +import * as root from "./index" +import * as portalBilling from "./portal-billing" +import type {MemberView} from "./index" +import { + BILLING_ERROR_CODES, + BillingActionSchema, + BillingCatalogSchema, + BillingStatusSchema, + BillingTotalSchema, + BuySchema, + CatalogEntrySchema, + CatalogFeatureSchema, + FallbackPriceSchema, + HostedUrlSchema, + KNOWN_ACTION_KINDS, + KNOWN_LICENSE_STATUSES, + KNOWN_TAX, + LicenseBillingSchema, + MoneySchema, + OfferSchema, + PerSeatPriceSchema, + PriceSchema, + PurchaseAnswerSchema, + PurchaseRequestSchema, + PublicProductSchema, + PurchaseStatusSchema, + SessionAnswerSchema, + SessionRequestSchema, + TestModeSchema, + billingIconPath, + isPerSeat, + type BillingCatalog, + type BillingStatus, + type BillingTotal, + type Buy, + type CatalogFeature, + type FallbackPrice, + type Offer, + type PerSeatPrice, + type Price, + type PurchaseStatus, + type TestMode, +} from "./portal-billing" + +const callUnlimited = { + product: "mentra.call.unlimited", + name: "Mentra Call Unlimited", + shortName: "Call Unlimited", + description: "Unlimited calls and call summaries in Mentra Call.", + icon: "/api/portal/billing/ui/icons/mentra.call.unlimited.png", + features: [{key: "call.unlimited", name: "Unlimited calls", appName: "Mentra Call"}], + offer: { + price: { + scheme: "per_seat", + unit: {amountMinor: 2900, currency: "USD"}, + recurrence: {interval: "month", count: 1}, + }, + tax: "excluded", + buy: {minSeats: 1, maxSeats: 500}, + }, +} + +const notesPro = { + product: "mentra.notes.pro", + name: "Mentra Notes Pro", + description: "Searchable notes and summaries across everything you say.", + icon: null, + features: [ + {key: "notes.pro", name: "Pro notes", appName: "Mentra Notes"}, + {key: "notes.export", name: "Export"}, + ], + offer: { + price: { + scheme: "per_seat", + unit: {amountMinor: 1500, currency: "USD"}, + recurrence: {interval: "month", count: 1}, + }, + tax: "excluded", + buy: null, + }, +} + +const fleetSuite = { + product: "mentra.fleet.suite", + name: "Fleet Suite", + description: "Device management for a fleet of glasses.", + icon: "/api/portal/billing/ui/icons/mentra.fleet.suite.svg", + features: [], + offer: { + price: {scheme: "tiered", fallbackLabel: "From $10 per seat a month"}, + tax: "none", + buy: {minSeats: 1}, + }, +} + +const catalogDocument = { + locale: "en", + products: [callUnlimited, notesPro, fleetSuite], +} + +const addSeats = {kind: "add_seats", fallbackLabel: "Add seats"} +const changeSeats = {kind: "change_seats", fallbackLabel: "Change seats"} +const cancel = {kind: "cancel", fallbackLabel: "Cancel"} +const renew = {kind: "renew", fallbackLabel: "Renew"} +const updatePayment = {kind: "update_payment", fallbackLabel: "Update payment method"} +const completePayment = {kind: "complete_payment", fallbackLabel: "Complete payment", returns: false} +const billingAndInvoices = {kind: "billing_and_invoices", fallbackLabel: "Billing & invoices"} + +const perSeat = { + scheme: "per_seat", + unit: {amountMinor: 2900, currency: "USD"}, + recurrence: {interval: "month", count: 1}, +} + +const activeLicense = { + licenseId: "01JZWY3V8N0F2E9GQ4T6KXH5RD", + product: "mentra.call.unlimited", + status: "active", + fallbackStatusLabel: "Active", + renewsAt: "2026-11-01T00:00:00Z", + price: perSeat, + quantity: 5, + total: {amountMinor: 14500, currency: "USD"}, + tax: "excluded", + actions: [addSeats, changeSeats, cancel], +} + +const endingLicense = { + licenseId: "01JZWY3V8N0F2E9GQ4T6KXH5RE", + product: "mentra.notes.pro", + status: "ending", + fallbackStatusLabel: "Ending", + endsAt: "2026-11-15T09:30:00+01:00", + price: {...perSeat, unit: {amountMinor: 1500, currency: "USD"}}, + quantity: 3, + total: {amountMinor: 4500, currency: "USD"}, + tax: "excluded", + actions: [renew], +} + +const pastDueLicense = { + licenseId: "01JZWY3V8N0F2E9GQ4T6KXH5RF", + product: "mentra.fleet.suite", + status: "past_due", + fallbackStatusLabel: "Payment failed", + renewsAt: "2026-10-18T00:00:00.000Z", + seatsStopAt: "2026-10-25T00:00:00Z", + price: {scheme: "tiered", fallbackLabel: "From $10 per seat a month"}, + quantity: 8, + total: null, + tax: "none", + actions: [addSeats, changeSeats, updatePayment, completePayment], +} + +const statusDocument = { + locale: "en", + licenses: [activeLicense, endingLicense, pastDueLicense], + total: { + amount: {amountMinor: 14500, currency: "USD"}, + recurrence: {interval: "month", count: 1}, + tax: "excluded", + licenseCount: 1, + }, + actions: [billingAndInvoices], + testMode: {cardNumber: "4242424242424242", environment: "STAGING"}, + purchase: { + purchaseId: "pur_01JZWY3V8N0F2E9GQ4T6KXH5RG", + status: "ready", + product: "mentra.call.unlimited", + quantity: 5, + paid: true, + licenseId: "01JZWY3V8N0F2E9GQ4T6KXH5RD", + }, +} + +/** A deep copy that a test can edit without touching the shared documents. */ +function copy(value: T): T { + return JSON.parse(JSON.stringify(value)) as T +} + +describe("the spec's example documents", () => { + test("a catalog with three products parses and keeps its values", () => { + const parsed: BillingCatalog = BillingCatalogSchema.parse(catalogDocument) + expect(parsed).toEqual(catalogDocument as unknown as BillingCatalog) + expect(parsed.products.map((product) => product.product)).toEqual([ + "mentra.call.unlimited", + "mentra.notes.pro", + "mentra.fleet.suite", + ]) + }) + + test("a status with active, ending and past_due licenses, a total, test mode and a purchase parses", () => { + const parsed: BillingStatus = BillingStatusSchema.parse(statusDocument) + expect(parsed).toEqual(statusDocument as unknown as BillingStatus) + expect(parsed.licenses.map((license) => license.status)).toEqual(["active", "ending", "past_due"]) + expect(parsed.total?.licenseCount).toBe(1) + expect(parsed.testMode?.cardNumber).toBe("4242424242424242") + expect(parsed.purchase?.status).toBe("ready") + }) + + test("a status with nothing in it parses: no licenses, total, test mode or purchase", () => { + const parsed = BillingStatusSchema.parse({ + locale: "en-GB", + licenses: [], + total: null, + actions: [], + testMode: null, + purchase: null, + }) + expect(parsed.licenses).toEqual([]) + expect(parsed.total).toBeNull() + expect(parsed.purchase).toBeNull() + }) + + test("a purchase that is still processing has no license yet", () => { + const document = copy(statusDocument) + document.purchase = {...document.purchase, status: "processing", paid: false, licenseId: null as unknown as string} + const parsed = BillingStatusSchema.parse(document) + expect(parsed.purchase).toMatchObject({status: "processing", paid: false, licenseId: null}) + }) + + test("an unknown purchase status parses and keeps its value", () => { + const document = copy(statusDocument) + document.purchase.status = "refunded" + const parsed = BillingStatusSchema.parse(document) + expect(parsed.purchase).toMatchObject({status: "refunded", licenseId: "01JZWY3V8N0F2E9GQ4T6KXH5RD"}) + }) + + test("every known action kind parses, with returns only when billing sends it", () => { + for (const action of [addSeats, changeSeats, cancel, renew, updatePayment, completePayment, billingAndInvoices]) { + expect(BillingActionSchema.parse(action)).toEqual(action) + } + expect(BillingActionSchema.parse(completePayment).returns).toBe(false) + expect("returns" in BillingActionSchema.parse(cancel)).toBe(false) + }) +}) + +describe("values the contract does not know", () => { + test("an unknown license status parses and keeps its value", () => { + const document = copy(statusDocument) + document.licenses[0]!.status = "paused" + document.licenses[0]!.fallbackStatusLabel = "Paused" + const parsed = BillingStatusSchema.parse(document) + expect(parsed.licenses[0]).toMatchObject({status: "paused", fallbackStatusLabel: "Paused"}) + expect(KNOWN_LICENSE_STATUSES as readonly string[]).not.toContain("paused") + }) + + test("an unknown action kind parses and keeps its value, on a license and on the account", () => { + const document = copy(statusDocument) + const transfer = {kind: "transfer_ownership", fallbackLabel: "Transfer ownership"} + document.licenses[0]!.actions.push(transfer as never) + document.actions.push(transfer as never) + const parsed = BillingStatusSchema.parse(document) + expect(parsed.licenses[0]!.actions.at(-1)).toEqual(transfer) + expect(parsed.actions.at(-1)).toEqual(transfer) + expect(KNOWN_ACTION_KINDS as readonly string[]).not.toContain("transfer_ownership") + }) + + test("an unknown tax value parses and keeps its value, on a license, the total and an offer", () => { + const status = copy(statusDocument) + status.licenses[0]!.tax = "reverse_charge" + status.total.tax = "reverse_charge" + const parsedStatus = BillingStatusSchema.parse(status) + expect(parsedStatus.licenses[0]!.tax).toBe("reverse_charge") + expect(parsedStatus.total!.tax).toBe("reverse_charge") + + const catalog = copy(catalogDocument) + catalog.products[0]!.offer!.tax = "reverse_charge" + expect(BillingCatalogSchema.parse(catalog).products[0]!.offer!.tax).toBe("reverse_charge") + expect(KNOWN_TAX as readonly string[]).not.toContain("reverse_charge") + }) + + test("an unknown price scheme with a fallbackLabel parses and keeps its value", () => { + const price = {scheme: "metered", fallbackLabel: "$0.02 per minute"} + expect(PriceSchema.parse(price)).toEqual(price) + const document = copy(statusDocument) + document.licenses[0]!.price = price as never + document.licenses[0]!.total = null as never + expect(BillingStatusSchema.parse(document).licenses[0]!.price).toEqual(price) + }) + + test("a per_seat price that is malformed but has a fallbackLabel falls back to its label", () => { + const price = {scheme: "per_seat", fallbackLabel: "$29 per seat a month", unit: {amountMinor: -1, currency: "USD"}} + const parsed = PriceSchema.parse(price) + expect(parsed).toEqual({scheme: "per_seat", fallbackLabel: "$29 per seat a month"}) + expect(isPerSeat(parsed)).toBe(false) + }) + + test("the known constants list what the spec names", () => { + expect(KNOWN_LICENSE_STATUSES).toEqual(["active", "ending", "past_due", "processing", "incomplete"]) + expect(KNOWN_ACTION_KINDS).toEqual([ + "add_seats", + "change_seats", + "cancel", + "renew", + "update_payment", + "complete_payment", + "billing_and_invoices", + ]) + expect(KNOWN_TAX).toEqual(["excluded", "included", "none"]) + }) + + test("an unknown field is stripped, at every level", () => { + const catalog = copy(catalogDocument) as Record & {products: Record[]} + catalog.futureField = "x" + catalog.products[0]!.futureField = "x" + catalog.products[0]!.features[0].futureField = "x" + catalog.products[0]!.offer.futureField = "x" + catalog.products[0]!.offer.price.futureField = "x" + catalog.products[0]!.offer.price.unit.futureField = "x" + catalog.products[0]!.offer.price.recurrence.futureField = "x" + catalog.products[0]!.offer.buy.futureField = "x" + expect(BillingCatalogSchema.parse(catalog)).toEqual(catalogDocument as unknown as BillingCatalog) + + const status = copy(statusDocument) as Record + status.futureField = "x" + status.licenses[0].futureField = "x" + status.licenses[0].actions[0].futureField = "x" + status.total.futureField = "x" + status.testMode.futureField = "x" + status.purchase.futureField = "x" + expect(BillingStatusSchema.parse(status)).toEqual(statusDocument as unknown as BillingStatus) + }) +}) + +describe("a catalog entry", () => { + test("without an offer, display content only, parses and has none", () => { + const {offer: _offer, ...display} = callUnlimited + const parsed = CatalogEntrySchema.parse(display) + expect(parsed).toEqual(display as never) + expect("offer" in parsed).toBe(false) + }) + + test("without a shortName or an appName parses", () => { + const parsed = CatalogEntrySchema.parse(notesPro) + expect(parsed.shortName).toBeUndefined() + expect(parsed.features[1]!.appName).toBeUndefined() + }) + + test("an offer's buy is null where the owner can't buy now, and maxSeats is optional", () => { + expect(CatalogEntrySchema.parse(notesPro).offer!.buy).toBeNull() + expect(CatalogEntrySchema.parse(fleetSuite).offer!.buy).toEqual({minSeats: 1}) + }) + + test("an owner type list from an older Store is stripped, and never fails the entry", () => { + for (const ownerTypes of [["workspace", "person"], ["team"], [], [3], "workspace"]) { + const parsed = CatalogEntrySchema.parse({...callUnlimited, ownerTypes}) + expect("ownerTypes" in parsed).toBe(false) + expect(parsed).toEqual(callUnlimited as never) + } + }) + + test("a catalog whose entries still carry ownerTypes parses, and keeps the rest", () => { + const catalog = copy(catalogDocument) + for (const product of catalog.products) (product as Record).ownerTypes = ["workspace", "person"] + const parsed = BillingCatalogSchema.parse(catalog) + expect(parsed.products.map((product) => "ownerTypes" in product)).toEqual([false, false, false]) + expect(parsed.products.map((product) => product.product)).toEqual(catalog.products.map((product) => product.product)) + }) + + test("a buy from an older Store with defaultSeats is stripped to its limits", () => { + const old = {...callUnlimited, offer: {...callUnlimited.offer, buy: {minSeats: 1, maxSeats: 500, defaultSeats: 5}}} + const parsed = CatalogEntrySchema.parse(old) + expect(parsed.offer!.buy).toEqual({minSeats: 1, maxSeats: 500}) + expect(BuySchema.parse({minSeats: 2, defaultSeats: 9})).toEqual({minSeats: 2}) + }) + + test("the owner-type helpers are gone: a workspace is the only owner", () => { + expect("KNOWN_OWNER_TYPES" in portalBilling).toBe(false) + expect("isKnownOwnerType" in portalBilling).toBe(false) + }) +}) + +describe("prices and money", () => { + test("a per_seat price without a unit and without a fallbackLabel fails", () => { + expect(PriceSchema.safeParse({scheme: "per_seat", recurrence: {interval: "month", count: 1}}).success).toBe(false) + expect(PriceSchema.safeParse({scheme: "per_seat"}).success).toBe(false) + const document = copy(statusDocument) + delete (document.licenses[0]!.price as any).unit + expect(BillingStatusSchema.safeParse(document).success).toBe(false) + }) + + test("a per_seat price without a recurrence and without a fallbackLabel fails", () => { + expect(PriceSchema.safeParse({scheme: "per_seat", unit: {amountMinor: 2900, currency: "USD"}}).success).toBe(false) + }) + + test("a price with neither a unit nor a fallbackLabel, whatever its scheme, fails", () => { + expect(PriceSchema.safeParse({scheme: "metered"}).success).toBe(false) + expect(PriceSchema.safeParse({fallbackLabel: "From $10"}).success).toBe(false) + }) + + test("a recurrence needs a known interval and a count of at least one", () => { + const base = {scheme: "per_seat", unit: {amountMinor: 100, currency: "EUR"}} + expect(PriceSchema.safeParse({...base, recurrence: {interval: "year", count: 1}}).success).toBe(true) + expect(PriceSchema.safeParse({...base, recurrence: {interval: "fortnight", count: 1}}).success).toBe(false) + expect(PriceSchema.safeParse({...base, recurrence: {interval: "month", count: 0}}).success).toBe(false) + expect(PriceSchema.safeParse({...base, recurrence: {interval: "month", count: 1.5}}).success).toBe(false) + }) + + test("amountMinor -1 or 1.5 fails, and zero and a large whole number pass", () => { + expect(MoneySchema.safeParse({amountMinor: -1, currency: "USD"}).success).toBe(false) + expect(MoneySchema.safeParse({amountMinor: 1.5, currency: "USD"}).success).toBe(false) + expect(MoneySchema.safeParse({amountMinor: Number.NaN, currency: "USD"}).success).toBe(false) + expect(MoneySchema.safeParse({amountMinor: Number.MAX_SAFE_INTEGER + 1, currency: "USD"}).success).toBe(false) + expect(MoneySchema.safeParse({amountMinor: "100", currency: "USD"}).success).toBe(false) + expect(MoneySchema.parse({amountMinor: 0, currency: "USD"})).toEqual({amountMinor: 0, currency: "USD"}) + expect(MoneySchema.safeParse({amountMinor: Number.MAX_SAFE_INTEGER, currency: "JPY"}).success).toBe(true) + }) + + test("a currency other than three uppercase letters fails, such as usd", () => { + for (const currency of ["usd", "Usd", "US", "USDD", "U$D", "US1", " USD", ""]) { + expect(MoneySchema.safeParse({amountMinor: 100, currency}).success).toBe(false) + } + expect(MoneySchema.safeParse({amountMinor: 100, currency: "USD"}).success).toBe(true) + }) + + test("a bad amount anywhere fails the whole document", () => { + const status = copy(statusDocument) + status.licenses[0]!.total!.amountMinor = -1 + expect(BillingStatusSchema.safeParse(status).success).toBe(false) + const catalog = copy(catalogDocument) as {products: {offer: {price: {unit: {currency: string}}}}[]} + catalog.products[0]!.offer.price.unit.currency = "usd" + expect(BillingCatalogSchema.safeParse(catalog).success).toBe(false) + }) + + test("isPerSeat narrows a per_seat price and nothing else", () => { + const seat: Price = PriceSchema.parse(perSeat) + expect(isPerSeat(seat)).toBe(true) + if (isPerSeat(seat)) { + expect(seat.unit.amountMinor).toBe(2900) + expect(seat.recurrence.interval).toBe("month") + } + expect(isPerSeat(PriceSchema.parse({scheme: "tiered", fallbackLabel: "From $10"}))).toBe(false) + expect(isPerSeat(PriceSchema.parse({scheme: "per_seat", fallbackLabel: "$29 a seat"}))).toBe(false) + }) +}) + +describe("dates", () => { + const withDate = (field: "renewsAt" | "endsAt" | "seatsStopAt", value: unknown) => { + const document = copy(statusDocument) as Record + document.licenses[0][field] = value + return BillingStatusSchema.safeParse(document) + } + + test("a date without an offset fails", () => { + expect(withDate("renewsAt", "2026-11-01T00:00:00").success).toBe(false) + expect(withDate("endsAt", "2026-11-01T00:00:00.000").success).toBe(false) + expect(withDate("seatsStopAt", "2026-11-01").success).toBe(false) + expect(withDate("renewsAt", "tomorrow").success).toBe(false) + expect(withDate("renewsAt", "").success).toBe(false) + expect(withDate("renewsAt", 1_790_000_000_000).success).toBe(false) + }) + + test("a date with Z or an offset passes, with or without fractional seconds", () => { + for (const value of [ + "2026-11-01T00:00:00Z", + "2026-11-01T00:00:00.123Z", + "2026-11-01T09:30:00+01:00", + "2026-11-01T09:30:00-07:00", + "2026-11-01T09:30:00.5+05:30", + ]) { + expect(withDate("renewsAt", value).success).toBe(true) + } + }) + + test("a date that is not on the calendar fails", () => { + expect(withDate("renewsAt", "2026-02-30T00:00:00Z").success).toBe(false) + expect(withDate("renewsAt", "2026-13-01T00:00:00Z").success).toBe(false) + }) +}) + +describe("billingIconPath", () => { + const icons = "/api/portal/billing/ui/icons/" + + test("keeps /api/portal/billing/ui/icons/ for a file of letters, digits, dots, underscores and hyphens", () => { + expect(billingIconPath("/api/portal/billing/ui/icons/mentra.call.unlimited.png")).toBe( + "/api/portal/billing/ui/icons/mentra.call.unlimited.png", + ) + for (const file of ["mentra.fleet.suite.svg", "Call_Unlimited-2.PNG", "x", "a-b_c.1.2.webp", ".hidden", "x..png"]) { + expect([file, billingIconPath(`${icons}${file}`)]).toEqual([file, `${icons}${file}`]) + } + expect(billingIconPath(`${icons}${"a".repeat(255)}`)).toBe(`${icons}${"a".repeat(255)}`) + }) + + test("is null for an address that is not billing's own icon path", () => { + for (const value of [ + "https://files.example.com/x.png", + "http://localhost:3000/api/portal/billing/ui/icons/x.png", + "//host/x.png", + "//host/api/portal/billing/ui/icons/x.png", + "/api/portal/other/ui/x.png", + "/api/portal/other/ui/icons/x.png", + "/api/portal/billing/uix/icons/x.png", + "/api/portal/billing/ui/icon/x.png", + "/API/PORTAL/BILLING/UI/ICONS/x.png", + "icons/x.png", + "javascript:alert(1)", + "data:image/png;base64,AAAA", + "", + ]) { + expect([value, billingIconPath(value)]).toEqual([value, null]) + } + }) + + test("is null for the rest of ui/, the legacy entry.js included, and for ui/icons/ with no file", () => { + for (const value of [ + "/api/portal/billing/ui", + "/api/portal/billing/ui/", + "/api/portal/billing/ui/entry.js", + "/api/portal/billing/ui/entry.js?v=1", + "/api/portal/billing/ui/x.png", + "/api/portal/billing/ui/icons", + "/api/portal/billing/ui/icons/", + "/api/portal/billing/ui/icons/?x.png", + ]) { + expect([value, billingIconPath(value)]).toEqual([value, null]) + } + }) + + test("is null for a file with a character outside letters, digits, dots, underscores and hyphens", () => { + for (const file of [ + 'a"b.png', + "a'b.png", + "a(1).png", + "a)b.png", + "a b.png", + "a\tb.png", + "a\nb.png", + "a\u0000b.png", + "a\\b.png", + "a;b.png", + "a,b.png", + "a&b.png", + "a=b.png", + "a+b.png", + "a@b.png", + "a.png", + "a{b}.png", + "a:b.png", + "é.png", + "x.png?v=2", + "x.png#frag", + "%2e%2e", + "%2e%2e%2fme", + "x%2epng", + "a%20b.png", + "sub/x.png", + "sub/../x.png", + "../x.png", + "../../me", + "..", + ".", + "...", + "x.png/", + "/x.png", + "x.png\n", + "a".repeat(256), + ]) { + expect([file, billingIconPath(`${icons}${file}`)]).toEqual([file, null]) + } + }) + + test("is null for a value that is not a string", () => { + for (const value of [null, undefined, 3, {}, []]) { + expect(billingIconPath(value)).toBeNull() + } + }) + + test("applies in a catalog entry: another address parses to null and does not fail the entry", () => { + for (const icon of [ + "https://files.example.com/x.png", + "//host/x.png", + "/api/portal/other/ui/x.png", + "/api/portal/billing/ui/entry.js", + "/api/portal/billing/ui/icons/", + "/api/portal/billing/ui/icons/a b.png", + ]) { + const parsed = CatalogEntrySchema.parse({...callUnlimited, icon}) + expect([icon, parsed.icon]).toEqual([icon, null]) + expect(parsed.name).toBe(callUnlimited.name) + } + expect(CatalogEntrySchema.parse(callUnlimited).icon).toBe("/api/portal/billing/ui/icons/mentra.call.unlimited.png") + expect(CatalogEntrySchema.parse({...callUnlimited, icon: null}).icon).toBeNull() + }) +}) + +describe("hosted URLs", () => { + const accepted = [ + "https://billing.example.com/p/session/x", + "https://checkout.example.com/c/pay/a1B2c3#fragment", + "https://billing.example.com:8443/x?y=1", + "HTTPS://billing.example.com/x", + "http://localhost:4010/x", + "http://localhost/x", + "http://127.0.0.1:4010/x?session=1", + "http://127.0.0.1/x", + ] + const refused = [ + "javascript:alert(1)", + "JavaScript:alert(1)", + "java\nscript:alert(1)", + "http://example.com", + "http://example.com/x", + "http://localhost.evil.com/x", + "http://127.0.0.1.evil.com/x", + "http://evil.com@localhost/x", + "http://localhost@evil.com/x", + "https://user:pass@billing.example.com/x", + "http://[::1]:4010/x", + "http://0.0.0.0/x", + "http://127.0.0.2/x", + "data:text/html,", + "data:text/plain;base64,AAAA", + "blob:https://billing.example.com/3b3f", + "file:///etc/passwd", + "ftp://billing.example.com/x", + "//billing.example.com/x", + "/p/session/x", + "billing.example.com/x", + "https://", + "", + ] + + test("https passes, and http passes only to localhost or 127.0.0.1", () => { + for (const url of accepted) { + expect([url, HostedUrlSchema.safeParse(url).success]).toEqual([url, true]) + } + }) + + test("javascript:, data: and other http or non-web addresses fail", () => { + for (const url of refused) { + expect([url, HostedUrlSchema.safeParse(url).success]).toEqual([url, false]) + } + }) + + test("a value that is not a string fails", () => { + for (const value of [null, undefined, 3, {}, ["https://billing.example.com/x"]]) { + expect(HostedUrlSchema.safeParse(value).success).toBe(false) + } + }) + + test("returns the canonical address, the one the browser follows", () => { + for (const url of accepted) { + expect([url, HostedUrlSchema.parse(url)]).toEqual([url, new URL(url).href]) + } + expect(HostedUrlSchema.parse("https://billing.example.com")).toBe("https://billing.example.com/") + expect(HostedUrlSchema.parse("HTTPS://Billing.Example.COM/Path")).toBe("https://billing.example.com/Path") + expect(HostedUrlSchema.parse("https://billing.example.com:443/x")).toBe("https://billing.example.com/x") + expect(HostedUrlSchema.parse("https://billing.example.com/p/session/x?a=1#frag")).toBe( + "https://billing.example.com/p/session/x?a=1#frag", + ) + }) + + test("padding the browser ignores is gone from what is returned", () => { + for (const padded of [ + " https://billing.example.com/p/session/x", + "https://billing.example.com/p/session/x ", + " https://billing.example.com/p/session/x ", + "\thttps://billing.example.com/p/session/x\n", + "\n\r https://billing.example.com/p/session/x \r\n", + "\u0001https://billing.example.com/p/session/x\u0001", + ]) { + expect([padded, HostedUrlSchema.parse(padded)]).toEqual([padded, "https://billing.example.com/p/session/x"]) + } + expect(HostedUrlSchema.parse(" http://localhost:4010/x ")).toBe("http://localhost:4010/x") + }) + + test("tabs and newlines inside the address, which the browser drops, are gone from what is returned", () => { + for (const [input, expected] of [ + ["https://billing.example.com/p/ses\tsion/x", "https://billing.example.com/p/session/x"], + ["ht\ttps://billing.example.com/x", "https://billing.example.com/x"], + ["https://billing.exa\nmple.com/x", "https://billing.example.com/x"], + ["https://billing.example.com/x?a=\r\n1", "https://billing.example.com/x?a=1"], + ["http://local\thost:4010/x", "http://localhost:4010/x"], + ["http://127.0.\t0.1/x", "http://127.0.0.1/x"], + ] as const) { + expect([input, HostedUrlSchema.parse(input)]).toEqual([input, expected]) + } + }) + + test("a tab or padding cannot turn a refused address into an accepted one, nor the other way", () => { + for (const input of [ + " javascript:alert(1)", + "\tjava\tscript:alert(1)", + " http://example.com/x ", + "http://local\thost.evil.com/x", + "http://127.0.0.\t1.evil.com/x", + "https://user:pass@billing.example.com/x ", + " data:text/html,x", + ]) { + expect([input, HostedUrlSchema.safeParse(input).success]).toEqual([input, false]) + } + }) + + test("the session answer and the purchase answer check the url the same way", () => { + for (const schema of [SessionAnswerSchema, PurchaseAnswerSchema]) { + expect(schema.parse({url: "https://billing.example.com/p/session/x"})).toEqual({ + url: "https://billing.example.com/p/session/x", + }) + expect(schema.parse({url: "http://localhost:4010/x"})).toEqual({url: "http://localhost:4010/x"}) + expect(schema.parse({url: " https://billing.example.com/p/session/x "})).toEqual({ + url: "https://billing.example.com/p/session/x", + }) + expect(schema.safeParse({url: "javascript:alert(1)"}).success).toBe(false) + expect(schema.safeParse({url: "http://example.com"}).success).toBe(false) + expect(schema.safeParse({url: "data:text/html,x"}).success).toBe(false) + expect(schema.safeParse({}).success).toBe(false) + expect(schema.parse({url: "https://billing.example.com/x", futureField: "x"})).toEqual({ + url: "https://billing.example.com/x", + }) + } + }) +}) + +describe("requests", () => { + test("a purchase request names a product, seats and a locale", () => { + const body = {product: "mentra.call.unlimited", seats: 5, locale: "en-US"} + expect(PurchaseRequestSchema.parse(body)).toEqual(body) + expect(PurchaseRequestSchema.safeParse({...body, seats: 2.5}).success).toBe(false) + expect(PurchaseRequestSchema.safeParse({...body, seats: "5"}).success).toBe(false) + expect(PurchaseRequestSchema.safeParse({...body, product: undefined}).success).toBe(false) + expect(PurchaseRequestSchema.safeParse({...body, locale: undefined}).success).toBe(false) + }) + + test("a session request names an action and a locale, and may name a license and seats", () => { + expect(SessionRequestSchema.parse({action: "billing_and_invoices", locale: "en"})).toEqual({ + action: "billing_and_invoices", + locale: "en", + }) + const full = {action: "add_seats", licenseId: "01JZWY3V8N0F2E9GQ4T6KXH5RD", seats: 3, locale: "en-GB"} + expect(SessionRequestSchema.parse(full)).toEqual(full) + // An action Core doesn't know is still a string: billing answers 400 unknown_action. + expect(SessionRequestSchema.parse({action: "transfer_ownership", locale: "en"}).action).toBe("transfer_ownership") + expect(SessionRequestSchema.safeParse({action: "add_seats", seats: 1.5, locale: "en"}).success).toBe(false) + expect(SessionRequestSchema.safeParse({locale: "en"}).success).toBe(false) + }) + + test("a session request may ask for the one license it adds to be the asker's (forMe: true only)", () => { + const forMe = {action: "add_seats", licenseId: "01JZWY3V8N0F2E9GQ4T6KXH5RD", seats: 1, forMe: true as const, locale: "en"} + expect(SessionRequestSchema.parse(forMe)).toEqual(forMe) + expect(SessionRequestSchema.safeParse({...forMe, forMe: false}).success).toBe(false) + expect(SessionRequestSchema.safeParse({...forMe, forMe: "yes"}).success).toBe(false) + const {forMe: _forMe, ...without} = forMe + expect(SessionRequestSchema.parse(without)).toEqual(without) + expect(SessionRequestSchema.parse(without).forMe).toBeUndefined() + }) + + test("an unknown field of a request is stripped", () => { + expect(SessionRequestSchema.parse({action: "cancel", locale: "en", futureField: "x"})).toEqual({ + action: "cancel", + locale: "en", + }) + }) +}) + +describe("a product's public name", () => { + test("is a name and nothing else: a price, an id or an offer beside it is stripped", () => { + expect(PublicProductSchema.parse({name: "Mentra Call Unlimited"})).toEqual({name: "Mentra Call Unlimited"}) + const parsed = PublicProductSchema.parse({ + name: "Mentra Call Unlimited", + product: "mentra.call.unlimited", + priceId: "price_123", + offer: {price: {scheme: "per_seat"}}, + }) + expect(parsed).toEqual({name: "Mentra Call Unlimited"}) + expect(Object.keys(parsed)).toEqual(["name"]) + }) + + test("needs a non-empty string name", () => { + for (const value of [{}, {name: ""}, {name: null}, {name: 7}, {name: ["x"]}, null, "Mentra Call", []]) { + expect([value, PublicProductSchema.safeParse(value).success]).toEqual([value, false]) + } + }) +}) + +describe("the license billing document alone", () => { + test("a license needs its licenseId, product, status, label, price, quantity, total, tax and actions", () => { + expect(LicenseBillingSchema.safeParse(activeLicense).success).toBe(true) + for (const field of [ + "licenseId", + "product", + "status", + "fallbackStatusLabel", + "price", + "quantity", + "total", + "tax", + "actions", + ]) { + const license = copy(activeLicense) as Record + delete license[field] + expect([field, LicenseBillingSchema.safeParse(license).success]).toEqual([field, false]) + } + }) + + test("the dates are optional", () => { + const parsed = LicenseBillingSchema.parse({ + ...activeLicense, + status: "processing", + renewsAt: undefined, + }) + expect(parsed.renewsAt).toBeUndefined() + expect(parsed.endsAt).toBeUndefined() + expect(parsed.seatsStopAt).toBeUndefined() + }) + + test("a quantity that is not a whole number fails", () => { + expect(LicenseBillingSchema.safeParse({...activeLicense, quantity: 2.5}).success).toBe(false) + expect(LicenseBillingSchema.safeParse({...activeLicense, quantity: -1}).success).toBe(false) + }) +}) + +describe("billing's error codes", () => { + test("list the refusals the spec names", () => { + expect(BILLING_ERROR_CODES).toEqual([ + "invalid_request", + "not_for_sale", + "invalid_seats", + "unknown_action", + "forbidden", + "license_not_found", + "no_billing_account", + "already_licensed", + "checkout_in_progress", + "seat_request_pending", + "owner_ended", + "billing_unavailable", + "core_unavailable", + ]) + }) +}) + +describe("seat assignments and member names", () => { + test("MemberView without a name still type-checks, and one with a name or null does too", () => { + const base = { + membershipId: "mem_1", + mentraUserId: "mu_1", + email: "dana@example.test", + role: "member" as const, + startedAt: "2026-10-01T00:00:00Z", + pending: false, + } + const without: MemberView = base + const named: MemberView = {...base, name: "Dana Reyes"} + const unnamed: MemberView = {...base, name: null} + expect([without.name, named.name, unnamed.name]).toEqual([undefined, "Dana Reyes", null]) + }) + + test("the bulk assignment contract is in the package root", () => { + expect(root.MAX_SEAT_ASSIGNMENTS).toBe(500) + expect(root.NO_SEATS_AVAILABLE_ERROR).toBe("no_seats_available") + const request: root.SeatAssignmentsRequest = {assignments: [{licenseId: "lic_1", membershipId: "mem_1"}]} + const shortfall: root.SeatShortfall = {licenseId: "lic_1", needed: 3, free: 1} + const response: root.SeatAssignmentsResponse = {licenses: []} + expect([request.assignments.length, shortfall.needed - shortfall.free, response.licenses.length]).toEqual([1, 2, 0]) + }) +}) + +describe("the parts of the contract are exported by name", () => { + test("the catalog's and the status's inner objects parse and keep their values", () => { + const feature: CatalogFeature = CatalogFeatureSchema.parse({key: "call.unlimited", name: "Unlimited calls"}) + const buy: Buy = BuySchema.parse({minSeats: 1, maxSeats: 500}) + const offer: Offer = OfferSchema.parse(callUnlimited.offer) + const total: BillingTotal = BillingTotalSchema.parse(statusDocument.total) + const testMode: TestMode = TestModeSchema.parse(statusDocument.testMode) + const purchase: PurchaseStatus = PurchaseStatusSchema.parse(statusDocument.purchase) + expect(feature).toEqual({key: "call.unlimited", name: "Unlimited calls"}) + expect(buy).toEqual({minSeats: 1, maxSeats: 500}) + expect(offer).toEqual(callUnlimited.offer as unknown as Offer) + expect(total).toEqual(statusDocument.total as unknown as BillingTotal) + expect(testMode).toEqual(statusDocument.testMode) + expect(purchase).toEqual(statusDocument.purchase) + }) + + test("the two price shapes parse apart", () => { + const seat: PerSeatPrice = PerSeatPriceSchema.parse(perSeat) + const fallback: FallbackPrice = FallbackPriceSchema.parse({scheme: "tiered", fallbackLabel: "From $10"}) + expect(seat).toEqual(perSeat as unknown as PerSeatPrice) + expect(fallback).toEqual({scheme: "tiered", fallbackLabel: "From $10"}) + expect(PerSeatPriceSchema.safeParse({scheme: "tiered", fallbackLabel: "From $10"}).success).toBe(false) + expect(FallbackPriceSchema.safeParse(perSeat).success).toBe(false) + }) + + test("each part rejects what the whole rejects", () => { + expect(BuySchema.safeParse({minSeats: 0}).success).toBe(false) + expect(BillingTotalSchema.safeParse({...statusDocument.total, licenseCount: -1}).success).toBe(false) + expect(PurchaseStatusSchema.safeParse({...statusDocument.purchase, paid: "yes"}).success).toBe(false) + expect(TestModeSchema.safeParse({cardNumber: "4242424242424242"}).success).toBe(false) + expect(OfferSchema.safeParse({...callUnlimited.offer, price: {scheme: "per_seat"}}).success).toBe(false) + expect(CatalogFeatureSchema.safeParse({key: "call.unlimited"}).success).toBe(false) + }) +}) + +describe("the package entry points", () => { + test("portal-billing is a subpath of the package, not part of the root", () => { + const manifest = JSON.parse(readFileSync(join(import.meta.dir, "..", "package.json"), "utf8")) + expect(manifest.exports["./portal-billing"]).toBe("./src/portal-billing.ts") + expect(manifest.dependencies.zod).toBe("^3.24.1") + expect(Object.keys(root)).not.toContain("BillingStatusSchema") + expect(Object.keys(root)).not.toContain("billingIconPath") + }) + + test("portal-billing bundles for the browser", () => { + // Resolved rather than hard-coded so the compiled copy under dist/ finds its own portal-billing.js. + // Bundled by a separate `bun build`: a second in-process Bun.build of a package that imports zod fails + // with EISDIR once zod is loaded, which is what running this file and its dist copy together does. + const entrypoint = Bun.resolveSync("./portal-billing", import.meta.dir) + const result = Bun.spawnSync([process.execPath, "build", entrypoint, "--target=browser"], { + stdout: "pipe", + stderr: "pipe", + }) + expect(result.stderr.toString()).not.toContain("error") + expect(result.exitCode).toBe(0) + const bundle = result.stdout.toString() + expect(bundle).toContain("billingIconPath") + // zod is inlined: a browser that loads the bundle has nothing else to resolve. + expect(bundle).toContain("ZodError") + expect(bundle).not.toMatch(/\bfrom\s*["']zod["']|\brequire\(\s*["']zod["']\s*\)/) + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/portal-billing.ts b/cloud-v2/packages/workspace-contract/src/portal-billing.ts new file mode 100644 index 0000000000000000000000000000000000000000..975ca37cf23c759adfb88253e62d5e6a8e590497 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/portal-billing.ts @@ -0,0 +1,352 @@ +/** + * What the billing module sends the portal's Licenses page, as typed values: the catalog of + * products, and a workspace's billing status. Billing builds its answers with these schemas + * and the portal parses them with the same ones; the types are inferred from them. Core formats the values + * in the portal's locale and the viewer's time zone and words them with its own strings. Billing localizes + * only its own content (names, descriptions, feature and miniapp names, and every `fallback*` label). + * + * The routes, under `/api/portal/billing/workspaces//`: + * `GET catalog?locale=` ({@link BillingCatalog}), `GET status?locale=&purchase=` ({@link BillingStatus}), + * `POST purchase` ({@link PurchaseRequest} to {@link PurchaseAnswer}), `POST session` ({@link SessionRequest} + * to {@link SessionAnswer}) and `GET ui/icons/`. A refusal is `{error}` with one of + * {@link BILLING_ERROR_CODES}. + * + * One route is for anyone, signed in or not: `GET /api/portal/billing/public/products/` + * ({@link PublicProduct}), the product's name for the sign-in page. Core forwards it to billing's + * `GET /v1/portal/public/products/` with the `public` principal, which names no person. + * + * Values the portal doesn't know don't break a page. A status, an action kind and a tax value are plain + * strings, with `KNOWN_*` lists to narrow them by; a price of a scheme the portal doesn't know carries a + * `fallbackLabel`; an unknown field is stripped (an older Store's `ownerTypes` on an entry, or `defaultSeats` on a + * `buy`, among them). A value that is malformed is another matter: a response that doesn't match is the portal's + * "unavailable" state, so the schemas are strict about what the portal acts on (amounts, dates, addresses it + * follows) and `icon` is the one value that degrades instead (to null). + * + * Import it from `@mentra/workspace-contract/portal-billing`, not the package root. + */ + +import {z} from "zod" + +import {BILLING_ICON_FILE, BILLING_ICON_PATH_PREFIX, billingIconPath} from "./portal-billing-icons" + +/** Where billing serves its own files from, behind Core's portal proxy. */ +export const BILLING_UI_PATH_PREFIX = "/api/portal/billing/ui/" + +/** + * The icon rule lives in `portal-billing-icons`, which has no zod, so a screen that only draws an icon can import it + * without the schemas. It is re-exported here, so every import from this module keeps working. + */ +export {BILLING_ICON_FILE, BILLING_ICON_PATH_PREFIX, billingIconPath} + +/** + * The canonical address of `value` (`new URL(value).href`) when the portal may send the browser to it, or null: + * `https:`, or `http:` to `localhost` or `127.0.0.1` for local development, with no credentials in it. The + * browser's own URL parser reads it, and its result is what is returned, so what is checked is exactly what is + * followed: padding, tabs and newlines the parser ignores are gone from it. + */ +function hostedUrlHref(value: string): string | null { + let url: URL + try { + url = new URL(value) + } catch { + return null + } + if (url.username !== "" || url.password !== "") return null + if (url.protocol === "https:") return url.href + return url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1") ? url.href : null +} + +/** + * A purchase's or a session's `url`: the hosted page the portal sends the browser to, as its canonical address. + * See {@link hostedUrlHref}. + */ +export const HostedUrlSchema = z.string().transform((value, ctx) => { + const href = hostedUrlHref(value) + if (href === null) { + ctx.addIssue({code: z.ZodIssueCode.custom, message: "not an https: address (or http: to localhost)"}) + return z.NEVER + } + return href +}) + +/** ISO 8601 with an offset (`Z` or `+01:00`): a time that means one instant wherever it is read. */ +const DateTimeSchema = z.string().datetime({offset: true}) + +/** A whole number of at least one: seats, and the count of a recurrence. */ +const PositiveIntSchema = z.number().int().positive().safe() + +/** A whole number of at least zero: a quantity, and how many licenses are in a total. */ +const CountSchema = z.number().int().nonnegative().safe() + +/** An amount in the currency's minor unit (cents for USD), never fractional or negative, in ISO 4217 upper case. */ +export const MoneySchema = z.object({ + amountMinor: z.number().int().nonnegative().safe(), + currency: z.string().regex(/^[A-Z]{3}$/, "three uppercase letters"), +}) +export type Money = z.infer + +/** How often a price is charged: every `count` of the `interval`. */ +export const RecurrenceSchema = z.object({ + interval: z.enum(["day", "week", "month", "year"]), + count: PositiveIntSchema, +}) +export type Recurrence = z.infer + +/** A price per seat, per recurrence. */ +export const PerSeatPriceSchema = z.object({ + scheme: z.literal("per_seat"), + unit: MoneySchema, + recurrence: RecurrenceSchema, +}) +export type PerSeatPrice = z.infer + +/** + * A scheme the portal doesn't know, or a `per_seat` price that is malformed but carries its label. It is + * shown by `fallbackLabel`, in place of the price or the cost line. + */ +export const FallbackPriceSchema = z.object({ + scheme: z.string(), + fallbackLabel: z.string(), +}) +export type FallbackPrice = z.infer + +/** + * A list price. `per_seat` is the one scheme the portal can compute with; any other scheme, which billing may + * add without a portal release, comes with the words to show. A `per_seat` price that is malformed and has no + * `fallbackLabel` fails. + */ +export const PriceSchema = z.union([PerSeatPriceSchema, FallbackPriceSchema]) +export type Price = z.infer + +/** Whether `price` is a `per_seat` one, with a unit amount and a recurrence the portal can compute with. */ +export function isPerSeat(price: Price): price is PerSeatPrice { + return price.scheme === "per_seat" && "unit" in price && "recurrence" in price +} + +/** How tax relates to an amount. A value the portal doesn't know adds no words. */ +export const KNOWN_TAX = ["excluded", "included", "none"] as const +export type KnownTax = (typeof KNOWN_TAX)[number] +/** One of {@link KNOWN_TAX}, or a value the portal doesn't know. */ +export const TaxSchema = z.string() +export type Tax = z.infer + +/** The states of a license the portal words. An unknown status gets a grey badge with `fallbackStatusLabel`. */ +export const KNOWN_LICENSE_STATUSES = ["active", "ending", "past_due", "processing", "incomplete"] as const +export type KnownLicenseStatus = (typeof KNOWN_LICENSE_STATUSES)[number] + +/** The billing actions the portal words. An unknown kind is a "…" menu item with its `fallbackLabel`. */ +export const KNOWN_ACTION_KINDS = [ + "add_seats", + "change_seats", + "cancel", + "renew", + "update_payment", + "complete_payment", + "billing_and_invoices", +] as const +export type KnownActionKind = (typeof KNOWN_ACTION_KINDS)[number] + +/** + * Something billing can do for a license or the account, as a hosted page (`POST session`). Billing lists + * only actions it can serve. `returns: false` means its hosted page doesn't come back to the portal (an + * invoice's payment page), so the portal opens a tab for it in the click itself; absent means it returns. + */ +export const BillingActionSchema = z.object({ + kind: z.string(), + fallbackLabel: z.string(), + returns: z.boolean().optional(), +}) +export type BillingAction = z.infer + +/** A product's feature: its key, its name, and the miniapp it is for when there is one. */ +export const CatalogFeatureSchema = z.object({ + key: z.string(), + name: z.string(), + appName: z.string().optional(), +}) +export type CatalogFeature = z.infer + +/** + * What buying a product allows: the seats within `minSeats` and `maxSeats` (unbounded when absent). The portal + * starts at the workspace's member count, held to these. + */ +export const BuySchema = z.object({ + minSeats: PositiveIntSchema, + maxSeats: PositiveIntSchema.optional(), +}) +export type Buy = z.infer + +/** + * What a viewer who may manage the owner's billing sees beside a product: its price and tax treatment, and + * what buying allows. `buy` is null where billing won't sell the product to this owner now (they hold it, or + * a purchase of it is in progress). + */ +export const OfferSchema = z.object({ + price: PriceSchema, + tax: TaxSchema, + buy: BuySchema.nullable(), +}) +export type Offer = z.infer + +/** + * One product. `offer` is there only for a viewer who may manage the owner's billing; for anyone else the + * entry is display content only, the same for every workspace, and reveals no price. + * + * `icon` is a path under {@link BILLING_ICON_PATH_PREFIX} or null: any other address parses to null. + */ +export const CatalogEntrySchema = z.object({ + /** The license's product key, such as `mentra.call.unlimited`. */ + product: z.string(), + name: z.string(), + /** For chips and counts; the name when absent. */ + shortName: z.string().optional(), + description: z.string(), + icon: z + .string() + .nullable() + .transform((value) => billingIconPath(value)), + features: z.array(CatalogFeatureSchema), + offer: OfferSchema.optional(), +}) +export type CatalogEntry = z.infer + +/** `GET catalog`: the products a workspace is shown, in the locale billing chose (`locale`). */ +export const BillingCatalogSchema = z.object({ + locale: z.string().min(1), + products: z.array(CatalogEntrySchema), +}) +export type BillingCatalog = z.infer + +/** + * One license as billing reads it. `renewsAt` is the next renewal (for `past_due`, the one not paid), `endsAt` + * an end scheduled for an `ending` license or for an `active` or `past_due` one, and `seatsStopAt` when a + * `past_due` license's seats stop. `total` is quantity × unit, before tax, discounts and prorations: null for + * a scheme with no total per period. + */ +export const LicenseBillingSchema = z.object({ + licenseId: z.string(), + product: z.string(), + /** One of {@link KNOWN_LICENSE_STATUSES}, or a status the portal doesn't know. */ + status: z.string(), + fallbackStatusLabel: z.string(), + renewsAt: DateTimeSchema.optional(), + endsAt: DateTimeSchema.optional(), + seatsStopAt: DateTimeSchema.optional(), + price: PriceSchema, + quantity: CountSchema, + total: MoneySchema.nullable(), + tax: TaxSchema, + actions: z.array(BillingActionSchema), +}) +export type LicenseBilling = z.infer + +/** The page's total of the licenses billing will charge again; `licenseCount` says how many are in it. */ +export const BillingTotalSchema = z.object({ + amount: MoneySchema, + recurrence: RecurrenceSchema, + tax: TaxSchema, + licenseCount: CountSchema, +}) +export type BillingTotal = z.infer + +/** Test mode: the card to pay with, and the environment the purchase works in. */ +export const TestModeSchema = z.object({ + cardNumber: z.string(), + environment: z.string(), +}) +export type TestMode = z.infer + +/** + * A purchase that a checkout returned to the portal with (`?purchase=`). `status` is `processing` + * until Core has accepted the license, then `ready` with its `licenseId`. `paid` is whether the checkout + * collected a payment: false for a trial. + */ +export const PurchaseStatusSchema = z.object({ + purchaseId: z.string(), + /** `processing` or `ready`, or a status the portal doesn't know. */ + status: z.string(), + product: z.string(), + quantity: CountSchema, + paid: z.boolean(), + licenseId: z.string().nullable(), +}) +export type PurchaseStatus = z.infer + +/** + * `GET public/products/`: what anyone may know of a product, its name, for the sign-in page ("Sign in to + * buy ."). Billing answers it for a product that is for sale, and 404 for any other; Core relays the name and + * nothing else, so a price, an id or an offer beside it never leaves Core. + */ +export const PublicProductSchema = z.object({name: z.string().min(1)}) +export type PublicProduct = z.infer + +/** `GET status`: a workspace's licenses as billing reads them, with the owner's total, actions and purchase. */ +export const BillingStatusSchema = z.object({ + locale: z.string().min(1), + licenses: z.array(LicenseBillingSchema), + /** Null unless the licenses in it share one currency, one recurrence and one tax treatment. */ + total: BillingTotalSchema.nullable(), + /** The account's: `billing_and_invoices`. */ + actions: z.array(BillingActionSchema), + testMode: TestModeSchema.nullable(), + purchase: PurchaseStatusSchema.nullable(), +}) +export type BillingStatus = z.infer + +/** `POST purchase`: one checkout for one product. Billing refuses seats outside `buy`'s limits (`invalid_seats`). */ +export const PurchaseRequestSchema = z.object({ + product: z.string(), + seats: z.number().int().safe(), + locale: z.string().min(1), +}) +export type PurchaseRequest = z.infer + +/** + * `POST session`: the hosted page for an action. `licenseId` names the license it is for (none for the + * account's actions); `seats` is how many to add, for `add_seats`. An `action` that isn't offered gets + * 400 `unknown_action` from billing, so it stays a plain string here. + * + * `forMe: true`, with `add_seats` and `seats: 1` only, adds one license for the person asking: billing records + * their request, and Core assigns them the license once the write that adds it arrives. Billing refuses it with + * any other action or count (400 `invalid_request`), and while another person's request on the license is open + * (409 `seat_request_pending`). + */ +export const SessionRequestSchema = z.object({ + action: z.string(), + licenseId: z.string().optional(), + seats: z.number().int().safe().optional(), + forMe: z.literal(true).optional(), + locale: z.string().min(1), +}) +export type SessionRequest = z.infer + +/** The answer to `POST purchase`: the hosted checkout to send the browser to. */ +export const PurchaseAnswerSchema = z.object({url: HostedUrlSchema}) +export type PurchaseAnswer = z.infer + +/** The answer to `POST session`: the hosted page to send the browser to. */ +export const SessionAnswerSchema = z.object({url: HostedUrlSchema}) +export type SessionAnswer = z.infer + +/** + * The `error` of a refusal from billing (`{error}`): 400 `invalid_request`, `not_for_sale`, `invalid_seats` or + * `unknown_action`; 403 `forbidden`; 404 `license_not_found` or `no_billing_account`; + * 409 `already_licensed`, `checkout_in_progress`, `seat_request_pending` or `owner_ended`; 503 + * `billing_unavailable` or `core_unavailable`. Core words the ones it knows, and any other gets its generic "try again". + */ +export const BILLING_ERROR_CODES = [ + "invalid_request", + "not_for_sale", + "invalid_seats", + "unknown_action", + "forbidden", + "license_not_found", + "no_billing_account", + "already_licensed", + "checkout_in_progress", + "seat_request_pending", + "owner_ended", + "billing_unavailable", + "core_unavailable", +] as const +export type BillingErrorCode = (typeof BILLING_ERROR_CODES)[number] diff --git a/cloud-v2/packages/workspace-contract/src/portal-module-ui.test.ts b/cloud-v2/packages/workspace-contract/src/portal-module-ui.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce2bce1143e60e2bde61005990a9aae29df6fcd7 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/portal-module-ui.test.ts @@ -0,0 +1,88 @@ +import {describe, expect, test} from "bun:test" +import {readFileSync} from "node:fs" +import {join} from "node:path" +import * as root from "./index" +import { + PORTAL_MODULE_CONTRACT_VERSION, + type PortalModule, + type PortalModuleContext, + type PortalModuleMe, +} from "./portal-module-ui" + +const me: PortalModuleMe = { + authenticated: true, + user: {mentraUserId: "mu_1", email: "person@example.test", emailVerified: true}, +} + +describe("portal module UI contract", () => { + test("is version 1", () => { + expect(PORTAL_MODULE_CONTRACT_VERSION).toBe(1) + }) + + test("is reached through the ./portal-module-ui subpath, not the package root, and bundles for the browser", async () => { + const manifest = JSON.parse(readFileSync(join(import.meta.dir, "..", "package.json"), "utf8")) + expect(manifest.exports["./portal-module-ui"]).toBe("./src/portal-module-ui.ts") + expect(Object.keys(root)).not.toContain("PORTAL_MODULE_CONTRACT_VERSION") + const entrypoint = Bun.resolveSync("./portal-module-ui", import.meta.dir) + const result = await Bun.build({entrypoints: [entrypoint], target: "browser"}) + expect(result.logs.filter((log) => log.level === "error").map((log) => log.message)).toEqual([]) + expect(result.success).toBe(true) + }) + + test("a module mounts into a host element with the host's context and unmounts", () => { + const calls: string[] = [] + const mod: PortalModule = { + contractVersion: PORTAL_MODULE_CONTRACT_VERSION, + mount(element, ctx) { + calls.push(`mount ${ctx.apiBase} ${JSON.stringify(ctx.scope)} ${ctx.route.path}${ctx.route.query}`) + ctx.navigate("/licenses", {replace: true}) + ctx.onSessionExpired() + return {unmount: () => calls.push("unmount")} + }, + } + const ctx: PortalModuleContext = { + apiBase: "/api/portal/billing", + me, + scope: {kind: "workspace", workspaceId: "ws_1"}, + route: {path: "/", query: "?tab=seats"}, + navigate: (path, opts) => calls.push(`navigate ${path} ${opts?.replace === true}`), + onSessionExpired: () => calls.push("expired"), + } + const handle = mod.mount({} as unknown as HTMLElement, ctx) + handle.unmount() + expect(calls).toEqual([ + 'mount /api/portal/billing {"kind":"workspace","workspaceId":"ws_1"} /?tab=seats', + "navigate /licenses true", + "expired", + "unmount", + ]) + }) + + test("a person's own account is a scope of its own, and a handle's setRoute is optional", () => { + const calls: string[] = [] + const ctx: PortalModuleContext = { + apiBase: "/api/portal/billing", + me, + scope: {kind: "person"}, + route: {path: "/", query: ""}, + navigate: () => {}, + onSessionExpired: () => {}, + } + const redrawing: PortalModule = { + contractVersion: PORTAL_MODULE_CONTRACT_VERSION, + mount: () => ({ + unmount: () => calls.push("unmount"), + setRoute: (route) => calls.push(`route ${route.path}${route.query}`), + }), + } + const remounting: PortalModule = { + contractVersion: PORTAL_MODULE_CONTRACT_VERSION, + mount: () => ({unmount: () => calls.push("unmount")}), + } + const withSetRoute = redrawing.mount({} as unknown as HTMLElement, ctx) + withSetRoute.setRoute?.({path: "/plans", query: "?x=1"}) + const withoutSetRoute = remounting.mount({} as unknown as HTMLElement, ctx) + expect(withoutSetRoute.setRoute).toBeUndefined() + expect(calls).toEqual(["route /plans?x=1"]) + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/portal-module-ui.ts b/cloud-v2/packages/workspace-contract/src/portal-module-ui.ts new file mode 100644 index 0000000000000000000000000000000000000000..57938cc5b4bec1e747224d4f2f438e55a91f9ed0 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/portal-module-ui.ts @@ -0,0 +1,58 @@ +/// +/** + * The contract between a host page and the UI module that a portal module serves through Core + * (`/api/portal//ui/entry.js`, for example the billing module's). The host, a workspace portal + * page, imports the module, checks `contractVersion`, and calls `mount` with a {@link PortalModuleContext}. + * Types and one constant only, so the host and the module can both import it in the browser. + * + * Import it from `@mentra/workspace-contract/portal-module-ui`, not the package root: the contract names DOM + * types, which server packages do not have. + */ + +import type {ForwardedScope} from "./types" + +/** The version of this contract. A host and a module that disagree on it must not be mounted together. */ +export const PORTAL_MODULE_CONTRACT_VERSION = 1 + +/** What the host knows about the caller: a signed-in person, since the portal serves nobody else. */ +export interface PortalModuleMe { + authenticated: true + user: {mentraUserId: string; email: string | null; emailVerified: boolean} +} + +/** + * What the page the module is mounted on covers: one workspace's, or the person's own account. It + * names which of the module's two API roots to call (`/workspaces//...` or + * `/account/...`). Core decides what a request may do from the session, never from this value. + */ +export type PortalModuleScope = Extract + +/** Everything the host hands the module when it mounts. */ +export interface PortalModuleContext { + /** Where the module sends its API requests, e.g. `/api/portal/billing`. */ + apiBase: string + me: PortalModuleMe + scope: PortalModuleScope + /** The host's route when the module mounts. Later changes reach the module as the {@link PortalModule.mount} doc says. */ + route: {path: string; query: string} + /** Asks the host to go to `path`; with `replace`, the current history entry is replaced instead of a new one added. */ + navigate(path: string, opts?: {replace?: boolean}): void + /** Tells the host the caller's session has ended (the API answered 401), so it can send them to sign in. */ + onSessionExpired(): void +} + +/** What a portal module's UI entry exports. */ +export interface PortalModule { + contractVersion: number + /** + * Renders into `element`; the returned handle removes everything the module added. + * + * `ctx.route` is the route at mount. If the handle provides `setRoute`, the host calls it on every later + * route change (including after the module's own `navigate` and Back/Forward) instead of remounting; + * otherwise the host unmounts and mounts again. + */ + mount( + element: HTMLElement | ShadowRoot, + ctx: PortalModuleContext, + ): {unmount(): void; setRoute?(route: {path: string; query: string}): void} +} diff --git a/cloud-v2/packages/workspace-contract/src/registry-admin.ts b/cloud-v2/packages/workspace-contract/src/registry-admin.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce1fd95f2e2f0adb58ea2c1c256a6e071b45c311 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/registry-admin.ts @@ -0,0 +1,155 @@ +/** + * The admin portal's miniapp registry (`/api/admin/registry`, Core's `docs/registry.md`): every miniapp URL the + * Mentra App has installed, for Organization Admins, who archive entries and register URLs themselves. It needs + * `organization.registry.administer`, which only an Organization Admin holds: no operator key carries it. + * + * An archive rule names a URL, a package name, a registrable domain or the account that first registered entries. + * It archives the entries it covers and refuses the URLs registered after it. Archiving refuses installs and stops + * updates; installed copies keep running. Times are ISO 8601 UTC. + */ + +/** What an archive rule names: a miniapp URL, a package name, a registrable domain, or an account (a Mentra user id). */ +export const ADMIN_REGISTRY_RULE_KINDS = ["url", "package", "domain", "account"] as const +export type AdminRegistryRuleKind = (typeof ADMIN_REGISTRY_RULE_KINDS)[number] + +/** An archive rule. Core normalizes `value` (a URL ends in `/`, a domain is lowercase) and answers with its form. */ +export interface AdminRegistryRule { + kind: AdminRegistryRuleKind + value: string +} + +/** An archive rule as Core keeps it: why, and who made it (an Organization Admin's email, or a service and its actor). */ +export interface AdminRegistryRuleView extends AdminRegistryRule { + reason: string + createdBy: string + createdAt: string +} + +/** `verified`: Core read the URL's `miniapp.json` itself. `phone_reported`: Core couldn't, so it holds a phone's report. */ +export type AdminRegistryVerification = "verified" | "phone_reported" + +/** One registry entry, as an Organization Admin sees it: nothing is redacted. */ +export interface AdminRegistryEntryView { + /** The normalized miniapp URL: the entry's key. */ + url: string + packageName: string + registrableDomain: string + /** Null when Core knows only the package name (a private server that refused Core's token). */ + name: string | null + version: string | null + ageRating: string | null + /** The manifest's icon, an absolute HTTPS URL on the developer's host. Core never fetches it. */ + iconUrl: string | null + verification: AdminRegistryVerification + /** Its server asks for sign-in. */ + private: boolean + /** `archived` when the entry's own status is, or an archive rule covers it. */ + status: "active" | "archived" + /** The kinds of the archive rules that cover it, in `ADMIN_REGISTRY_RULE_KINDS` order; empty when none does. */ + archivedBy: AdminRegistryRuleKind[] + firstRegisteredAt: string + /** The Mentra user id of the account that first registered it: the value of an `account` rule. */ + firstRegisteredBy: string + /** Null when Core has never read it. */ + lastVerifiedAt: string | null +} + +/** The `status` filter of `GET /api/admin/registry/entries`. */ +export const ADMIN_REGISTRY_STATUSES = ["active", "archived"] as const +/** The `verification` filter of `GET /api/admin/registry/entries`. */ +export const ADMIN_REGISTRY_VERIFICATIONS = ["verified", "phone_reported"] as const + +/** The longest search text, in characters. */ +export const ADMIN_REGISTRY_QUERY_MAX_LENGTH = 200 + +/** + * Response of `GET /api/admin/registry/entries?q=&status=&verification=&cursor=`: a page of entries, most recently + * registered first. `next` is the `cursor` of the page after this one, or null on the last page. + */ +export interface AdminRegistryEntriesResponse { + items: AdminRegistryEntryView[] + next: string | null +} + +/** Response of `GET /api/admin/registry/rules?cursor=`: archive rules, newest first. */ +export interface AdminRegistryRulesResponse { + items: AdminRegistryRuleView[] + next: string | null +} + +/** + * Response of `GET /api/admin/registry/coverage?kind=&value=`, asked before archiving: the rule in Core's form, how + * many entries it covers today and how many of those are active, and whether the rule exists already. + */ +export interface AdminRegistryCoverage { + rule: AdminRegistryRule + entries: number + activeEntries: number + exists: boolean +} + +/** `POST /api/admin/registry/archive` with `{rule, reason?}`. */ +export interface AdminRegistryArchiveRequest { + rule: AdminRegistryRule + /** Shown with the rule. At most `ADMIN_REGISTRY_REASON_MAX_LENGTH` characters. */ + reason?: string +} + +/** The longest archive reason, in characters. */ +export const ADMIN_REGISTRY_REASON_MAX_LENGTH = 500 + +/** The answer to an archive: `created` is false for a rule that existed (its reason and author stay). */ +export interface AdminRegistryArchiveResponse { + rule: AdminRegistryRule + created: boolean + entriesArchived: number +} + +/** The answer to `POST /api/admin/registry/unarchive` with `{rule}`: entries no other rule covers are active again. */ +export interface AdminRegistryUnarchiveResponse { + rule: AdminRegistryRule + removed: boolean + entriesRestored: number +} + +/** The most URLs one `POST /api/admin/registry/register` may name. */ +export const ADMIN_REGISTRY_REGISTER_MAX_URLS = 50 + +/** + * What registering one URL came to, as a phone's registration would, with the Organization Admin as the person + * registering it: + * - `accepted`: Core read a valid `miniapp.json` whose package passes the domain rule; + * - `accepted_unverified`: a private server that refused the admin's token, or a URL Core already holds that it + * couldn't read this time; + * - `not_a_miniapp`, with `reason`; + * - `unreachable`: Core couldn't read the URL and holds no report of it, so nothing was recorded; + * - `archived`: an archive rule covers it; + * - `invalid_url`: not a miniapp URL at all; + * - `failed`: Core couldn't finish; nothing changed that a retry wouldn't redo. + */ +export type AdminRegistryRegisterOutcome = + | "accepted" + | "accepted_unverified" + | "not_a_miniapp" + | "unreachable" + | "archived" + | "invalid_url" + | "failed" + +export interface AdminRegistryRegisterResult { + /** The URL as it was sent. */ + input: string + result: AdminRegistryRegisterOutcome + /** The normalized URL, for `accepted` and `accepted_unverified`. */ + url?: string + /** For `not_a_miniapp`: `invalid_manifest`, `domain_mismatch`, `not_https` or `local_network_url`. */ + reason?: string + /** For `accepted` and `accepted_unverified`. */ + packageName?: string + name?: string | null +} + +/** Response of `POST /api/admin/registry/register` with `{urls}`: one result per distinct URL, in order. */ +export interface AdminRegistryRegisterResponse { + results: AdminRegistryRegisterResult[] +} diff --git a/cloud-v2/packages/workspace-contract/src/server.ts b/cloud-v2/packages/workspace-contract/src/server.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb7806899b72f872b4100f3ee67c55be3e369c71 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/server.ts @@ -0,0 +1,8 @@ +// Server entry point: request signing and the Core client use `node:crypto`, so this must not be +// imported into browser bundles. Browser code imports the package root instead. +export * from "./client" +export * from "./deletion-holds" +export * from "./forwarded-principal" +export * from "./licenses" +export * from "./service-signature" +export * from "./types" diff --git a/cloud-v2/packages/workspace-contract/src/service-signature.test.ts b/cloud-v2/packages/workspace-contract/src/service-signature.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..98ff5024fd52b07812452b46ebde787d8e5c5e97 --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/service-signature.test.ts @@ -0,0 +1,141 @@ +import {describe, expect, test} from "bun:test" +import {createHmac} from "node:crypto" +import {SERVICE_HEADERS, signServiceRequest, verifyServiceRequest} from "./service-signature" + +const base = {method: "POST", pathWithQuery: "/api/internal/workspaces/authorize", body: "{}", timestampMs: 1_000} + +describe("service request signatures", () => { + test("verifies a signature and rejects body, path, skew and secret changes", () => { + const signature = signServiceRequest({...base, secret: "s1"}) + expect(verifyServiceRequest({...base, secrets: ["old", "s1"], signature, nowMs: 1_000})).toBe(true) + expect(verifyServiceRequest({...base, body: "{ }", secrets: ["s1"], signature, nowMs: 1_000})).toBe(false) + expect(verifyServiceRequest({...base, pathWithQuery: "/x", secrets: ["s1"], signature, nowMs: 1_000})).toBe(false) + expect(verifyServiceRequest({...base, secrets: ["s1"], signature, nowMs: 62_000})).toBe(false) + expect(verifyServiceRequest({...base, secrets: ["s2"], signature, nowMs: 1_000})).toBe(false) + }) + + test("binds the method, the query string and the timestamp", () => { + const withQuery = { + ...base, + method: "GET", + pathWithQuery: "/api/internal/workspaces/changes?after=a&limit=5", + body: "", + } + const signature = signServiceRequest({...withQuery, secret: "s1"}) + expect(verifyServiceRequest({...withQuery, secrets: ["s1"], signature, nowMs: 1_000})).toBe(true) + expect(verifyServiceRequest({...withQuery, method: "POST", secrets: ["s1"], signature, nowMs: 1_000})).toBe(false) + expect( + verifyServiceRequest({ + ...withQuery, + pathWithQuery: "/api/internal/workspaces/changes?after=b&limit=5", + secrets: ["s1"], + signature, + nowMs: 1_000, + }), + ).toBe(false) + expect(verifyServiceRequest({...withQuery, timestampMs: 1_001, secrets: ["s1"], signature, nowMs: 1_001})).toBe( + false, + ) + }) + + test("signs the documented base64url HMAC-SHA256 string", () => { + const signature = signServiceRequest({...base, secret: "s1"}) + expect(signature).toMatch(/^[A-Za-z0-9_-]{43}$/) + expect(signServiceRequest({...base, secret: "s1"})).toBe(signature) + expect(signServiceRequest({...base, secret: "s2"})).not.toBe(signature) + }) + + test("accepts timestamps within the skew window in either direction and honours maxSkewMs", () => { + const signature = signServiceRequest({...base, secret: "s1"}) + const verify = (nowMs: number, maxSkewMs?: number) => + verifyServiceRequest({...base, secrets: ["s1"], signature, nowMs, maxSkewMs}) + expect(verify(61_000)).toBe(true) + expect(verify(61_001)).toBe(false) + expect(verify(0)).toBe(true) // clock slightly behind the signer + expect(verify(-60_001)).toBe(false) + expect(verify(5_000, 1_000)).toBe(false) + expect(verify(1_500, 1_000)).toBe(true) + }) + + test("rejects malformed signatures, an empty secret list and a non-finite timestamp", () => { + const signature = signServiceRequest({...base, secret: "s1"}) + expect(verifyServiceRequest({...base, secrets: ["s1"], signature: "", nowMs: 1_000})).toBe(false) + expect(verifyServiceRequest({...base, secrets: ["s1"], signature: signature.slice(1), nowMs: 1_000})).toBe(false) + expect(verifyServiceRequest({...base, secrets: ["s1"], signature: `${signature}x`, nowMs: 1_000})).toBe(false) + expect(verifyServiceRequest({...base, secrets: [], signature, nowMs: 1_000})).toBe(false) + expect(verifyServiceRequest({...base, secrets: ["s1"], signature, nowMs: Number.NaN})).toBe(false) + }) + + test("matches known-answer vectors computed independently of this module", () => { + // Computed once with node:crypto over "\n\n\n"; do not regenerate + // these from signServiceRequest, they pin the wire format shared with the Store and Fleet integrations. + const post = { + secret: "known-answer-secret", + method: "POST", + pathWithQuery: "/api/internal/workspaces/authorize", + body: '{"credential":{"type":"mentra_user","mentraUserId":"user_1"}}', + timestampMs: 1_700_000_000_000, + } + expect(signServiceRequest(post)).toBe("xfy3gn_baTCt6aTUQ_cqs_E_Zm8kE1b4Ue_vKc4F3Ko") + const get = { + secret: "known-answer-secret", + method: "GET", + pathWithQuery: "/api/internal/workspaces/changes?after=abc&limit=100", + body: "", + timestampMs: 1_700_000_000_000, + } + expect(signServiceRequest(get)).toBe("xS_WFYqxy44wawNhjro4C71KeDIDiVxns1e5N7z4L_I") + expect(signServiceRequest({...get, method: "get"})).toBe("xS_WFYqxy44wawNhjro4C71KeDIDiVxns1e5N7z4L_I") + expect( + verifyServiceRequest({ + ...get, + secrets: ["known-answer-secret"], + signature: "xS_WFYqxy44wawNhjro4C71KeDIDiVxns1e5N7z4L_I", + nowMs: get.timestampMs, + }), + ).toBe(true) + }) + + test("refuses to sign with an empty or whitespace-only secret", () => { + expect(() => signServiceRequest({...base, secret: ""})).toThrow() + expect(() => signServiceRequest({...base, secret: " "})).toThrow() + }) + + test("never verifies against an empty secret, so a signature made with one is not forgeable", () => { + const forged = createHmac("sha256", "") + .update( + `${base.timestampMs}\n${base.method}\n${base.pathWithQuery}\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`, + ) + .digest("base64url") + const attempt = {...base, body: "", signature: forged, nowMs: 1_000} + expect(verifyServiceRequest({...attempt, secrets: [""]})).toBe(false) + expect(verifyServiceRequest({...attempt, secrets: ["", " "]})).toBe(false) + expect(verifyServiceRequest({...attempt, secrets: []})).toBe(false) + expect(verifyServiceRequest({...attempt, secrets: ["", "s1"]})).toBe(false) + }) + + test("still verifies a real secret that sits next to an empty one in the rotation list", () => { + const signature = signServiceRequest({...base, secret: "s1"}) + expect(verifyServiceRequest({...base, secrets: ["", " ", "s1"], signature, nowMs: 1_000})).toBe(true) + }) + + test("treats a non-finite or negative maxSkewMs as invalid rather than disabling the skew check", () => { + const signature = signServiceRequest({...base, secret: "s1"}) + const verify = (nowMs: number, maxSkewMs: number) => + verifyServiceRequest({...base, secrets: ["s1"], signature, nowMs, maxSkewMs}) + expect(verify(1_000, Number.NaN)).toBe(false) + expect(verify(1_000, -1)).toBe(false) + expect(verify(1_000, Number.POSITIVE_INFINITY)).toBe(false) + expect(verify(1_000_000, Number.NaN)).toBe(false) + expect(verify(1_000, 0)).toBe(true) + expect(verify(1_001, 0)).toBe(false) + }) + + test("exposes the header names", () => { + expect(SERVICE_HEADERS).toEqual({ + service: "x-mentra-service", + timestamp: "x-mentra-service-timestamp", + signature: "x-mentra-service-signature", + }) + }) +}) diff --git a/cloud-v2/packages/workspace-contract/src/service-signature.ts b/cloud-v2/packages/workspace-contract/src/service-signature.ts new file mode 100644 index 0000000000000000000000000000000000000000..267953911865e188312320ada148455ad3b1466f --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/service-signature.ts @@ -0,0 +1,57 @@ +/** HMAC signatures for Core's internal service calls (Store, Fleet integration). */ +import {createHash, createHmac, timingSafeEqual} from "node:crypto" + +export const SERVICE_HEADERS = { + service: "x-mentra-service", + timestamp: "x-mentra-service-timestamp", + signature: "x-mentra-service-signature", +} as const + +const DEFAULT_MAX_SKEW_MS = 60_000 + +const isBlank = (secret: string) => secret.trim().length === 0 + +interface SignedFields { + method: string + /** URL path plus query string exactly as sent. */ + pathWithQuery: string + body: string + timestampMs: number +} + +/** + * HMAC-SHA256 over `\n\n\n`, base64url. + * Throws on an empty secret: a signature made with one is forgeable by anyone. + */ +export function signServiceRequest(input: SignedFields & {secret: string}): string { + if (isBlank(input.secret)) throw new Error("A service secret must not be empty") + const bodyHash = createHash("sha256").update(input.body).digest("hex") + const signed = `${input.timestampMs}\n${input.method.toUpperCase()}\n${input.pathWithQuery}\n${bodyHash}` + return createHmac("sha256", input.secret).update(signed).digest("base64url") +} + +/** + * True when `signature` matches any of `secrets` (rotation) and the timestamp is within the skew window. + * Empty or whitespace-only secrets are ignored, so they can never authenticate a request; an invalid + * `maxSkewMs` (non-finite or negative) fails verification instead of disabling the skew check. + */ +export function verifyServiceRequest( + input: SignedFields & { + secrets: readonly string[] + signature: string + nowMs: number + maxSkewMs?: number + }, +): boolean { + if (!Number.isFinite(input.timestampMs) || !Number.isFinite(input.nowMs)) return false + const maxSkewMs = input.maxSkewMs ?? DEFAULT_MAX_SKEW_MS + if (!Number.isFinite(maxSkewMs) || maxSkewMs < 0) return false + if (Math.abs(input.nowMs - input.timestampMs) > maxSkewMs) return false + const provided = Buffer.from(input.signature) + let matched = false + for (const secret of input.secrets.filter((candidate) => !isBlank(candidate))) { + const expected = Buffer.from(signServiceRequest({...input, secret})) + if (expected.length === provided.length && timingSafeEqual(expected, provided)) matched = true + } + return matched +} diff --git a/cloud-v2/packages/workspace-contract/src/types.ts b/cloud-v2/packages/workspace-contract/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..28c4bd0122578fba91573eb10be6dc5cd5ada21b --- /dev/null +++ b/cloud-v2/packages/workspace-contract/src/types.ts @@ -0,0 +1,726 @@ +/** Wire types for Core's workspace APIs: the signed service API and the public workspace and organization routes. */ +import type {OrganizationCapability, WorkspaceCapability, WorkspaceRole} from "./capabilities" + +/** + * Who is calling Core. A person is a Core user (`mentraUserId`): the same user on the phone and in the + * browser. A credential is a Core key: a workspace key (`msk_`) or an organization operator key (`mak_`, + * or an `msk_` admin key made before operator keys). + */ +export type CorePrincipal = + | { + kind: "user" + mentraUserId: string + email: string | null + /** Whether the identity provider verified `email`. An unverified email is never an authorization. */ + emailVerified: boolean + isOrganizationAdmin: boolean + } + | { + kind: "credential" + credentialId: string + credentialKind: "workspace" | "organization" + workspaceId: string | null + scopes: string[] + /** + * Non-empty: the key may act only on these packages. A consumer that lists or acts on packages + * must filter by it, and must pass `packageName` to `/authorize` for anything package-specific + * (see {@link AuthorizeRequest.packageName}). + */ + packageNames: string[] + label: string + } + +export interface WorkspaceSummary { + workspaceId: string + name: string + status: "active" | "deleted" + authorizationRevision: number +} + +export interface MembershipSummary { + membershipId: string + role: WorkspaceRole +} + +export type AuthorizeCredential = {type: "bearer"; token: string} | {type: "mentra_user"; mentraUserId: string} + +export interface AuthorizeRequest { + credential: AuthorizeCredential + workspaceId?: string + capability?: WorkspaceCapability + /** + * The package the request acts on. A package-scoped credential (non-empty + * `principal.packageNames`) is refused with `package_out_of_scope` for any other package. + * + * Omitting it authorizes the capability workspace-wide, package-scoped keys included: Core cannot + * apply a package restriction to a request that names no package. So every route that reads or + * changes one package must pass it, and a route that lists packages must itself filter the result + * by `principal.packageNames`. People and workspace-wide keys are never package-scoped. + */ + packageName?: string +} + +export type DenyReason = + | "unauthenticated" + | "not_a_member" + | "capability_missing" + | "workspace_not_found" + | "workspace_deleted" + | "package_out_of_scope" + | "credential_invalid" + +export interface AuthorizeResponse { + allowed: boolean + reason?: DenyReason + principal: CorePrincipal | null + workspace?: WorkspaceSummary | null + membership?: MembershipSummary | null + capabilities: WorkspaceCapability[] +} + +export interface PrincipalResponse { + principal: CorePrincipal + /** + * The person's workspaces, oldest first. `replaceable` is true for their own automatic workspace (the one + * Core made for them, which they own) while it holds nothing: they are its only member, and it has no + * pending invitation, key, license that has not ended, or deletion hold. Core deletes such a workspace in + * the transaction that gives them a membership in another one (accepting an invitation, claiming an + * imported membership, recovering ownership). An older Core leaves it out. + */ + workspaces: Array< + WorkspaceSummary & {membership: MembershipSummary; capabilities: WorkspaceCapability[]; replaceable?: boolean} + > +} + +export interface MembershipCheckEntry { + role: WorkspaceRole + capabilities: WorkspaceCapability[] +} + +/** Response of `POST /memberships/check`: one entry per requested workspace, null for a non-member. */ +export interface MembershipCheckResponse { + memberships: Record +} + +/** Response of `POST /credentials`. The token is shown once. */ +export interface ServiceCredentialResponse { + credentialId: string + token: string +} + +/** Response of `POST /users/resolve-email`: the Mentra user behind a verified account email. */ +export interface ResolveEmailResponse { + mentraUserId: string +} + +// --- Deletion holds --------------------------------------------------------- + +/** + * A service's hold on a workspace. While a workspace has any hold, nobody can delete it, an + * Organization Admin included: the delete is refused with 409 {@link WORKSPACE_HAS_HOLDS_ERROR} + * until the service clears its hold. Each service has at most one hold per workspace, which it sets + * with `PUT /workspaces/:workspaceId/deletion-holds/:service` (replacing its previous one) and clears + * with `DELETE` on the same path. + * + * Every set and clear carries `asOf`, the instant the service computed it ({@link DeletionHoldUpdate}), + * so a call Core applies late never overwrites a newer one. + * + * `service` is the service that placed it (`store`); `reason` is a lowercase code + * ({@link DELETION_HOLD_REASON_PATTERN}, for example `owns_miniapps`); `count`, when present, is how + * many of the things the reason names the workspace still has. `describeDeletionHold` puts a hold in + * words. + */ +export interface WorkspaceDeletionHold { + service: string + reason: string + count?: number +} + +/** + * What every set and clear of a hold carries (`PUT` and `DELETE` bodies both): `asOf`, the instant at + * which the service computed the hold, as an ISO 8601 UTC string with at most millisecond precision + * (`Date.prototype.toISOString`). Take it just before reading what the hold counts, so the count + * reflects every change made before it, and make it later than every `asOf` the service sent for the + * workspace before: an equal `asOf` with a different hold is stale too, and wall clocks repeat, step + * back and differ between hosts. + * + * Core keeps, for each service, the newest `asOf` it has applied, a clear's included, and ignores a + * set or clear that is not newer (see {@link DeletionHoldsResponse.ignored}): a call that timed out + * and reached Core late cannot undo a newer one. The same call again, with the same `asOf`, is + * answered as applied. An `asOf` more than {@link DELETION_HOLD_MAX_FUTURE_SKEW_MS} ahead of Core's + * clock is 400 `invalid_request`, as is a missing or malformed one. + */ +export interface DeletionHoldUpdate { + asOf: string +} + +/** How far ahead of Core's clock a hold's `asOf` may be: five minutes. */ +export const DELETION_HOLD_MAX_FUTURE_SKEW_MS = 5 * 60_000 + +/** Response of `PUT` and `DELETE /workspaces/:workspaceId/deletion-holds/:service`: every hold on the workspace after the call. */ +export interface DeletionHoldsResponse { + workspaceId: string + holds: WorkspaceDeletionHold[] + /** + * True when Core ignored the call because it has already applied a set or clear from this service + * with a newer `asOf`, or the same `asOf` and a different hold. Core wrote and recorded nothing, and + * `holds` are the holds it keeps. A stale call changes nothing, so it is not a failure, but a caller + * that needs the workspace held (before a publication takes effect) must find its own hold in + * `holds`: an ignored set leaves whatever the newer call did, a clear included. + */ + ignored: boolean +} + +/** What a hold's `reason` must match: a lowercase code of at most 64 letters, digits and underscores, starting with a letter. */ +export const DELETION_HOLD_REASON_PATTERN = /^[a-z][a-z0-9_]{0,63}$/ + +/** The Store's hold `reason` while a workspace still owns a miniapp that is not deleted; its `count` is how many. */ +export const OWNS_MINIAPPS_HOLD_REASON = "owns_miniapps" + +/** + * `error` of the 409 that deleting a workspace answers while any service holds it. The body is + * {@link WorkspaceHasHoldsErrorBody}: `error_description` says why in words and `holds` lists every hold. + */ +export const WORKSPACE_HAS_HOLDS_ERROR = "workspace_has_holds" + +export interface WorkspaceHasHoldsErrorBody { + error: typeof WORKSPACE_HAS_HOLDS_ERROR + error_description: string + holds: WorkspaceDeletionHold[] +} + +// --- Change feed ------------------------------------------------------------ + +/** + * One entry of Core's change feed (`GET /changes`). `eventId` identifies the event; `seq` is its + * position in the feed, assigned in commit order, and is the only thing to page by: pass the last + * `seq` you processed, as a decimal string, as the next request's `after`. The feed leaves out + * organization-level events (operator keys), so consecutive events can skip `seq` numbers. A + * skipped number is never a missed event. + * + * `workspaceId` is null only for user-level tombstones ({@link USER_DELETED_ACTION}). `action` + * names the change (`"user.deleted"`, `"workspace.created"`, ...); a receiver treats an action it + * does not know as a no-op. `target`, `before` and `after` are snapshots whose shape depends on + * `action` (see the event catalog in Core's `docs/fleet-integration.md`), null when the event has + * none, with every credential-looking key (`token`, `secret`, `hash`, `password`) removed at any + * depth. + */ +export interface WorkspaceChangeEvent { + eventId: string + seq: number + workspaceId: string | null + action: string + occurredAt: string + target: Record | null + before: Record | null + after: Record | null +} + +/** + * Response of `GET /changes`: events in `seq` order. `next` is the cursor for the following page + * (the last event's `seq`), or null when the page was not full and there is nothing more yet. + */ +export interface WorkspaceChangesResponse { + events: WorkspaceChangeEvent[] + next: string | null +} + +/** + * `action` of the tombstone recorded when a Mentra account is deleted: `workspaceId` is null and + * `target` is `{mentraUserId}`. A service that keeps data keyed by that user deletes it. Each + * membership the deletion ended was recorded before it, as a `membership.removed` event. + */ +export const USER_DELETED_ACTION = "user.deleted" + +// --- Forwarded principals (Core -> Fleet) ---------------------------------- + +/** + * The headers Core adds to a request it forwards to the Fleet integration or to a portal module, beyond the service + * signature headers (`SERVICE_HEADERS`, with `x-mentra-service: core`). `principal` is the caller as + * base64url JSON ({@link ForwardedPrincipal}); `principalSignature` is a base64url HMAC-SHA256, + * keyed with the same secret as the service signature, over `\n`. + * Verify both with `verifyForwardedPrincipal` from `@mentra/workspace-contract/server`. + */ +export const FORWARDED_PRINCIPAL_HEADERS = { + principal: "x-mentra-principal", + principalSignature: "x-mentra-principal-signature", +} as const + +/** The `x-mentra-service` value of every request Core forwards. */ +export const FORWARDING_SERVICE = "core" + +/** + * What a forwarded request covers, decided by Core. A signed-in person's request ({@link UserScope}) covers + * the whole organization, one workspace (a team), or the person's own account. `public` is a request Core + * forwards for anyone, signed in or not, and it names no person: only a `public` principal carries it. + */ +export type ForwardedScope = + | {kind: "organization"} + | {kind: "workspace"; workspaceId: string} + | {kind: "person"} + | {kind: "public"} + +/** What a signed-in person's request covers: every scope but `public`, which names no person. */ +export type UserScope = Exclude + +/** The scope under its first name, when Fleet was the only service Core forwarded to. */ +export type FleetScope = ForwardedScope + +/** + * Who a forwarded request is from. Fleet's `/v1/client` only ever receives `phone` principals, and Fleet's + * `/v1/admin` and a portal module's `/v1/portal` `user` principals, but for a module's public reads, which + * receive only `public` ones. Which kinds a route accepts is the route's decision: one that serves people + * refuses a `public` principal, and the one that serves a public read refuses everything else. + * + * - `phone`: a signed-in phone session. `email` is the account's verified email, or null; it is a + * display attribute and never an identity key. + * - `user`: a signed-in person. `isOrganizationAdmin` comes from a verified identity email; `email` + * may be unverified (`emailVerified`) and is never an authorization. `organizationCapabilities` is + * what Core decided the person may do to the organization, and `scope` is what this request covers. + * - `public`: a request Core forwards for anyone, signed in or not. It names no person, not even one who is + * signed in, and covers the `public` scope only: Core vouches that it sent the request, and for nobody. + */ +export type ForwardedPrincipal = + | {kind: "phone"; mentraUserId: string; tenantId: string; sessionId: string; email: string | null} + | { + kind: "user" + mentraUserId: string + email: string | null + emailVerified: boolean + isOrganizationAdmin: boolean + organizationCapabilities: OrganizationCapability[] + scope: UserScope + } + | {kind: "public"; scope: {kind: "public"}} + +/** + * `error` values on 401 responses from the internal service API. The client treats only `invalid_token` + * from `/principal` as "this bearer token is not valid"; anything else is a service-level failure. + */ +export const INVALID_TOKEN_ERROR = "invalid_token" +export const SERVICE_UNAUTHORIZED_ERROR = "service_unauthorized" + +/** + * `error` value of the 404 that `GET /workspaces/:workspaceId` answers for an unknown workspace. The + * client reads only this 404 as "no such workspace": a 404 from anything else (a proxy, a wrong base URL, + * a Core without this API) says nothing about the workspace and is an error. + */ +export const WORKSPACE_NOT_FOUND_ERROR = "workspace_not_found" + +/** + * `error` value of the 404 that `POST /users/resolve-email` answers when no Mentra account has that + * email verified. As with `workspace_not_found`, the client reads only this 404 as "no such person". + */ +export const USER_NOT_FOUND_ERROR = "user_not_found" + +// --- Public workspace API -------------------------------------------------- +// The response bodies of Core's workspace and organization routes. Every date is an ISO 8601 string, +// so the same types serve the workspace portal, the admin portal and the Store's Developer Console. + +/** A workspace, the caller's membership in it (null for an Organization Admin who is not a member) and what the caller may do there. */ +export interface WorkspaceDetail extends WorkspaceSummary { + /** The caller's own membership, null when they have none. Their role is this, whatever `capabilities` say. */ + membership: MembershipSummary | null + capabilities: WorkspaceCapability[] + /** + * Whether the caller is an Organization Admin, who acts as an Owner in every workspace: when their + * membership's role grants less (or they have none), that is where `capabilities` come from. + * Optional for servers that predate it. + */ + organizationAdmin?: boolean + /** + * What holds the workspace from deletion: deleting it is refused while this is not empty. Optional for + * servers that predate holds. + */ + deletionHolds?: WorkspaceDeletionHold[] +} + +/** + * One row of a workspace's member list. `email` is display-only and never an authorization. `pending` + * marks a membership imported from the Store whose person has not signed in yet: it has no + * `mentraUserId` until they do, and holds its role meanwhile. + */ +export interface MemberView { + membershipId: string + mentraUserId: string | null + email: string | null + /** + * The person's name from their sign-in, null when Core has none or they haven't signed in. Optional so a + * portal still works against a Core that doesn't send it. + */ + name?: string | null + role: WorkspaceRole + startedAt: string + pending: boolean +} + +/** A pending invitation as listed to administrators. It never carries the token or its hash. */ +export interface InvitationView { + invitationId: string + email: string + role: WorkspaceRole + expiresAt: string + invitedByMembershipId: string | null +} + +/** + * An invitation as the invitee sees it before accepting: what an invitation link is for + * (`POST /invitations/peek`), and each of the invitations addressed to the signed-in person + * (`GET /invitations/mine`). It never carries the token or its hash. + */ +export interface InvitationPreview { + invitationId: string + workspaceId: string + workspaceName: string + /** The invited address. */ + email: string + role: WorkspaceRole + /** Who sent it, by email address; null when the system did, or the address is no longer known. */ + invitedByEmail: string | null + expiresAt: string +} + +// --- Mentra App workspace calls (`/api/client/workspaces`) ------------------ +// A person belongs to at most one workspace, so a phone sees one workspace, or none. + +/** The workspace the signed-in phone's person belongs to (`GET /api/client/workspaces/mine`), or null when none. */ +export interface MyWorkspace { + workspaceId: string + name: string + role: WorkspaceRole + membershipId: string +} + +/** `GET /api/client/workspaces/mine`. */ +export interface MyWorkspaceResponse { + workspace: MyWorkspace | null +} + +/** `GET /api/client/workspaces/invitations/mine`: the invitations addressed to the signed-in person. */ +export interface PendingInvitationsResponse { + invitations: InvitationPreview[] +} + +/** `POST /api/client/workspaces/invitations/:invitationId/accept`. */ +export interface AcceptInvitationResult { + workspace: MyWorkspace +} + +/** + * `POST /api/client/workspaces/invitations/:invitationId/decline`. Declining twice is idempotent. Decline opens and + * closes no membership interval. + */ +export interface DeclineInvitationResult { + invitationId: string + declined: true +} + +/** + * `POST /api/client/workspaces/leave`. A body is optional: with `workspaceId`, Core leaves that workspace only while + * the person is in it, and answers `membership_changed` (409) otherwise; without one, the person's workspace. + */ +export interface LeaveWorkspaceRequest { + workspaceId?: string +} + +/** Codes a client workspace call can fail with, so the Mentra App can map each to its own words. */ +export const CLIENT_WORKSPACE_ERRORS = { + /** The person already belongs to a workspace; leave it first. */ + alreadyInWorkspace: "already_in_workspace", + /** The only Owner cannot leave. */ + lastOwner: "last_owner", + invitationExpired: "invitation_expired", + invitationNotFound: "invitation_not_found", + emailUnverified: "email_unverified", + /** The membership changed under the call: its role, or the workspace a leave named is no longer the person's. */ + membershipChanged: "membership_changed", +} as const +export type ClientWorkspaceErrorCode = (typeof CLIENT_WORKSPACE_ERRORS)[keyof typeof CLIENT_WORKSPACE_ERRORS] + +/** `action` of the change-feed event recorded when an invitee declines. It opens and closes no interval. */ +export const INVITATION_DECLINED_ACTION = "invitation.declined" + +// --- Membership interval history (Core -> Fleet) ----------------------------- + +/** Why a membership interval ended. */ +export type MembershipIntervalEndReason = "left" | "removed" | "workspace_deleted" | "account_deleted" + +/** + * One continuous stretch of an account's membership in a workspace: one membership generation. It begins when + * the membership's account is known: for a membership imported from the Store and waiting for its person that is + * the claim (`membership.claimed`), never the import, so records observed earlier are never counted. A membership + * that has no account yet is not an interval at all. `end` is null while the membership is open. `role` is the role + * held now, or the last one before the end; a role change does not split an interval (visibility follows + * membership, not role), and `roles` lists the role intervals within it. A leave and a later re-join are two + * intervals with two `membershipId`s. + * `membership.merged_duplicate` and `membership.replaced` act on memberships with no account and so end no interval. + */ +export interface MembershipInterval { + membershipId: string + workspaceId: string + mentraUserId: string + role: WorkspaceRole + /** ISO 8601 UTC. */ + start: string + /** ISO 8601 UTC, or null while the membership is open. */ + end: string | null + endReason: MembershipIntervalEndReason | null + /** + * The role intervals within this one that overlap the lookback window, oldest first: each role from when it took + * effect (never before `start`) until the next took effect, the last until `end`. Never empty. + */ + roles: MembershipRoleInterval[] +} + +/** One role held within a membership interval. */ +export interface MembershipRoleInterval { + role: WorkspaceRole + /** ISO 8601 UTC. */ + start: string + /** ISO 8601 UTC, or null while the role is still held. */ + end: string | null +} + +/** `GET /api/internal/workspaces/workspaces/:workspaceId/members` (service `fleet` only): who is in the workspace now. */ +export interface WorkspaceMembersResponse { + /** Active memberships, oldest first. `name` is null when Core has none; Fleet then shows the full email. */ + members: MemberView[] +} + +/** + * One page of `GET /api/internal/workspaces/membership-intervals` (service `fleet` only). + * + * Core returns every interval that overlaps `[windowStart, now]`, where `windowStart` is `now` minus + * `lookbackDays` (`CLOUD_CORE_FLEET_HISTORY_MAX_DAYS`). An interval still open whose `start` is older than the + * window is returned with its real `start` and `end: null`, so long-standing members never vanish. One that ended + * before `windowStart` is not returned. `feedSeq` is the change-feed position the read is consistent with: a + * consumer applies feed events after it. `next` is an opaque cursor, or null on the last page. + */ +export interface MembershipIntervalsResponse { + lookbackDays: number + windowStart: string + feedSeq: number + intervals: MembershipInterval[] + next: string | null +} + +/** A credential as shown to people (a workspace `msk_` key or an organization `mak_` operator key). It never includes the token or its hash. */ +export interface CredentialView { + credentialId: string + prefix: "msk" | "mak" + name: string + /** `__…`, e.g. `msk_prod_…abcd`. */ + display: string + workspaceId: string | null + scopes: string[] + packageNames: string[] + createdByEmail: string | null + issuedByService: string | null + expiresAt: string | null + lastUsedAt: string | null + createdAt: string +} + +/** One entry of a workspace's audit log, newest first. `target`, `before` and `after` are snapshots whose shape depends on `action`. */ +export interface AuditEventView { + eventId: string + action: string + actor: { + kind: "user" | "credential" | "service" | "system" + email: string | null + credentialId: string | null + service: string | null + } + target: Record | null + before: Record | null + after: Record | null + occurredAt: string +} + +/** + * What the caller may do to this deployment (the organization). `workspaceCreation` says whether this + * caller may create a workspace: on hosted Core anyone with a verified email may; a Private Cloud may + * limit creation to Organization Admins (`CLOUD_CORE_WORKSPACE_CREATION`). + */ +export interface OrganizationView { + capabilities: OrganizationCapability[] + workspaceCreation: {allowed: boolean; reason: "email_unverified" | "organization_admins_only" | "not_a_person" | null} +} + +// --- The miniapp registry ---------------------------------------------------- +// +// Core's miniapp registry, over the signed service API at `/api/internal/registry/*`. Fleet checks and names +// miniapps (`check`, `lookup`); the directory reads and archives entries (`entries`, `archive`). The phone's own +// registry calls, and the wire types they share with these, are in `@mentra/cloud-protocol` (`miniapp-registry.ts`). + +/** The most URLs one `check` may name. */ +export const REGISTRY_CHECK_MAX_URLS = 50 +/** The most package names one `lookup` may name. */ +export const REGISTRY_LOOKUP_MAX_PACKAGES = 500 +/** `403`: the workspace `check` names isn't active, or the person it names isn't a live account. */ +export const NOT_A_MEMBER_ERROR = "not_a_member" +/** `404` from `entries`: the registry has no entry for the URL. */ +export const REGISTRY_ENTRY_NOT_FOUND_ERROR = "not_found" + +/** The age ratings a `miniapp.json` may declare. */ +export type RegistryAgeRating = "4+" | "9+" | "13+" | "16+" | "18+" + +/** + * One registry entry, as Core shows it. The same shape as `RegistryEntryView` in `@mentra/cloud-protocol`, which + * the phone's registry calls answer with. + */ +export interface RegistryEntryView { + /** The normalized miniapp URL: the entry's key. */ + url: string + packageName: string + registrableDomain: string + /** Null when Core knows only the package name, or doesn't show this caller more (see each route). */ + name: string | null + version: string | null + ageRating: RegistryAgeRating | null + iconUrl: string | null + /** `verified`: Core read the URL's `miniapp.json` itself. `phone_reported`: Core couldn't; a phone reported it. */ + verification: "verified" | "phone_reported" + /** Its server asks for sign-in. */ + private: boolean + /** `archived` when its own status is, or when an archive rule covers it. */ + status: "active" | "archived" + /** ISO 8601. */ + firstRegisteredAt: string + /** ISO 8601, or null when Core has never read it. */ + lastVerifiedAt: string | null +} + +/** + * Core's verified copy of a served `miniapp.json`. The fields every copy has are typed here; the rest are kept as + * served. `ServedMiniappManifestSchema` in `@mentra/cloud-protocol` parses it in full. + */ +export interface RegistryManifest { + packageName: string + version: string + name: string + description?: string + /** Relative to the miniapp URL, or an absolute URL. */ + icon?: string + ageRating?: RegistryAgeRating + /** The directory's listing: the optional category and screenshots. Not checked by Core. */ + listing?: unknown + bundle: {url: string; sha256: string} + [field: string]: unknown +} + +/** `GET /api/internal/registry/entries?url=` (the directory): an entry and Core's verified `miniapp.json`. */ +export interface RegistryEntryDetail extends RegistryEntryView { + /** Null unless the entry is verified, and always for a private entry. */ + manifest: RegistryManifest | null +} + +export interface RegistryEntryResponse { + entry: RegistryEntryDetail +} + +/** + * What `check` found at a URL: + * - `accepted`: Core read a valid `miniapp.json` whose package name passes the domain rule; + * - `accepted_unverified`: Core couldn't read it, and holds a phone's report of it, or its server asks for sign-in + * and refused the assigning admin's token; + * - `archived`: an archive rule covers it; + * - `not_a_miniapp`: an invalid `miniapp.json`, a package name its domain doesn't own, or not a public HTTPS URL; + * - `unreachable`: Core couldn't read it and no phone has reported it; + * - `unknown`: Core didn't finish checking it in time, or the admin has registered too many URLs this hour. Never a + * yes: ask again later. + */ +export type RegistryCheckStatus = + | "accepted" + | "accepted_unverified" + | "archived" + | "not_a_miniapp" + | "unreachable" + | "unknown" + +export const REGISTRY_CHECK_STATUSES: readonly RegistryCheckStatus[] = [ + "accepted", + "accepted_unverified", + "archived", + "not_a_miniapp", + "unreachable", + "unknown", +] + +/** `POST /api/internal/registry/check` (Fleet): the URLs an admin is assigning, at most 50. */ +export interface RegistryCheckRequest { + /** Each a miniapp URL, normalized as `normalizeMiniappUrl` does. */ + urls: string[] + /** The assigning workspace: a private miniapp's token names it. */ + workspaceId: string + /** The assigning admin: the person registering an unknown URL. */ + mentraUserId: string +} + +/** One URL's answer, in the order asked, with the URL as it was sent. */ +export interface RegistryCheckResult { + url: string + status: RegistryCheckStatus + /** The URL's package; null when Core doesn't know it. */ + packageName: string | null + /** The miniapp's name; null when Core doesn't know it, or for a private miniapp whose server refused the admin. */ + name: string | null + /** The icon's absolute HTTPS URL, under the same rule as `name`. */ + iconUrl: string | null + /** Its server asks for sign-in. */ + private: boolean + /** ISO 8601: when Core answered for this URL. */ + checkedAt: string +} + +export interface RegistryCheckResponse { + results: RegistryCheckResult[] +} + +/** `POST /api/internal/registry/lookup` (Fleet): names for a workspace's views, for at most 500 packages. */ +export interface RegistryLookupRequest { + workspaceId: string + packageNames: string[] +} + +/** + * A package as a workspace's views name it: from the package's most recently verified active entry (a + * phone-reported one when none is verified). `archived` is true when every entry for the package is archived. A + * private miniapp's `name` and `iconUrl` are null unless the workspace assigned the package through Fleet. + */ +export interface RegistryLookupEntry { + name: string | null + iconUrl: string | null + private: boolean + archived: boolean +} + +export interface RegistryLookupResponse { + /** Every package asked about; null for one the registry has no entry for. */ + entries: Record +} + +/** What an archive rule names: a miniapp URL, a package name, a registrable domain, or a `mentraUserId`. */ +export type RegistryArchiveRuleKind = "url" | "package" | "domain" | "account" + +export interface RegistryArchiveRule { + kind: RegistryArchiveRuleKind + value: string +} + +/** `POST /api/internal/registry/archive` (the directory): a staff member archives through the directory. */ +export interface RegistryArchiveRequest { + rule: RegistryArchiveRule + reason: string + /** The staff member, recorded as the actor (`store:`) in Core's admin audit log. */ + actorEmail: string +} + +export interface RegistryArchiveResponse { + /** The rule as Core stores it (a URL normalized, a domain lowercased). */ + rule: RegistryArchiveRule + /** False when the rule already existed; it keeps its first reason and author. */ + created: boolean + /** How many entries this call moved to archived. */ + entriesArchived: number +} diff --git a/cloud-v2/packages/workspace-contract/tsconfig.json b/cloud-v2/packages/workspace-contract/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..14d2afe6bd76cd85537e61be150c4c75f5e1296e --- /dev/null +++ b/cloud-v2/packages/workspace-contract/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": {"composite": true, "outDir": "./dist", "rootDir": "./src"}, + "include": ["src/**/*"] +} diff --git a/cloud-v2/packages/workspace-ui/README.md b/cloud-v2/packages/workspace-ui/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4feacc050770c10fe0311ce2316cc1dd94a190ca --- /dev/null +++ b/cloud-v2/packages/workspace-ui/README.md @@ -0,0 +1,529 @@ +# @mentra/workspace-ui + +Shared React screens for Core workspaces: a picker, members, invitations, keys, +settings, an audit log and the invitation-accept page. The workspace portal and the admin +portal use it directly; the Developer Console vendors it. All of them call the same JSON +API, so the package only needs to know where that API is mounted. + +It also holds the workspace portal's Licenses page: the +view, its header actions, the cards, the buying dialogs, the billing client, and the +strings and formatting they are worded with (see [Licenses](#licenses)). + +It also holds the workspace portal's frame and controls, for any Mentra site that should +look like the portal: the sidebar shell, the workspace switcher, the brand marks, a +one-column layout, cards, dialogs, badges and form fields (see [Shell](#shell)). + +A **workspace** is a group of people with permissions inside an organization (one Core +deployment). Roles are `member`, `developer`, `admin` and `owner`. + +## Use + +```tsx +import {QueryClient, QueryClientProvider} from "@tanstack/react-query" +import {createWorkspaceApi, WorkspaceMembersPanel} from "@mentra/workspace-ui" + +// "/api/portal/workspaces" in the workspace portal, "/api/admin/workspaces" in the admin portal. +const api = createWorkspaceApi({basePath: "/api/portal/workspaces"}) +const queryClient = new QueryClient() + +function Page({workspaceId}: {workspaceId: string | null}) { + return ( + + {workspaceId ? : null} + + ) +} +``` + +The components must render inside a `QueryClientProvider`. Query keys start with the +API's `basePath`, so two APIs can share one client without sharing data. + +`react`, `react-dom` and `@tanstack/react-query` are peer dependencies: the site that +renders the screens provides them, so the screens and the site share one React and one +query client context. Only the `cloud-v2` workspace links this package; the root and +`sdk` workspaces exclude it (`!…/workspace-ui` in their `workspaces`). A package linked by +two installs resolves its peers from whichever install ran last, which would give the +screens a second React (and every hook a null dispatcher). Each site's +`shared-react.test.ts` checks that the screens and the site resolve the same copies. + +| Export | What it is | +| --- | --- | +| `createWorkspaceApi({basePath, fetch?, credentials?})` | Typed client for every route; throws `WorkspaceApiError` | +| `createBillingApi({locale, base?, fetch?, credentials?})`, `BillingApi` | Typed client for billing's `catalog`, `status`, `purchase` and `session`; every answer is parsed with the contract's schemas. `base` defaults to `/api/portal/billing`; `locale` rides on every request | +| `BillingScope`, `workspaceScope(id)` | Whose billing a call is about: a workspace's. A license belongs to a workspace and to nothing else | +| `BillingRefusedError`, `BillingUnavailableError`, `BillingContractError`, `billingErrorMessage` | A refusal billing worded with a code, a billing that could not answer, one that answered off-contract (`BillingContractError`, a `BillingUnavailableError` the queries do not retry), and the sentence for any | +| `CreateWorkspaceForm`, `useCreateWorkspace` | Create a person's first workspace from just its name (the first-run screen); the new workspace's detail is cached and the list refreshed. A person belongs to one workspace, so nothing offers a second | +| `WorkspaceMembersPanel` (`showUserIds?`, `licenses?`, `locale?`) | Members (with a count): name over email, role, licenses and joined, and a row menu ("…") for role changes and removal, which asks in a dialog; `showUserIds` adds each member's copyable Mentra user id (for Organization Admins, who need it to recover ownership); `licenses` adds the read-only Licenses column (see [Members' licenses](#members-licenses)) | +| `WorkspaceInvitationsPanel` | Invite by email, and the pending invitations with Resend and Revoke, in one card | +| `WorkspaceInviteDialog` (`open`, `onClose`) | Invite by email and role in a dialog; the link is shown once after sending | +| `WorkspacePendingInvitationsPanel` | The pending invitations alone (Resend, Revoke), for a member page that invites through the dialog; renders nothing when none are pending | +| `WorkspaceCredentialsPanel` | The workspace's `msk_` keys; the token is shown once, with a copy button | +| `WorkspaceSettingsPanel` (`onDeleted?`, `onLeft?`) | Name and workspace ID (with copy), then a danger zone to leave or delete | +| `WorkspaceAuditPanel` | The workspace's audit log, paged: each event a sentence ("Changed priya@… from Member to Developer"), with the raw record behind Show details | +| `WorkspaceLicensesView`, `WorkspaceLicensesHeaderActions` | The workspace's Licenses page, and the buttons for the title bar (Billing & invoices ↗, Buy licenses); props in [Licenses](#licenses) | +| `LicenseCard` (`card`, `view`, `scope`, `billing`, `navigateOut`, `locale`, …) | One product's card: its icon, name and feature chips (no description: that is the catalog's), status badge, facts (Licenses, Renews or Ends, Cost), the notices for a failed or unfinished payment, who holds its licenses, and a "…" menu for billing's other actions; `view` is `workspace` or `member` | +| `SeatStrip`, `SeatRoster`, `AvatarStack`, `PeoplePickerDialog`, `seatHolders` | A product's licenses: the folded strip, the roster (Unassign, available licenses, search past 8 people), and the people picker that assigns them; `seatHolders` names who holds them | +| `CatalogGrid`, `CatalogDialog`, `BuyDialog`, `CatalogCard`, `canBuy` | Buying from billing's catalog: the grid an owner with nothing yet is offered, the "Buy licenses" dialog, a workspace's licenses step, and one product's card | +| `PurchaseDialog`, `TestModeBanner`, `LicensesUnavailable`, `PURCHASE_POLL_MS`, `PURCHASE_TIMEOUT_MS` | The dialog back from checkout (setting up, ready, or not in Core after a minute, with OK), the banner and state around the cards, and the pace of the poll after checkout (2 seconds, for a minute) | +| `useHostedAction`, `HostedFeedback`, `NavigateOut`, `PortalTab` | How every ↗ button leaves the portal for a hosted page, its refusal in words, and the host's two ways out (see [Licenses](#licenses)) | +| `ConfirmDialog` (`title`, `description`, `cancelLabel`, `confirmLabel`, `typeToConfirm?`, `onConfirm`, `onClose`), `useAsking`, `MembersLicenses` | A question in a modal for what can't be taken back (Unassign, Remove, Leave, Delete, Revoke): Cancel and a destructive button, a refusal shown inside with focus back on the button (a throw from `onConfirm` becomes the generic one), busy while the request is out, and `typeToConfirm` for a name to type back first; `useAsking` is how a list of rows opens one and where focus goes when it closes; and the source `WorkspaceMembersPanel` takes (see [Members' licenses](#members-licenses)) | +| `ProductIcon`, `ProductChip`, `FeatureChips` | A product's look: its icon (a letter tile when it has none or it fails to load), icon and short name, and its feature chips (only with more than one feature) | +| `Notice`, `Fact`, `Skeleton`, `StatusBadge`, `HostedPageButton`, `isHeldLicense` | The pieces the cards are made of: a status notice (`warn`, `info`, `neutral`), a label and value for a `
`, a loading bar, a badge, a button that leaves the portal (its ↗ is an icon, so its name is the label alone), and the guard for a card Core also lists | +| `joinLicenses`, `fitFor`, `seatCounts`, `holdsSeat`, `listedAction` | The page's logic, with no schemas at run time: Core's licenses joined to billing's entries and the catalog, in the page's order; what fits a product's available licenses; and the rules that gate what is offered | +| `licenseStrings`, `refusalMessage` | Every sentence these pages show, in one module (see [Strings](#strings)) | +| `formatMoney`, `formatRecurrence`, `formatDay`, `formatDayShort`, `formatDate`, `priceLine`, `costFact`, `taxNote`, `renewalCadence`, `fitNote`, `holderNames`, `nameList`, `groupCardNumber` | Billing's typed values as text, in the portal's locale (see [Formatting](#formatting)) | +| `InvitationAcceptView` (`token`, `onAccepted(workspaceId)`, `onDismiss?`, `viewerEmail?`, `onSwitchAccount?`, `onGone?`) | What an invitation link opens; for someone else's invitation it says so and offers Switch account instead of Accept | +| `InvitationAcceptCard`, `useAcceptInvitation(api, {token} \| {invitationId}, …)`, `isInvitationForOtherAccount` | The same card for an invitation the host already has (one of `myInvitationsQuery`), and accepting it | +| `describeAuditEvent`, `plainText` | An audit event as a sentence, for other screens | +| `SecretDialog` (`name`, `token`, `onDone`) | The show-once dialog for a new credential, for other screens that mint one (the admin portal's operator keys) | +| `Button`, `buttonVariants`, `Input`, `Label`, `NativeSelect`, `Textarea` | Mentra's controls, for a host's own screens: one pill button system (`default`, `secondary`, `destructive-secondary`, `destructive`, `ghost`, `link`), pill inputs, native selects drawn to match, and a multi-line field drawn like the input | +| `Card`, `CardHeader`, `CardTitle`, `CardDescription`, `CardAction`, `CardContent`, `CardFooter` | The bordered 24px card the panels sit in | +| `Dialog` (`open`, `onClose`, `title`, `description?`) | A modal on the platform's ``; its content renders only while open | +| `SidePanel` (`open`, `onClose`, `title`, `description?`) | A modal `` as a 30rem sheet from the right (full screen on a phone) | +| `Menu` (`label`, `trigger`, `items`, `align?`, `variant?`, `size?`) | A button that opens a list of `{key, label, onSelect, disabled?, destructive?}` items, with the keys a menu button has | +| `Stepper` (`value`, `onChange`, `min?`, `max?`, `label`, `decrementLabel`, `incrementLabel`) | A license-count control: minus, an editable number and plus, and `onChange` only ever gets a whole number within the bounds | +| `Checkbox` (`label?`), `Switch`, `Meter` (`used`, `total`) | A styled native checkbox, a native switch, and the bar for licenses assigned (dark up to the quantity, amber past it) | +| `Panel` (`title`, `description?`, `count?`, `actions?`) | A titled card for one panel's content, with a count beside the title and actions on the right | +| `Badge` (`tone?`) | A small chip: `outline` (the default, "You"), or filled `success` (green), `warn` (amber) or `neutral` (grey) for a status | +| `ErrorNotice` (`error`, `tone?`), `AlertText`, `Loading`, `QueryGate` (`result`, `loadingLabel?`, `tone?`, `children(data)`) | An error in words (amber, as the sign-in page's notice, or `tone="neutral"`), the spinner with what is loading, and a query's loading and failed-load states with Try again | +| `Avatar`, `WorkspaceAvatar`, `Count`, `Spinner` | A person's initials, a workspace's letter tile, a count beside a heading, the loading spinner | +| `AppShell`, `AccountFooter`, `WorkspaceLabel`, `WorkspaceSwitcher`, `SWITCHER_ITEM_CLASS` | The portal's frame, its account menu, its static workspace block, and the menu for hosts that list several workspaces (see [Shell](#shell)) | +| `MentraMark`, `MentraLogo`, `BrandPage` (`title`) | The Mentra mark, the logo with its wordmark (inline SVG, no asset loader), and a page that is one card under the logo | +| `CenteredLayout` (`userEmail`, `onSignOut?`, `signingOut?`) | A page that is one focused task: the logo and Sign out across the top, one centered column | +| `useDismiss(ref, open, close)` | Closes a popover on a press outside `ref` or on Escape | +| `expiryFromDateInput` | The end of a `` day as an ISO string, or null | +| `effectiveRole`, `actsAsOrganizationAdmin`, `assignableRoles`, `can`, `ROLE_LABELS`, `ROLE_DESCRIPTIONS` | The capability helpers the panels use, whether an Organization Admin's powers go beyond their membership, and a one-line description of each role | +| `workspaceListQuery`, `workspaceDetailQuery`, `invitationPreviewQuery`, `myInvitationsQuery`, `workspaceKeys` | Query options and keys, for a host that shows the same data (a workspace switcher) | +| `billingCatalogQuery`, `billingStatusQuery`, `billingKeys`, `licensesQuery` | Query options and keys for billing's catalog and status and Core's licenses, for a host that shows the same data; a workspace's billing keys sit under `["workspace-ui", "billing", "workspace", id]` | +| `errorMessage`, `isInvitationGone`, `isWorkspaceChangedError`, `WORKSPACE_CHANGED_MESSAGE` | Error text, whether an invitation can never be accepted, and the 409 handling | +| `isLicenseChangedError` | Whether assigning or unassigning a license failed because the product changed under the caller (409 `no_seats_available`, 404 `license_not_found`) | + +## Behavior worth knowing + +- **Controls follow capabilities.** Each panel reads `GET {basePath}/:workspaceId` and + shows only what the viewer's capabilities allow. Role selectors offer exactly the + transitions `canChangeRole` allows. The server still checks every request, so this is + about not offering what would be refused, not about security. +- **Nobody changes their own role here.** The viewer's own row has no role selector, so + one stray keystroke cannot demote an owner. Another owner or an Organization Admin + changes it. +- **The viewer's role comes from their capabilities, not their membership.** An + organization admin acts as an owner whether or not they are a member. +- **Stale views end in a refetch.** Changes carry the workspace revision the viewer last + saw. On a 409 `membership_changed` the workspace is refetched and the panel says + "This workspace changed. Review and try again." +- **Destructive actions ask twice, in a dialog**: removing a member, revoking a key or an + invitation, leaving a workspace, and deleting one (the workspace name is typed in the + dialog). The only owner cannot leave: Leave is disabled and says why. A refused action + says why inside its dialog, which stays open for another try. +- **Resend is a new invitation.** It sends the same address the same role again; Core + supersedes the pending invitation, so only the newest link works. +- **Dialogs are the platform's ``**, opened with `showModal()`: the page behind is + inert, focus stays inside, Escape and the backdrop close it. Their content renders only + while open. +- **Secrets are shown once and never cached.** A credential's token and an invitation + link live in the panel's state until dismissed. They are not in the query or mutation + cache and never in API paths: invitation tokens travel in POST bodies. (The invitation + link itself carries its token in the invitee's page URL, by design.) They stay on screen + even if a background refetch fails: a failed refetch keeps the data already loaded, and + only a query that has never loaded shows an error. +- **Credentials need a member who can publish.** Core ties a credential to its creator's + membership, so the create form is shown only to members with the developer role or + above. An organization admin outside the workspace can list and revoke but not create. + +## Styling + +The screens look like Mentra's sign-in page (`websites/account`): Red Hat Display, black and +grey pill buttons, pill inputs and selects, bordered 24px cards on a plain background, +the green focus ring, and amber and green notices. The tokens are defined once, in +`styles/mentra.css` (exported as `@mentra/workspace-ui/mentra.css`): the sign-in page's +palette as `--mentra-*` variables, mapped onto the shadcn theme names the components use +(`background`, `foreground`, `primary`, `secondary`, `muted`, `destructive`, `border`, +`ring`, …) plus brand names (`surface`, `hover`, `brand`, `info`, `error`), the card, menu +and notice radii, the dialog and menu shadows, the font and the focus ring. + +The components are Tailwind v4 utility classes. In the stylesheet that imports Tailwind, +import the tokens and scan this package's sources (Tailwind only generates the classes it +finds): + +```css +@import "tailwindcss"; +@import "@mentra/workspace-ui/mentra.css"; +@source "../node_modules/@mentra/workspace-ui/src"; +``` + +The `@source` path is relative to that stylesheet (this one is for a stylesheet in +`src/`, next to `node_modules/`). The tokens load Red Hat Display from `/fonts`, so the +site serves the sign-in page's `public/fonts` (with its `OFL.txt`), keeps those URLs out +of the bundle (`external: ["/fonts/*"]` in `Bun.build`) and preloads both weights, as the +workspace portal's and the admin portal's `build.ts` do. Nothing is loaded from another +origin. + +## Shell + +`AppShell` is the workspace portal's frame: a 264px sidebar with the brand and a +switcher on top, the sections, links to other sites and the account at the bottom, a +sticky page header over the content, and on a phone the sidebar as a drawer behind a +menu button. It needs no `QueryClientProvider` and knows no router. + +```tsx +import {AppShell, WorkspaceSwitcher, type ShellLinkComponent} from "@mentra/workspace-ui" +import {Link, useRouterState} from "@tanstack/react-router" + +// The shell renders every in-app address through the host's link. +const ShellLink: ShellLinkComponent = ({href, ...props}) => + +function ConsoleShell({children}: {children: React.ReactNode}) { + const pathname = useRouterState({select: state => state.location.pathname}) + return ( + + } + nav={[{key: "main", items: [{key: "apps", label: "Miniapps", icon: Boxes, href: "/apps"}]}]} + active={item => item.href !== undefined && pathname.startsWith(item.href)} + accountItems={[{key: "billing", label: "Billing", icon: CreditCard, href: "/billing"}]} + title="Miniapps" + userEmail={email} + onSignOut={signOut} + > + {children} + + ) +} +``` + +- **Items go somewhere by address or by action.** A section, an account-menu item or a + switcher workspace has either an `href`, rendered with `linkComponent`, or an + `onSelect`, rendered as a ` + + ))} + setBuying(null)} /> + + ); +} + +/** `grid`'s rig, around the seats step (`Chooser`) instead of the grid. */ +function chooser(options: GridOptions = {}) { + const out = ways(); + const stub = stubBilling(); + const ui = ( + + ); + return { ui, ...out, ...stub }; +} + +// ---- the catalog grid --------------------------------------------------------------------------------------------- + +describe("the catalog grid", () => { + test("a workspace's reads 'Buy licenses for your members', with one card per product, its price and Buy", async () => { + const { ui } = grid(); + await mount(ui); + expect(find("h2").textContent).toBe("Buy subscriptions for your members"); + expect(text()).not.toContain("secure payment page"); + expect(findAll("[data-product]").map((element) => element.getAttribute("data-product"))).toEqual([ + "mentra.call.unlimited", + "mentra.fleet", + "mentra.example", + ]); + expect(find("h3", card("mentra.call.unlimited")).textContent).toBe("Mentra Call Unlimited"); + // Billing's description is not drawn: the name, the price and Buy say enough. + expect(card("mentra.call.unlimited").textContent).not.toContain("Unlimited Teams calls in Mentra Call."); + expect(byText("$29 per user per month", "p", card("mentra.call.unlimited"))).toBeTruthy(); + expect(byText("$15 per user per month", "p", card("mentra.fleet"))).toBeTruthy(); + expect(byText("$9 per user per month", "p", card("mentra.example"))).toBeTruthy(); + for (const element of findAll("[data-product]")) expect(buttons(element).map((button) => button.textContent)).toEqual(["Buy"]); + }); + + test("features are a list only with more than one, each with the miniapp it works in", async () => { + const { ui } = grid(); + await mount(ui); + // One feature is the product: no list. + expect(findAll("ul", card("mentra.call.unlimited"))).toHaveLength(0); + expect(findAll("li", card("mentra.fleet")).map((item) => item.textContent)).toEqual([ + "Managed phones and glasses", + "Miniapp assignments", + "Usage reports", + ]); + expect(findAll("li", card("mentra.example")).map((item) => item.textContent)).toEqual(["Feature one in Mentra Call", "Feature two"]); + }); + + test("a product with no icon draws a letter tile, and one with an icon draws billing's image", async () => { + const { ui } = grid(); + await mount(ui); + expect(find("img", card("mentra.call.unlimited")).getAttribute("src")).toBe("/api/portal/billing/ui/icons/mentra-call.png"); + expect(findAll("img", card("mentra.fleet"))).toHaveLength(0); + }); + + test("with nothing to show it draws nothing, not a heading over no cards", async () => { + const { container } = await mount(grid({ products: [] }).ui); + expect(container.textContent).toBe(""); + }); + + test("an entry without an offer shows no price and no Buy, and the rest of the card as it is", async () => { + const { ui } = grid({ products: [callFor({ offer: undefined }), fleet()] }); + await mount(ui); + const bare = card("mentra.call.unlimited"); + expect(find("h3", bare).textContent).toBe("Mentra Call Unlimited"); + expect(bare.textContent).not.toContain("Unlimited Teams calls in Mentra Call."); + expect(bare.textContent).not.toContain("$"); + expect(buttons(bare)).toHaveLength(0); + expect(buttons(card("mentra.fleet")).map((button) => button.textContent)).toEqual(["Buy"]); + }); + + test("Buy is named for its product to a screen reader, without changing its label", async () => { + await mount(grid().ui); + for (const product of ["mentra.call.unlimited", "mentra.fleet"]) { + const buy = buttonNamed("Buy", card(product)); + const described = buy.getAttribute("aria-describedby")!.split(" ").map((id) => document.getElementById(id)?.textContent); + expect(described).toContain(find("h3", card(product)).textContent!); + } + }); + + test("there is no native select, and nothing names the payment processor", async () => { + await mount(grid().ui); + expect(findAll("select")).toHaveLength(0); + expect(text()).not.toMatch(NAMES_THE_PROCESSOR); + }); +}); + +// ---- what the owner already holds --------------------------------------------------------------------------------- + +describe("a product the owner holds", () => { + const held = [licenseBillingFor({ quantity: 5 })]; + + test("a workspace sees 'You have 5 licenses' and 'Add licenses', and no Buy for it", async () => { + await mount(grid({ licenses: held }).ui); + const mine = card("mentra.call.unlimited"); + expect(mine.textContent).toContain("You have 5 subscriptions"); + expect(buttons(mine).map((button) => button.textContent)).toEqual(["Buy more seats"]); + expect(mine.textContent).not.toContain("$29"); + // The others are still for sale. + expect(buttons(card("mentra.fleet")).map((button) => button.textContent)).toEqual(["Buy"]); + }); + + test("one license is 'You have 1 license'", async () => { + await mount(grid({ licenses: [licenseBillingFor({ quantity: 1 })] }).ui); + expect(card("mentra.call.unlimited").textContent).toContain("You have 1 subscription"); + expect(card("mentra.call.unlimited").textContent).not.toContain("1 subscriptions"); + }); + + test("Add licenses is offered only when billing lists it for that license", async () => { + const noAddSeats = licenseBillingFor({ quantity: 5, actions: [{ kind: "cancel", fallbackLabel: "Cancel" }] }); + await mount(grid({ licenses: [noAddSeats] }).ui); + expect(card("mentra.call.unlimited").textContent).toContain("You have 5 subscriptions"); + expect(buttons(card("mentra.call.unlimited"))).toHaveLength(0); + }); + + test("a product billing won't sell now (buy is null) has no Buy, and keeps its price", async () => { + const inProgress = callFor({ offer: workspaceOffer(2900, { buy: null }) }); + await mount(grid({ products: [inProgress, fleet()] }).ui); + const bare = card("mentra.call.unlimited"); + expect(buttons(bare)).toHaveLength(0); + expect(bare.textContent).toContain("$29 per user per month"); + expect(bare.textContent).not.toContain("You have"); + }); + + test("Add licenses asks billing for add_seats on that license and goes to its page", async () => { + const { ui, session, leave, openTab } = grid({ licenses: [licenseBillingFor({ licenseId: "lic_call_9", quantity: 5 })] }); + await mount(ui); + await click(buttonNamed("Buy more seats")); + await settle(); + expect(session).toHaveBeenCalledTimes(1); + expect(session.mock.calls[0]).toEqual([WS, { action: "add_seats", licenseId: "lic_call_9" }]); + // The card's button never asks for a license for the person pressing it: that is the link's dialog alone. + expect("forMe" in session.mock.calls[0]![1]).toBe(false); + expect(leave).toHaveBeenCalledWith(PAY); + // It returns to the portal, so no other tab is opened for it. + expect(openTab).not.toHaveBeenCalled(); + }); + + test("on the wire, Add licenses sends no forMe", async () => { + const wire = payingAt(PAY); + const out = ways(); + await mount( + , + ); + await click(buttonNamed("Buy more seats")); + await settle(); + expect(wire.requests.map((request) => request.body)).toEqual([{ action: "add_seats", licenseId: "lic_call_9", locale: "en-US" }]); + }); + + test("only the button that was pressed waits, when several products are held", async () => { + const pending = deferred<{ url: string }>(); + const both = [licenseBillingFor({ quantity: 5 }), licenseBillingFor({ licenseId: "lic_fleet", product: "mentra.fleet", quantity: 10 })]; + const { ui, session } = grid({ licenses: both }); + session.mockImplementation(() => pending.promise); + await mount(ui); + await click(buttonNamed("Buy more seats", card("mentra.fleet"))); + await settle(); + expect(session.mock.calls).toEqual([[WS, { action: "add_seats", licenseId: "lic_fleet" }]]); + expect(buttonNamed("Buy more seats", card("mentra.fleet")).getAttribute("aria-busy")).toBe("true"); + const other = buttonNamed("Buy more seats", card("mentra.call.unlimited")); + expect(other.disabled).toBe(true); + expect(other.hasAttribute("aria-busy")).toBe(false); + await act(async () => pending.reject(new BillingRefusedError("unknown_action", {}, 400))); + await settle(); + }); + + test("while Add licenses is being requested nothing else can be bought, and a refusal is worded", async () => { + const pending = deferred<{ url: string }>(); + const { ui, session, leave } = grid({ licenses: held }); + session.mockImplementation(() => pending.promise); + await mount(ui); + await click(buttonNamed("Buy more seats")); + await settle(); + expect(session).toHaveBeenCalledTimes(1); + expect(buttonNamed("Buy more seats").disabled).toBe(true); + expect(buttonNamed("Buy more seats").getAttribute("aria-busy")).toBe("true"); + expect(buttons(card("mentra.fleet"))[0]!.disabled).toBe(true); + await act(async () => pending.reject(new BillingRefusedError("unknown_action", {}, 400))); + await settle(); + expect(find('[role="alert"]').textContent).toBe("That isn't available for this subscription any more. Reload the page and try again."); + expect(leave).not.toHaveBeenCalled(); + expect(buttonNamed("Buy more seats").disabled).toBe(false); + }); +}); + +// ---- Add seats on a page that doesn't return --------------------------------------------------------------------- + +describe("Add licenses when billing lists it with returns: false", () => { + const detached = () => [ + licenseBillingFor({ + licenseId: "lic_call_9", + quantity: 5, + actions: [{ kind: "add_seats", fallbackLabel: "Buy more seats", returns: false }], + }), + ]; + const INVOICE = "https://invoice.example.test/i/9"; + + test("opens a tab in the click itself, asks for the session, then sends that tab there", async () => { + const pending = deferred<{ url: string }>(); + const { ui, session, events, leave, tab, openTab } = grid({ licenses: detached() }); + session.mockImplementation(() => pending.promise); + await mount(ui); + const button = buttonNamed("Buy more seats"); + let openedInTheClick = -1; + // Only the synchronous part of the click runs inside this callback: a browser allows the tab only there. + act(() => { + button.click(); + openedInTheClick = openTab.mock.calls.length; + }); + expect(openedInTheClick).toBe(1); + expect(events).toEqual(["openTab"]); + await settle(); + expect(session.mock.calls).toEqual([[WS, { action: "add_seats", licenseId: "lic_call_9" }]]); + await act(async () => pending.resolve({ url: INVOICE })); + await settle(); + expect(events).toEqual(["openTab", `go:${INVOICE}`]); + expect(leave).not.toHaveBeenCalled(); + expect(tab.close).not.toHaveBeenCalled(); + }); + + test("says to a screen reader that it opens in a new tab", async () => { + await mount(grid({ licenses: detached() }).ui); + const hint = document.getElementById(buttonNamed("Buy more seats").getAttribute("aria-describedby")!.split(" ").at(-1)!); + expect(hint?.textContent).toBe("Opens a secure billing page in a new tab"); + }); + + test("a session that fails closes the tab and says why", async () => { + const { ui, session, events, leave } = grid({ licenses: detached() }); + session.mockImplementation(async () => { + throw new BillingRefusedError("unknown_action", {}, 400); + }); + await mount(ui); + await click(buttonNamed("Buy more seats")); + await settle(); + expect(events).toEqual(["openTab", "close"]); + expect(leave).not.toHaveBeenCalled(); + expect(find('[role="alert"]').textContent).toBe("That isn't available for this subscription any more. Reload the page and try again."); + }); + + test("a blocked tab gives the page back as a link for a second click", async () => { + const out = ways({ blocked: true }); + const stub = stubBilling(); + await mount(); + await click(buttonNamed("Buy more seats")); + await settle(); + expect(out.leave).not.toHaveBeenCalled(); + const link = find("a[data-hosted-page]"); + expect(link.textContent).toBe("Open the payment page"); + expect(link.getAttribute("href")).toBe(PAY); + expect(link.getAttribute("target")).toBe("_blank"); + }); + + test("a row in the Buy licenses dialog does the same", async () => { + const out = ways(); + const stub = stubBilling(); + await mount( + {}} products={WORKSPACE_CATALOG} licenses={detached()} scope={WS} billing={stub.billing} navigateOut={out.navigateOut} />, + ); + await click(buttonNamed("Buy more seats", find('[data-product="mentra.call.unlimited"]', topDialog()))); + await settle(); + expect(out.events).toEqual(["openTab", `go:${PAY}`]); + expect(out.leave).not.toHaveBeenCalled(); + }); +}); + +// ---- the seats step ----------------------------------------------------------------------------------------------- + +describe("the licenses step", () => { + async function openBuyFleet(options: GridOptions = {}) { + const setup = chooser({ memberCount: 10, ...options }); + await mount(setup.ui); + await click(buttonNamed("Buy", card("mentra.fleet"))); + return setup; + } + + test("it is 'Buy ' with its terms (not its description), a stepper at the member count, and the member count", async () => { + await openBuyFleet({ memberCount: 14 }); + const dialog = topDialog(); + expect(find("h2", dialog).textContent).toBe("Buy Fleet"); + expect(dialog.textContent).not.toContain("Manage your members' phones and glasses, and the miniapps on them."); + expect(dialog.textContent).toContain("$15 per user per month · Renews every month. Change the number of subscriptions or cancel at any time."); + expect(stepper(dialog).getAttribute("aria-valuenow")).toBe("14"); + expect(stepper(dialog).value).toBe("14"); + expect(dialog.textContent).toContain("Your workspace has 14 members."); + expect(dialog.textContent).not.toContain("secure payment page"); + expect(dialog.textContent).not.toContain("yours once payment goes through"); + expect(buttons(dialog).map((button) => button.textContent)).toContain("Cancel"); + expect(buttonNamed("Continue to payment", dialog)).toBeTruthy(); + expect(findAll("select", dialog)).toHaveLength(0); + }); + + test("it shows '10 licenses × $15 · $150 a month · before tax', and follows the stepper", async () => { + await openBuyFleet(); + const dialog = topDialog(); + expect(byText("10 subscriptions × $15 · $150 a month · before tax", "p", dialog)).toBeTruthy(); + await click(find('[aria-label="One subscription more"]', dialog)); + expect(stepper(dialog).value).toBe("11"); + expect(byText("11 subscriptions × $15 · $165 a month · before tax", "p", dialog)).toBeTruthy(); + await click(find('[aria-label="One subscription fewer"]', dialog)); + await click(find('[aria-label="One subscription fewer"]', dialog)); + expect(byText("9 subscriptions × $15 · $135 a month · before tax", "p", dialog)).toBeTruthy(); + }); + + test("one license is '1 license × $15'", async () => { + await openBuyFleet({ memberCount: 2, products: [fleet({ offer: workspaceOffer(1500, { buy: { minSeats: 1, maxSeats: 5 } }) })] }); + await click(find('[aria-label="One subscription fewer"]', topDialog())); + expect(byText("1 subscription × $15 · $15 a month · before tax", "p", topDialog())).toBeTruthy(); + }); + + test("the stepper is bounded by minSeats and maxSeats, and the sum follows the bound", async () => { + await openBuyFleet({ memberCount: 11, products: [fleet({ offer: workspaceOffer(1500, { buy: { minSeats: 2, maxSeats: 12 } }) })] }); + const dialog = topDialog(); + const more = find('[aria-label="One subscription more"]', dialog); + const fewer = find('[aria-label="One subscription fewer"]', dialog); + expect(stepper(dialog).getAttribute("aria-valuemin")).toBe("2"); + expect(stepper(dialog).getAttribute("aria-valuemax")).toBe("12"); + await click(more); + expect(stepper(dialog).value).toBe("12"); + expect(more.disabled).toBe(true); + await press(stepper(dialog), "ArrowUp"); + expect(stepper(dialog).value).toBe("12"); + for (let step = 0; step < 12; step += 1) if (!fewer.disabled) await click(fewer); + expect(stepper(dialog).value).toBe("2"); + expect(fewer.disabled).toBe(true); + expect(byText("2 subscriptions × $15 · $30 a month · before tax", "p", dialog)).toBeTruthy(); + }); + + test("a member count outside the bounds starts at the nearest bound", async () => { + await openBuyFleet({ memberCount: 50, products: [fleet({ offer: workspaceOffer(1500, { buy: { minSeats: 3, maxSeats: 8 } }) })] }); + expect(stepper(topDialog()).value).toBe("8"); + await cleanup(); + await openBuyFleet({ memberCount: 2, products: [fleet({ offer: workspaceOffer(1500, { buy: { minSeats: 3, maxSeats: 8 } }) })] }); + expect(stepper(topDialog()).value).toBe("3"); + }); + + test("when billing's limits change while it is open the choice is held to them", async () => { + const client = new QueryClient(); + const { billing, purchase } = stubBilling(); + const out = ways(); + const dialog = (product: CatalogEntry) => ( + + {}} /> + + ); + const limits = (buy: { minSeats: number; maxSeats: number }) => fleet({ offer: workspaceOffer(1500, { buy }) }); + const view = await render(dialog(limits({ minSeats: 1, maxSeats: 500 }))); + await click(find('[aria-label="One subscription more"]', topDialog())); + await click(find('[aria-label="One subscription more"]', topDialog())); + expect(stepper(topDialog()).value).toBe("12"); + // The ceiling comes down below the choice. + await view.rerender(dialog(limits({ minSeats: 1, maxSeats: 8 }))); + expect(stepper(topDialog()).value).toBe("8"); + expect(stepper(topDialog()).getAttribute("aria-valuemax")).toBe("8"); + expect(byText("8 subscriptions × $15 · $120 a month · before tax", "p", topDialog())).toBeTruthy(); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + expect(purchase.mock.calls).toEqual([[WS, { product: "mentra.fleet", seats: 8 }]]); + }); + + test("and the floor coming up past the choice lifts it, and it stays there if the limits widen again", async () => { + const client = new QueryClient(); + const { billing } = stubBilling(); + const out = ways(); + const dialog = (minSeats: number) => ( + + {}} + /> + + ); + const view = await render(dialog(1)); + expect(stepper(topDialog()).value).toBe("10"); + await view.rerender(dialog(15)); + expect(stepper(topDialog()).value).toBe("15"); + expect(byText("15 subscriptions × $15 · $225 a month · before tax", "p", topDialog())).toBeTruthy(); + await view.rerender(dialog(1)); + expect(stepper(topDialog()).value).toBe("15"); + }); + + describe("when the catalog is read again while it is open", () => { + const withFleet = (fleetEntry: CatalogEntry) => [callFor(), fleetEntry, addOn()]; + const gridOf = (billing: BillingApi, client: QueryClient, products: readonly CatalogEntry[]) => ( + + + + ); + test("the licenses step takes the new price and limits, and the choice is held to them", async () => { + const client = new QueryClient(); + const { billing, purchase } = stubBilling(); + const view = await render(gridOf(billing, client, withFleet(fleet()))); + await click(buttonNamed("Buy", card("mentra.fleet"))); + await click(find('[aria-label="One subscription more"]', topDialog())); + await click(find('[aria-label="One subscription more"]', topDialog())); + expect(byText("12 subscriptions × $15 · $180 a month · before tax", "p", topDialog())).toBeTruthy(); + // Billing reads again: a dearer price, and a ceiling under the choice. + const dearer = fleet({ offer: workspaceOffer(1800, { buy: { minSeats: 1, maxSeats: 8 } }) }); + await view.rerender(gridOf(billing, client, withFleet(dearer))); + expect(topDialog().textContent).toContain("$18 per user per month"); + expect(stepper(topDialog()).getAttribute("aria-valuemax")).toBe("8"); + expect(stepper(topDialog()).value).toBe("8"); + expect(byText("8 subscriptions × $18 · $144 a month · before tax", "p", topDialog())).toBeTruthy(); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + expect(purchase.mock.calls).toEqual([[WS, { product: "mentra.fleet", seats: 8 }]]); + }); + + test("a product that can no longer be bought keeps the terms it was chosen with, and the step stays open", async () => { + const client = new QueryClient(); + const { billing } = stubBilling(); + const view = await render(gridOf(billing, client, withFleet(fleet()))); + await click(buttonNamed("Buy", card("mentra.fleet"))); + // Billing took the offer away (and for another owner it would be `buy: null`). + await view.rerender(gridOf(billing, client, withFleet(fleet({ offer: undefined })))); + expect(openDialogs()).toHaveLength(1); + expect(find("h2", topDialog()).textContent).toBe("Buy Fleet"); + expect(byText("10 subscriptions × $15 · $150 a month · before tax", "p", topDialog())).toBeTruthy(); + await view.rerender(gridOf(billing, client, withFleet(fleet({ offer: workspaceOffer(1500, { buy: null }) })))); + expect(openDialogs()).toHaveLength(1); + expect(byText("10 subscriptions × $15 · $150 a month · before tax", "p", topDialog())).toBeTruthy(); + // Gone from the catalog altogether. + await view.rerender(gridOf(billing, client, [callFor(), addOn()])); + expect(openDialogs()).toHaveLength(1); + expect(byText("10 subscriptions × $15 · $150 a month · before tax", "p", topDialog())).toBeTruthy(); + }); + }); + + test("with no maxSeats the sum still never leaves the safe integers", async () => { + // $10 billion a seat: 9,007 seats is the most whose total a number can hold exactly. + const huge = fleet({ offer: workspaceOffer(1_000_000_000_000, { buy: { minSeats: 1 } }) }); + await openBuyFleet({ memberCount: 9000, products: [huge] }); + const dialog = topDialog(); + expect(stepper(dialog).getAttribute("aria-valuemax")).toBe("9007"); + for (let step = 0; step < 10; step += 1) await press(stepper(dialog), "ArrowUp"); + expect(stepper(dialog).value).toBe("9007"); + expect(find('[aria-label="One subscription more"]', dialog).disabled).toBe(true); + }); + + test("'before tax' appears only when tax is excluded", async () => { + const withTax = (tax: string) => [fleet({ offer: workspaceOffer(1500, { tax }) })]; + await openBuyFleet({ products: withTax("included") }); + expect(byText("10 subscriptions × $15 · $150 a month · including tax", "p", topDialog())).toBeTruthy(); + expect(topDialog().textContent).not.toContain("before tax"); + await cleanup(); + await openBuyFleet({ products: withTax("none") }); + expect(byText("10 subscriptions × $15 · $150 a month", "p", topDialog())).toBeTruthy(); + await cleanup(); + await openBuyFleet({ products: withTax("reverse_charge") }); + expect(byText("10 subscriptions × $15 · $150 a month", "p", topDialog())).toBeTruthy(); + }); + + test("the sum is in the price's currency and recurrence", async () => { + const yearly: Price = { scheme: "per_seat", unit: { amountMinor: 14000, currency: "EUR" }, recurrence: { interval: "year", count: 1 } }; + await openBuyFleet({ products: [fleet({ offer: workspaceOffer(0, { price: yearly, tax: "included" }) })] }); + const dialog = topDialog(); + expect(dialog.textContent).toContain("€140 per user per year · Renews every year."); + expect(byText("10 subscriptions × €140 · €1,400 a year · including tax", "p", dialog)).toBeTruthy(); + }); + + test("Continue to payment calls purchase({product, seats}) and goes to the page it answers", async () => { + const { billing, requests } = payingAt(PAY); + const { leave } = await openBuyFleet({ billing }); + const dialog = topDialog(); + await click(find('[aria-label="One subscription more"]', dialog)); + await click(buttonNamed("Continue to payment", dialog)); + await settle(); + expect(requests).toEqual([ + { method: "POST", path: "/api/portal/billing/workspaces/ws_acme/purchase", body: { product: "mentra.fleet", seats: 11, locale: "en-US" } }, + ]); + expect(leave).toHaveBeenCalledTimes(1); + expect(leave).toHaveBeenCalledWith(PAY); + }); + + test("a purchase always returns to the portal, so it opens no other tab", async () => { + const { leave, openTab } = await openBuyFleet(); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + expect(leave).toHaveBeenCalledWith(PAY); + expect(openTab).not.toHaveBeenCalled(); + }); + + test("it hands the client the workspace's scope and exactly {product, seats}", async () => { + const { purchase, leave } = await openBuyFleet(); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + expect(purchase.mock.calls).toEqual([[WS, { product: "mentra.fleet", seats: 10 }]]); + expect(leave).toHaveBeenCalledWith(PAY); + }); + + test("Continue is a button that leaves the portal: its label stays the label, and it can't be pressed twice", async () => { + const pending = deferred<{ url: string }>(); + const setup = chooser({ memberCount: 14 }); + setup.purchase.mockImplementation(() => pending.promise); + await mount(setup.ui); + await click(buttonNamed("Buy", card("mentra.fleet"))); + const dialog = topDialog(); + const go = buttonNamed("Continue to payment", dialog); + expect(go.hasAttribute("data-hosted-page")).toBe(true); + expect(document.getElementById(go.getAttribute("aria-describedby")!)!.textContent).toBe("Opens a secure billing page"); + // Two presses before anything has re-rendered, and one after: a single checkout. + await click(go); + await click(go); + await settle(); + await click(go); + expect(setup.purchase).toHaveBeenCalledTimes(1); + expect(go.disabled).toBe(true); + expect(go.getAttribute("aria-busy")).toBe("true"); + await act(async () => pending.resolve({ url: PAY })); + await settle(); + expect(setup.leave).toHaveBeenCalledTimes(1); + }); + + test("Cancel and Escape close it without buying, and reopening starts fresh", async () => { + const { purchase, leave } = await openBuyFleet(); + await click(find('[aria-label="One subscription more"]', topDialog())); + expect(stepper(topDialog()).value).toBe("11"); + await click(buttonNamed("Cancel", topDialog())); + expect(openDialogs()).toHaveLength(0); + await click(buttonNamed("Buy", card("mentra.fleet"))); + expect(stepper(topDialog()).value).toBe("10"); + await click(find('[aria-label="One subscription more"]', topDialog())); + await escape(); + expect(openDialogs()).toHaveLength(0); + await click(buttonNamed("Buy", card("mentra.fleet"))); + expect(stepper(topDialog()).value).toBe("10"); + expect(purchase).not.toHaveBeenCalled(); + expect(leave).not.toHaveBeenCalled(); + }); + + test("a click on the backdrop closes it too", async () => { + const { purchase } = await openBuyFleet(); + expect(openDialogs()).toHaveLength(1); + // The content fills the dialog, so a click that lands on the dialog itself is a click on the backdrop. + await click(topDialog()); + expect(openDialogs()).toHaveLength(0); + expect(purchase).not.toHaveBeenCalled(); + }); + + test("closing it while the request is out doesn't send the browser away afterwards", async () => { + const pending = deferred<{ url: string }>(); + const setup = chooser(); + setup.purchase.mockImplementation(() => pending.promise); + await mount(setup.ui); + await click(buttonNamed("Buy", card("mentra.fleet"))); + await click(buttonNamed("Continue to payment", topDialog())); + await click(find('[aria-label="Close"]', topDialog())); + expect(openDialogs()).toHaveLength(0); + await act(async () => pending.resolve({ url: PAY })); + await settle(); + expect(setup.leave).not.toHaveBeenCalled(); + }); + + test("without a member count the sentence is left out", async () => { + await openBuyFleet({ memberCount: undefined }); + expect(topDialog().textContent).not.toContain("members."); + expect(topDialog().textContent).not.toContain("undefined"); + }); + + test("two members is 'Your workspace has 2 members.', and a stepper at 2", async () => { + await openBuyFleet({ memberCount: 2 }); + expect(topDialog().textContent).toContain("Your workspace has 2 members."); + expect(stepper(topDialog()).value).toBe("2"); + }); +}); + +describe("the licenses step starts at the workspace's member count", () => { + const range = (overrides: Record = {}) => fleet({ offer: workspaceOffer(1500, { buy: { minSeats: 1, maxSeats: 1000, ...overrides } as Offer["buy"] }) }); + async function openWith(memberCount: number, product = range()) { + const setup = chooser({ memberCount, products: [product] }); + await mount(setup.ui); + await click(buttonNamed("Buy", card("mentra.fleet"))); + return setup; + } + + test("14 members start at 14", async () => { + await openWith(14); + expect(stepper(topDialog()).value).toBe("14"); + expect(byText("14 subscriptions × $15 · $210 a month · before tax", "p", topDialog())).toBeTruthy(); + expect(topDialog().textContent).toContain("Your workspace has 14 members."); + }); + + test("2000 members start at the most billing allows", async () => { + await openWith(2000); + expect(stepper(topDialog()).value).toBe("1000"); + }); + + test("a floor above the count lifts the start to it", async () => { + await openWith(2, range({ minSeats: 5 })); + expect(stepper(topDialog()).value).toBe("5"); + }); + + test("one member has no stepper: '1 license · $15 a month · before tax' with no small print, and Continue buys 1", async () => { + const setup = await openWith(1); + const dialog = topDialog(); + expect(findAll('[role="spinbutton"]', dialog)).toHaveLength(0); + expect(findAll('[aria-label="One subscription more"]', dialog)).toHaveLength(0); + expect(byText("1 subscription · $15 a month · before tax", "p", dialog)).toBeTruthy(); + expect(dialog.textContent).not.toContain("It's yours once payment goes through."); + expect(dialog.textContent).not.toContain("secure payment page"); + expect(dialog.textContent).not.toContain("Your workspace has"); + expect(setup.purchase).not.toHaveBeenCalled(); + await click(buttonNamed("Continue to payment", dialog)); + await settle(); + expect(setup.purchase.mock.calls).toEqual([[WS, { product: "mentra.fleet", seats: 1 }]]); + }); + + test("the member count falling to one while the dialog is open buys the one license shown", async () => { + const client = new QueryClient(); + const { billing, purchase } = stubBilling(); + const out = ways(); + const dialog = (memberCount: number) => ( + + {}} /> + + ); + const view = await render(dialog(2)); + expect(stepper(topDialog()).value).toBe("2"); + await view.rerender(dialog(1)); + expect(findAll('[role="spinbutton"]', topDialog())).toHaveLength(0); + expect(byText("1 subscription · $15 a month · before tax", "p", topDialog())).toBeTruthy(); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + expect(purchase.mock.calls).toEqual([[WS, { product: "mentra.fleet", seats: 1 }]]); + }); + + test("one member and a floor of two still has the stepper", async () => { + await openWith(1, range({ minSeats: 2 })); + expect(stepper(topDialog()).value).toBe("2"); + }); +}); + +describe("the grid's Buy", () => { + test("goes straight to checkout for billing's smallest purchase, with no step in between", async () => { + const setup = grid(); + await mount(setup.ui); + await click(buttonNamed("Buy", card("mentra.fleet"))); + await settle(); + expect(openDialogs()).toHaveLength(0); + expect(setup.purchase.mock.calls.map((call) => call[1])).toEqual([{ product: "mentra.fleet", seats: 1 }]); + expect(setup.leave).toHaveBeenCalledWith(PAY); + }); + + test("buys billing's floor when it is more than one", async () => { + const setup = grid({ products: [fleet({ offer: workspaceOffer(1500, { buy: { minSeats: 3, maxSeats: 8 } }) })] }); + await mount(setup.ui); + await click(buttonNamed("Buy", card("mentra.fleet"))); + await settle(); + expect(setup.purchase.mock.calls.map((call) => call[1])).toEqual([{ product: "mentra.fleet", seats: 3 }]); + }); + + test("leaves the portal, so a screen reader hears so, and it shows no ↗", async () => { + await mount(grid().ui); + const buy = buttonNamed("Buy", card("mentra.fleet")); + expect(buy.textContent).toBe("Buy"); + expect(buy.hasAttribute("data-hosted-page")).toBe(true); + expect(findAll("svg", buy)).toHaveLength(0); + expect(card("mentra.fleet").textContent).toContain("Opens a secure billing page"); + }); + + test("a refusal is worded on the grid, and nothing is left", async () => { + const { billing } = realBilling(() => ({ status: 409, body: { error: "checkout_in_progress" } })); + const setup = grid({ billing }); + await mount(setup.ui); + await click(buttonNamed("Buy", card("mentra.fleet"))); + await settle(); + expect(find('[role="alert"]').textContent).toContain("A purchase of Fleet is already under way."); + expect(setup.leave).not.toHaveBeenCalled(); + }); +}); + +describe("a price of a scheme the portal doesn't know", () => { + const unknown = () => fleet({ offer: workspaceOffer(1500, { price: tiered }) }); + + test("the card shows billing's label exactly, with no arithmetic", async () => { + await mount(grid({ products: [unknown(), callFor()] }).ui); + const priced = card("mentra.fleet"); + expect(byText("From $10 per user per month, less in bulk", "p", priced)).toBeTruthy(); + // None of the offer's numbers is read: the label is all there is. + expect(priced.textContent).not.toContain("$15"); + // The known price beside it is still Core's. + expect(byText("$29 per user per month", "p", card("mentra.call.unlimited"))).toBeTruthy(); + }); + + test("a per_seat price that arrives without its numbers is read as its label too", async () => { + const malformed = fleet({ offer: workspaceOffer(1500, { price: { scheme: "per_seat", fallbackLabel: "About $15 per user" } }) }); + await mount(grid({ products: [malformed] }).ui); + expect(byText("About $15 per user", "p", card("mentra.fleet"))).toBeTruthy(); + }); + + test("the licenses step shows the label, and no sum, no renewal claim and no tax note", async () => { + await mount(chooser({ products: [unknown()], memberCount: 14 }).ui); + await click(buttonNamed("Buy")); + const dialog = topDialog(); + expect(dialog.textContent).toContain("From $10 per user per month, less in bulk"); + expect(dialog.textContent).not.toContain("×"); + expect(dialog.textContent).not.toContain("Renews every"); + expect(dialog.textContent).not.toContain("before tax"); + expect(dialog.textContent).not.toContain("a month ·"); + // Seats are still asked for, since billing asked for a seat count. + expect(stepper(dialog).value).toBe("14"); + expect(dialog.textContent).toContain("Your workspace has 14 members."); + }); + + test("it can still be bought: Continue sends the number of licenses chosen", async () => { + const { ui, purchase, leave } = chooser({ products: [unknown()], memberCount: 10 }); + await mount(ui); + await click(buttonNamed("Buy")); + await click(find('[aria-label="One subscription fewer"]', topDialog())); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + expect(purchase.mock.calls).toEqual([[WS, { product: "mentra.fleet", seats: 9 }]]); + expect(leave).toHaveBeenCalledWith(PAY); + }); + +}); + +// ---- addresses the portal won't follow ---------------------------------------------------------------------------- + +describe("unsafe purchase addresses", () => { + const refused = t.refusal.generic; + + for (const unsafe of [ + "javascript:alert(document.cookie)", + "http://pay.example.test/c/cs_1", + "data:text/html,", + "https://user:secret@pay.example.test/c/cs_1", + "//pay.example.test/c/cs_1", + ]) { + test(`a workspace's purchase answered with ${unsafe.slice(0, 28)} goes nowhere and says so`, async () => { + const { billing } = payingAt(unsafe); + const { ui, leave } = chooser({ billing, memberCount: 14 }); + await mount(ui); + await click(buttonNamed("Buy", card("mentra.fleet"))); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + expect(leave).not.toHaveBeenCalled(); + expect(find('[role="alert"]', topDialog()).textContent).toBe(refused); + expect(isNeutral(find('[role="alert"]', topDialog()))).toBe(true); + // The dialog stays, ready to try again. + expect(buttonNamed("Continue to payment", topDialog()).disabled).toBe(false); + }); + } + + test("an Add licenses session answered with an address the portal won't follow goes nowhere either", async () => { + const { billing } = payingAt("javascript:alert(1)"); + const { ui, leave } = grid({ billing, licenses: [licenseBillingFor()] }); + await mount(ui); + await click(buttonNamed("Buy more seats")); + await settle(); + expect(leave).not.toHaveBeenCalled(); + expect(find('[role="alert"]').textContent).toBe(refused); + }); + + test("https, and http to localhost or 127.0.0.1, are followed (as the canonical address)", async () => { + for (const [sent, followed] of [ + ["https://pay.example.test/c/cs_1", "https://pay.example.test/c/cs_1"], + ["http://localhost:4242/pay", "http://localhost:4242/pay"], + ["http://127.0.0.1:4242/pay", "http://127.0.0.1:4242/pay"], + [" https://pay.example.test/a b", "https://pay.example.test/a%20b"], + ] as const) { + const { billing } = payingAt(sent); + const { ui, leave } = chooser({ billing, memberCount: 14 }); + await mount(ui); + await click(buttonNamed("Buy", card("mentra.fleet"))); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + expect(leave).toHaveBeenCalledWith(followed); + await cleanup(); + } + }); + + test("billing being unreachable is the same generic line", async () => { + const billing = createBillingApi({ locale: "en-US", fetch: (async () => Promise.reject(new TypeError("offline"))) as never }); + const { ui, leave } = chooser({ billing, memberCount: 14 }); + await mount(ui); + await click(buttonNamed("Buy", card("mentra.fleet"))); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + expect(leave).not.toHaveBeenCalled(); + expect(find('[role="alert"]', topDialog()).textContent).toBe(refused); + }); +}); + +// ---- refusals ----------------------------------------------------------------------------------------------------- + +describe("refusals", () => { + const refusing = (status: number, error: string, details: Record = {}) => realBilling(() => ({ status, body: { error, ...details } })); + + async function buyFleet(billing: BillingApi, client = new QueryClient()) { + const setup = chooser({ billing, memberCount: 14 }); + await mount(setup.ui, client); + await click(buttonNamed("Buy", card("mentra.fleet"))); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + return setup; + } + + test("already_licensed says 'You already have . Add licenses instead.', refetches billing, and stops the purchase", async () => { + const client = new QueryClient(); + const invalidate = spyOn(client, "invalidateQueries"); + const { leave } = await buyFleet(refusing(409, "already_licensed", { licenseId: "lic_fleet" }).billing, client); + expect(find('[role="alert"]', topDialog()).textContent).toBe("You already have Fleet. Buy more seats instead."); + expect(invalidate).toHaveBeenCalledWith({ queryKey: billingKeys.owner(WS) }); + expect(leave).not.toHaveBeenCalled(); + // It is held now: another try would only be refused again. + expect(buttonNamed("Continue to payment", topDialog()).disabled).toBe(true); + expect(buttonNamed("Cancel", topDialog()).disabled).toBe(false); + }); + + test("checkout_in_progress says a purchase is under way, and leaves the button for another try", async () => { + const client = new QueryClient(); + const invalidate = spyOn(client, "invalidateQueries"); + await buyFleet(refusing(409, "checkout_in_progress").billing, client); + expect(find('[role="alert"]', topDialog()).textContent).toBe( + "A purchase of Fleet is already under way. Finish it, or try again in a minute.", + ); + expect(invalidate).not.toHaveBeenCalled(); + expect(buttonNamed("Continue to payment", topDialog()).disabled).toBe(false); + }); + + test("not_for_sale, invalid_seats and a code Core doesn't know are worded, and the generic line covers the rest", async () => { + await buyFleet(refusing(400, "not_for_sale").billing); + expect(find('[role="alert"]', topDialog()).textContent).toBe("Fleet isn't for sale right now."); + await cleanup(); + await buyFleet(refusing(400, "invalid_seats").billing); + expect(find('[role="alert"]', topDialog()).textContent).toBe("That number of subscriptions isn't available. Choose a different number."); + await cleanup(); + await buyFleet(refusing(418, "teapot").billing); + expect(find('[role="alert"]', topDialog()).textContent).toBe(t.refusal.generic); + await cleanup(); + await buyFleet(realBilling(() => ({ status: 502, body: "bad gateway" })).billing); + expect(find('[role="alert"]', topDialog()).textContent).toBe(t.refusal.generic); + }); + + test("a new attempt clears the last refusal", async () => { + let attempt = 0; + const { billing } = realBilling(() => (attempt++ === 0 ? { status: 409, body: { error: "checkout_in_progress" } } : { body: { url: PAY } })); + const { leave } = await buyFleet(billing); + expect(findAll('[role="alert"]', topDialog())).toHaveLength(1); + await click(buttonNamed("Continue to payment", topDialog())); + await settle(); + expect(leave).toHaveBeenCalledWith(PAY); + expect(findAll('[role="alert"]')).toHaveLength(0); + }); +}); + +// ---- Buy a license, as a dialog ----------------------------------------------------------------------------------- + +describe("the catalog dialog", () => { + const dialogFor = (options: GridOptions & { open?: boolean } = {}) => { + const out = ways(); + const onClose = mock(() => {}); + const stub = stubBilling(); + const ui = ( + + ); + return { ui, ...out, onClose, ...stub }; + }; + const row = (product: string) => find(`[data-product="${product}"]`, topDialog()); + const held = [licenseBillingFor({ quantity: 5 }), licenseBillingFor({ licenseId: "lic_fleet", product: "mentra.fleet", quantity: 10 })]; + + test("is 'Buy licenses', with what to do for a product you have", async () => { + await mount(dialogFor({ licenses: held }).ui); + expect(find("h2", topDialog()).textContent).toBe("Buy subscriptions"); + expect(topDialog().textContent).toContain("Products for your workspace. For one you have, buy more subscriptions instead."); + }); + + test("a held product shows 'You have licenses' and Add licenses; any other shows its price and Buy", async () => { + await mount(dialogFor({ licenses: held }).ui); + expect(row("mentra.call.unlimited").textContent).toContain("You have 5 subscriptions"); + expect(buttons(row("mentra.call.unlimited")).map((button) => button.textContent)).toEqual(["Buy more seats"]); + expect(row("mentra.fleet").textContent).toContain("You have 10 subscriptions"); + expect(buttons(row("mentra.fleet")).map((button) => button.textContent)).toEqual(["Buy more seats"]); + expect(row("mentra.example").textContent).toContain("Example Add-on"); + expect(row("mentra.example").textContent).toContain("$9 per user per month"); + expect(buttons(row("mentra.example")).map((button) => button.textContent)).toEqual(["Buy"]); + }); + + test("a row shows the product's icon beside its name, and no feature list or description", async () => { + await mount(dialogFor({ licenses: held }).ui); + expect(find("img", row("mentra.call.unlimited")).getAttribute("src")).toBe("/api/portal/billing/ui/icons/mentra-call.png"); + expect(findAll("ul", row("mentra.fleet"))).toHaveLength(0); + expect(row("mentra.fleet").textContent).not.toContain("Manage your members"); + }); + + test("Buy on a row goes straight to checkout, as the grid's does", async () => { + const setup = dialogFor({ licenses: held }); + await mount(setup.ui); + await click(buttonNamed("Buy", row("mentra.example"))); + await settle(); + expect(openDialogs()).toHaveLength(1); + expect(setup.purchase.mock.calls.map((call) => call[1])).toEqual([{ product: "mentra.example", seats: 1 }]); + expect(setup.leave).toHaveBeenCalledWith(PAY); + }); + + test("Add licenses on a row asks for add_seats and goes to the page", async () => { + const { ui, session, leave } = dialogFor({ licenses: held }); + await mount(ui); + await click(buttonNamed("Buy more seats", row("mentra.fleet"))); + await settle(); + expect(session.mock.calls).toEqual([[WS, { action: "add_seats", licenseId: "lic_fleet" }]]); + expect(leave).toHaveBeenCalledWith(PAY); + }); + + test("a refusal on a row is shown in the list", async () => { + const { billing } = realBilling(() => ({ status: 400, body: { error: "unknown_action" } })); + await mount(dialogFor({ billing, licenses: held }).ui); + await click(buttonNamed("Buy more seats", row("mentra.fleet"))); + await settle(); + expect(find('[role="alert"]', topDialog()).textContent).toBe("That isn't available for this subscription any more. Reload the page and try again."); + }); + + /** The three ways a person closes it, each as the platform delivers it. */ + const WAYS_TO_CLOSE: Array<[string, () => Promise]> = [ + ["×", () => click(find('[aria-label="Close"]', topDialog()))], + ["Escape", escape], + ["a click on the backdrop", () => click(topDialog())], + ]; + + for (const [way, close] of WAYS_TO_CLOSE) { + test(`closing it with ${way} asks the host to`, async () => { + const setup = dialogFor({ licenses: held }); + await mount(setup.ui); + expect(setup.onClose).not.toHaveBeenCalled(); + await close(); + expect(setup.onClose).toHaveBeenCalledTimes(1); + }); + } + + test("reopening it starts without the old refusal", async () => { + const { billing } = realBilling(() => ({ status: 400, body: { error: "unknown_action" } })); + const setup = dialogFor({ billing, licenses: held }); + const { rerender } = await mount(setup.ui); + await click(buttonNamed("Buy more seats", row("mentra.fleet"))); + await settle(); + expect(findAll('[role="alert"]')).toHaveLength(1); + await click(find('[aria-label="Close"]', topDialog())); + expect(setup.onClose).toHaveBeenCalled(); + await rerender( + + {dialogFor({ billing, licenses: held, open: false }).ui} + , + ); + expect(openDialogs()).toHaveLength(0); + await rerender({dialogFor({ billing, licenses: held }).ui}); + expect(findAll('[role="alert"]')).toHaveLength(0); + }); + + test("closed, it draws nothing", async () => { + await mount(dialogFor({ open: false }).ui); + expect(openDialogs()).toHaveLength(0); + expect(findAll("button", find("dialog"))).toHaveLength(0); + }); + + test("an entry without an offer is a row with no price and no Buy", async () => { + const products = [callFor({ offer: undefined }), addOn()]; + await mount(dialogFor({ products }).ui); + expect(findAll("[data-product]", topDialog()).map((element) => element.getAttribute("data-product"))).toEqual([ + "mentra.call.unlimited", + "mentra.example", + ]); + expect(row("mentra.call.unlimited").textContent).toBe("Mentra Call Unlimited"); + expect(buttons(row("mentra.call.unlimited"))).toHaveLength(0); + }); + + test("a product billing won't sell now has no Buy and no Add licenses", async () => { + const products = [callFor({ offer: workspaceOffer(2900, { buy: null }) })]; + await mount(dialogFor({ products }).ui); + expect(buttons(row("mentra.call.unlimited"))).toHaveLength(0); + expect(row("mentra.call.unlimited").textContent).toContain("$29 per user per month"); + }); + + test("a screen reader hears whose button it is, there is no native select, and nothing names the processor", async () => { + await mount(dialogFor({ licenses: held }).ui); + const buy = buttonNamed("Buy", row("mentra.example")); + const describedBy = buy.getAttribute("aria-describedby")!.split(" ").map((id) => document.getElementById(id)?.textContent); + expect(describedBy).toContain("Example Add-on"); + const add = buttonNamed("Buy more seats", row("mentra.fleet")); + expect(add.getAttribute("aria-describedby")!.split(" ").map((id) => document.getElementById(id)?.textContent)).toContain("Fleet"); + expect(findAll("select")).toHaveLength(0); + expect(text()).not.toMatch(NAMES_THE_PROCESSOR); + }); +}); + +// ---- the heading is buying copy ----------------------------------------------------------------------------------- + +describe("the grid's heading", () => { + test("are drawn only when at least one entry has an offer for this viewer", async () => { + await mount(grid({ products: [callFor({ offer: undefined }), fleet({ offer: undefined })] }).ui); + expect(findAll("h2")).toHaveLength(0); + expect(text()).not.toContain("Buy more seats"); + expect(text()).not.toContain("secure payment page"); + // The products themselves are display content: named, described, and nothing to buy. + expect(findAll("[data-product]")).toHaveLength(2); + expect(buttons()).toHaveLength(0); + await cleanup(); + await mount(grid({ products: [callFor({ offer: undefined }), fleet()] }).ui); + expect(find("h2").textContent).toBe("Buy subscriptions for your members"); + expect(text()).not.toContain("secure payment page"); + }); + + test("follow the offer, not whether Buy is possible: an offer billing won't sell now still has them", async () => { + await mount(grid({ products: [callFor({ offer: workspaceOffer(2900, { buy: null }) })] }).ui); + expect(find("h2").textContent).toBe("Buy subscriptions for your members"); + }); + +}); + +// ---- a first payment that isn't finished -------------------------------------------------------------------------- + +describe("a product whose first payment isn't finished", () => { + const COMPLETE = "https://invoice.example.test/i/first"; + const incomplete = (extra: Partial = {}) => + licenseBillingFor({ + status: "incomplete", + fallbackStatusLabel: "Incomplete", + quantity: 5, + renewsAt: undefined, + actions: [{ kind: "complete_payment", fallbackLabel: "Complete payment", returns: false }], + ...extra, + }); + + test("reads as its state, 'Payment incomplete', and never as 'You have 5 licenses'", async () => { + await mount(grid({ licenses: [incomplete()] }).ui); + const mine = card("mentra.call.unlimited"); + expect(mine.textContent).toContain("Payment incomplete"); + expect(mine.textContent).not.toContain("You have"); + expect(mine.textContent).not.toContain("5 subscriptions"); + // Amber, as a payment that needs the buyer. + expect(byText("Payment incomplete", "p", mine).className).toContain("text-error-foreground"); + // Nothing is bought or added to it; the other products are as they were. + expect(buttons(mine).map((button) => button.textContent)).toEqual(["Complete payment"]); + expect(buttons(card("mentra.fleet")).map((button) => button.textContent)).toEqual(["Buy"]); + }); + + test("its button is billing's complete_payment: a tab opened in the click, then sent to the payment page", async () => { + const pending = deferred<{ url: string }>(); + const { ui, session, events, leave } = grid({ licenses: [incomplete({ licenseId: "lic_half" })] }); + session.mockImplementation(() => pending.promise); + await mount(ui); + const button = buttonNamed("Complete payment"); + expect(button.hasAttribute("data-hosted-page")).toBe(true); + let openedInTheClick = -1; + act(() => { + button.click(); + openedInTheClick = events.filter((event) => event === "openTab").length; + }); + expect(openedInTheClick).toBe(1); + await settle(); + expect(session.mock.calls).toEqual([[WS, { action: "complete_payment", licenseId: "lic_half" }]]); + await act(async () => pending.resolve({ url: COMPLETE })); + await settle(); + expect(events).toEqual(["openTab", `go:${COMPLETE}`]); + expect(leave).not.toHaveBeenCalled(); + }); + + test("a complete_payment that returns navigates this tab, as every action that returns does", async () => { + const { ui, leave, openTab } = grid({ licenses: [incomplete({ actions: [{ kind: "complete_payment", fallbackLabel: "Complete payment" }] })] }); + await mount(ui); + await click(buttonNamed("Complete payment")); + await settle(); + expect(leave).toHaveBeenCalledWith(PAY); + expect(openTab).not.toHaveBeenCalled(); + }); + + test("with no complete_payment listed it is the state alone, and no button", async () => { + await mount(grid({ licenses: [incomplete({ actions: [] })] }).ui); + const mine = card("mentra.call.unlimited"); + expect(mine.textContent).toContain("Payment incomplete"); + expect(mine.textContent).not.toContain("You have"); + expect(buttons(mine)).toHaveLength(0); + }); + + test("never offers Add licenses, even if billing listed it", async () => { + const both = incomplete({ + actions: [ + { kind: "add_seats", fallbackLabel: "Buy more seats" }, + { kind: "complete_payment", fallbackLabel: "Complete payment" }, + ], + }); + await mount(grid({ licenses: [both] }).ui); + expect(buttons(card("mentra.call.unlimited")).map((button) => button.textContent)).toEqual(["Complete payment"]); + }); + + test("so does its row in the Buy licenses dialog", async () => { + const out = ways(); + const stub = stubBilling(); + await mount( + {}} products={WORKSPACE_CATALOG} licenses={[incomplete({ licenseId: "lic_half" })]} scope={WS} billing={stub.billing} navigateOut={out.navigateOut} />, + ); + const row = find('[data-product="mentra.call.unlimited"]', topDialog()); + expect(row.textContent).toContain("Payment incomplete"); + expect(row.textContent).not.toContain("You have"); + expect(buttons(row).map((button) => button.textContent)).toEqual(["Complete payment"]); + await click(buttonNamed("Complete payment", row)); + await settle(); + expect(stub.session.mock.calls).toEqual([[WS, { action: "complete_payment", licenseId: "lic_half" }]]); + expect(out.events).toEqual(["openTab", `go:${PAY}`]); + }); + + test("a failed payment on an active product is another matter: it still has its licenses, and Add licenses", async () => { + const failed = licenseBillingFor({ status: "past_due", fallbackStatusLabel: "Past due", quantity: 5 }); + await mount(grid({ licenses: [failed] }).ui); + expect(card("mentra.call.unlimited").textContent).toContain("You have 5 subscriptions"); + expect(buttons(card("mentra.call.unlimited")).map((button) => button.textContent)).toEqual(["Buy more seats"]); + }); +}); + +// ---- the pieces --------------------------------------------------------------------------------------------------- + +describe("canBuy", () => { + test("is true only for an entry with an offer whose buy isn't null", () => { + expect(canBuy(callFor())).toBe(true); + expect(canBuy(callFor({ offer: undefined }))).toBe(false); + expect(canBuy(callFor({ offer: workspaceOffer(2900, { buy: null }) }))).toBe(false); + }); +}); + +describe("CatalogCard", () => { + test("is the card the grid is made of: a held product with its own handlers", async () => { + const onBuy = mock(() => {}); + await mount( + {}} />, + ); + await click(buttonNamed("Buy")); + expect(onBuy).toHaveBeenCalledTimes(1); + }); + + test("prices in the locale it is given", async () => { + const entry = callFor({ offer: workspaceOffer(2900, { price: { scheme: "per_seat", unit: { amountMinor: 1450, currency: "USD" }, recurrence: { interval: "month", count: 3 } } }) }); + await mount( + {}} onAddSeats={() => {}} />, + ); + expect(byText("$14.50 per user every 3 months", "p")).toBeTruthy(); + }); +}); + +describe("what the buying components import", () => { + test("the contract's schemas are reached through billing-format's isPerSeat only, never the client", () => { + const { files } = runtimeImports("components/licenses/catalog.tsx"); + // The client (and with it the schemas for every answer) is the host's to bring; the dialogs take it as a prop. + expect(files.some((file) => file.endsWith("billing-api.ts"))).toBe(false); + }); +}); diff --git a/cloud-v2/packages/workspace-ui/src/confirm-dialogs.test.tsx b/cloud-v2/packages/workspace-ui/src/confirm-dialogs.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..4096b97447751d4c6f06372cce0b1ccd795c4672 --- /dev/null +++ b/cloud-v2/packages/workspace-ui/src/confirm-dialogs.test.tsx @@ -0,0 +1,299 @@ +/** + * Leave workspace, Delete workspace, Revoke invitation and Revoke key ask in a dialog, not in place of the button: the + * dialog opens with the question, Cancel sends nothing and gives focus back, and the destructive button sends the request. + * Driven through the real panels against a recording fake of Core. + */ + +import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from "bun:test"; +import { act } from "react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import type { CredentialView, InvitationView, WorkspaceRole } from "@mentra/workspace-contract"; +import type { ReactElement } from "react"; +import { createWorkspaceApi, type FetchLike, type WorkspaceApi } from "./api"; +import { ConfirmDialog } from "./components/confirm-dialog"; +import { WorkspaceCredentialsPanel } from "./components/credentials-panel"; +import { WorkspacePendingInvitationsPanel } from "./components/invitations-panel"; +import { WorkspaceSettingsPanel } from "./components/settings-panel"; +import { byText, cleanup, click, find, findAll, render, setupDom, teardownDom, typeInto, until } from "./test-dom"; +import { CREDENTIALS, detailFor, INVITATIONS, membersFor, seedClient, WORKSPACE_ID, WORKSPACE_NAME } from "./test-fixtures"; + +beforeAll(setupDom); +afterAll(teardownDom); +afterEach(cleanup); + +const BASE = "/api/workspaces"; +const WS = `/${WORKSPACE_ID}`; + +interface Call { + method: string; + path: string; + body: unknown; +} + +/** Core's side of the lists the dialogs act on, and a way to make it refuse. */ +interface World { + invitations: InvitationView[]; + credentials: CredentialView[]; + refuse?: (call: Call) => Response | undefined; +} + +const reply = (status: number, body?: unknown) => + ({ ok: status >= 200 && status < 300, status, statusText: "", json: async () => structuredClone(body) }) as unknown as Response; + +const TWO_KEYS: CredentialView[] = [CREDENTIALS[0]!, { ...CREDENTIALS[0]!, credentialId: "cred_docs", name: "Docs bot" }]; + +function serve(detail: unknown, members: unknown, world: World, calls: Call[]): FetchLike { + return async (input, init) => { + const path = String(input).slice(BASE.length); + const method = init?.method ?? "GET"; + const call: Call = { method, path, body: typeof init?.body === "string" ? JSON.parse(init.body) : undefined }; + calls.push(call); + const refused = world.refuse?.(call); + if (refused) return refused; + if (method === "GET" && path === WS) return reply(200, detail); + if (method === "GET" && path === `${WS}/members`) return reply(200, { items: members }); + if (method === "GET" && path === `${WS}/invitations`) return reply(200, { items: world.invitations }); + if (method === "GET" && path === `${WS}/credentials`) return reply(200, { items: world.credentials }); + const invitation = new RegExp(`^${WS}/invitations/([^/]+)$`).exec(path); + if (method === "DELETE" && invitation) { + world.invitations = world.invitations.filter((other) => other.invitationId !== invitation[1]); + return reply(204); + } + const credential = new RegExp(`^${WS}/credentials/([^/]+)$`).exec(path); + if (method === "DELETE" && credential) { + world.credentials = world.credentials.filter((other) => other.credentialId !== credential[1]); + return reply(204); + } + if ((method === "POST" && path === `${WS}/leave`) || (method === "DELETE" && path === WS)) return reply(204); + return reply(404, { error: "not_found" }); + }; +} + +async function mount(role: WorkspaceRole, panel: (api: WorkspaceApi) => ReactElement) { + const detail = detailFor(role); + const members = membersFor(detail); + const world: World = { invitations: structuredClone(INVITATIONS), credentials: structuredClone(TWO_KEYS) }; + const calls: Call[] = []; + const api = createWorkspaceApi({ basePath: BASE, fetch: serve(detail, members, world, calls) }); + const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, gcTime: Infinity, retry: false } } }); + seedClient(api, structuredClone({ detail, members, invitations: world.invitations, credentials: world.credentials }), client); + await render({panel(api)}); + return { world, writes: () => calls.filter((call) => call.method !== "GET") }; +} + +const openDialogs = () => findAll("dialog").filter((dialog) => dialog.open); +const theDialog = () => { + const [dialog, ...others] = openDialogs(); + if (!dialog || others.length > 0) throw new Error(`expected one open dialog, found ${openDialogs().length}`); + return dialog; +}; +const buttonsIn = (dialog: HTMLElement) => + findAll("button", dialog).map((button) => button.getAttribute("aria-label") ?? button.textContent!.trim()); +const trigger = (label: string) => find(`button[aria-label="${label}"]`); +const inDialog = (text: string) => byText(text, "button", theDialog()); + +describe("Leave workspace", () => { + const settings = () => { + const left = mock(() => {}); + const mounted = mount("owner", (api) => ); + return { left, mounted }; + }; + + test("asks in a dialog, Cancel sends nothing and gives focus back, Leave sends the request", async () => { + const { left, mounted } = settings(); + const { writes } = await mounted; + const button = trigger("Leave workspace"); + // The old inline prompt is gone: nothing replaces the button. + expect(findAll('[role="group"]')).toHaveLength(0); + await click(button); + const dialog = theDialog(); + expect(find("h2", dialog).textContent).toBe(`Leave ${WORKSPACE_NAME}?`); + expect(dialog.textContent).toContain("You lose access to this workspace."); + expect(buttonsIn(dialog)).toEqual(["Close", "Cancel", "Leave"]); + expect(inDialog("Leave").className).toContain("bg-destructive"); + expect(writes()).toHaveLength(0); + + await click(inDialog("Cancel")); + expect(openDialogs()).toHaveLength(0); + expect(writes()).toHaveLength(0); + expect(document.activeElement).toBe(button); + + await click(button); + await click(inDialog("Leave")); + await until(() => left.mock.calls.length === 1, "Leave to go through"); + expect(writes()).toEqual([{ method: "POST", path: `${WS}/leave`, body: undefined }]); + }); + + test("a refusal is shown in the dialog, which stays open, with focus back on the Leave button", async () => { + const { mounted } = settings(); + const { world, writes } = await mounted; + world.refuse = (call) => (call.method === "POST" ? reply(403, { error: "forbidden" }) : undefined); + await click(trigger("Leave workspace")); + await click(inDialog("Leave")); + await until(() => findAll('[role="alert"]', theDialog()).length === 1, "the refusal"); + expect(find('[role="alert"]', theDialog()).textContent).toBe("You do not have permission to do that."); + expect(inDialog("Leave").hasAttribute("disabled")).toBe(false); + // The button was disabled while the request was out, which dropped focus; it is back on the button for another try. + expect(document.activeElement).toBe(inDialog("Leave")); + expect(writes()).toHaveLength(1); + }); +}); + +describe("Delete workspace", () => { + test("asks in a dialog that wants the workspace's name typed back, Cancel sends nothing, Delete sends the request", async () => { + const deleted = mock(() => {}); + const { writes } = await mount("owner", (api) => ); + const button = byText("Delete workspace", "button"); + await click(button); + const dialog = theDialog(); + expect(find("h2", dialog).textContent).toBe(`Delete ${WORKSPACE_NAME}?`); + expect(dialog.textContent).toContain("Deleting a workspace ends every membership and invitation and revokes every key. It cannot be undone."); + expect(buttonsIn(dialog)).toEqual(["Close", "Cancel", "Delete"]); + expect(inDialog("Delete").className).toContain("bg-destructive"); + + // The name is typed here, in the dialog, and Delete waits for all of it. + const field = find("input", dialog); + expect(find("label", dialog).textContent).toBe(`Type ${WORKSPACE_NAME} to confirm`); + expect(find("label", dialog).getAttribute("for")).toBe(field.id); + expect(document.activeElement).toBe(field); + expect(inDialog("Delete").hasAttribute("disabled")).toBe(true); + await typeInto(field, "Acme"); + expect(inDialog("Delete").hasAttribute("disabled")).toBe(true); + + await click(inDialog("Cancel")); + expect(openDialogs()).toHaveLength(0); + expect(writes()).toHaveLength(0); + expect(document.activeElement).toBe(button); + + // Asked again, the field starts empty. + await click(button); + expect(find("input", theDialog()).value).toBe(""); + await typeInto(find("input", theDialog()), WORKSPACE_NAME); + expect(inDialog("Delete").hasAttribute("disabled")).toBe(false); + await click(inDialog("Delete")); + await until(() => deleted.mock.calls.length === 1, "Delete to go through"); + expect(writes()).toEqual([{ method: "DELETE", path: WS, body: { confirmName: WORKSPACE_NAME } }]); + }); + + test("a refusal because a service holds the workspace is shown in the dialog, in words", async () => { + const { world } = await mount("owner", (api) => ); + const holds = [{ service: "store", reason: "owns_miniapps", count: 1 }]; + world.refuse = (call) => + call.method === "DELETE" ? reply(409, { error: "workspace_has_holds", error_description: "workspace_has_holds", holds }) : undefined; + await click(byText("Delete workspace", "button")); + await typeInto(find("input", theDialog()), WORKSPACE_NAME); + await click(inDialog("Delete")); + await until(() => findAll('[role="alert"]', theDialog()).length === 1, "the refusal"); + expect(find('[role="alert"]', theDialog()).textContent).toBe("This workspace still owns 1 miniapp. Delete it in the Developer Console first."); + expect(document.activeElement).toBe(inDialog("Delete")); + }); +}); + +describe("Revoke invitation", () => { + const pending = () => mount("owner", (api) => ); + // Each invitation's "…" menu holds Resend and Revoke; Revoke asks. + const NEWBIE = "More for newbie@acme.test"; + const BOSS = "More for boss@acme.test"; + const revokeFrom = async (menu: string) => { + await click(trigger(menu)); + await click(byText("Revoke", '[role="menuitem"]')); + }; + + test("a row's menu holds Resend and Revoke, and nothing is sent by opening it", async () => { + const { writes } = await pending(); + expect(findAll('[role="menuitem"]')).toHaveLength(0); + await click(trigger(NEWBIE)); + expect(findAll('[role="menuitem"]').map(item => item.textContent!.trim())).toEqual(["Resend", "Revoke"]); + expect(writes()).toHaveLength(0); + }); + + test("asks in a dialog, Cancel sends nothing and gives focus back, Revoke sends the request and focus moves on", async () => { + const { writes } = await pending(); + expect(findAll('[role="group"]')).toHaveLength(0); + await revokeFrom(NEWBIE); + const dialog = theDialog(); + expect(find("h2", dialog).textContent).toBe("Revoke the invitation for newbie@acme.test?"); + expect(dialog.textContent).toContain("The link they were sent stops working."); + expect(buttonsIn(dialog)).toEqual(["Close", "Cancel", "Revoke"]); + expect(inDialog("Revoke").className).toContain("bg-destructive"); + expect(writes()).toHaveLength(0); + + await click(inDialog("Cancel")); + expect(openDialogs()).toHaveLength(0); + expect(writes()).toHaveLength(0); + expect(document.activeElement).toBe(trigger(NEWBIE)); + + await revokeFrom(NEWBIE); + await click(inDialog("Revoke")); + await until(() => openDialogs().length === 0 && findAll(`button[aria-label="${NEWBIE}"]`).length === 0, "the invitation to go"); + expect(writes()).toEqual([{ method: "DELETE", path: `${WS}/invitations/inv_member`, body: undefined }]); + // Its row is gone, so focus is on the next row's button. + expect(document.activeElement).toBe(trigger(BOSS)); + }); + + test("a refusal is shown in the dialog, which stays open", async () => { + const { world } = await pending(); + world.refuse = (call) => (call.method === "DELETE" ? reply(403, { error: "forbidden" }) : undefined); + await revokeFrom(NEWBIE); + await click(inDialog("Revoke")); + await until(() => findAll('[role="alert"]', theDialog()).length === 1, "the refusal"); + expect(find('[role="alert"]', theDialog()).textContent).toBe("You do not have permission to do that."); + expect(document.activeElement).toBe(inDialog("Revoke")); + }); +}); + +describe("Revoke key", () => { + const keys = () => mount("developer", (api) => ); + + test("asks in a dialog, Cancel sends nothing and gives focus back, Revoke sends the request and focus moves on", async () => { + const { writes } = await keys(); + expect(findAll('[role="group"]')).toHaveLength(0); + await click(trigger("Revoke CI publisher")); + const dialog = theDialog(); + expect(find("h2", dialog).textContent).toBe("Revoke CI publisher?"); + expect(dialog.textContent).toContain("Anything using it stops working."); + expect(buttonsIn(dialog)).toEqual(["Close", "Cancel", "Revoke"]); + expect(writes()).toHaveLength(0); + + await click(inDialog("Cancel")); + expect(openDialogs()).toHaveLength(0); + expect(writes()).toHaveLength(0); + expect(document.activeElement).toBe(trigger("Revoke CI publisher")); + + await click(trigger("Revoke CI publisher")); + await click(inDialog("Revoke")); + await until(() => openDialogs().length === 0 && findAll('button[aria-label="Revoke CI publisher"]').length === 0, "the key to go"); + expect(writes()).toEqual([{ method: "DELETE", path: `${WS}/credentials/cred_ci`, body: undefined }]); + expect(document.activeElement).toBe(trigger("Revoke Docs bot")); + }); + + test("a refusal is shown in the dialog, which stays open", async () => { + const { world } = await keys(); + world.refuse = (call) => (call.method === "DELETE" ? reply(403, { error: "forbidden" }) : undefined); + await click(trigger("Revoke Docs bot")); + await click(inDialog("Revoke")); + await until(() => findAll('[role="alert"]', theDialog()).length === 1, "the refusal"); + expect(find('[role="alert"]', theDialog()).textContent).toBe("You do not have permission to do that."); + expect(document.activeElement).toBe(inDialog("Revoke")); + }); +}); + +describe("how a dialog reports that it ended", () => { + test("once the request went through, a close the platform raises as the dialog leaves is not the person backing out", async () => { + const closed: boolean[] = []; + await render( + null} + onClose={(done) => closed.push(done)} + />, + ); + await click(inDialog("Revoke")); + expect(closed).toEqual([true]); + await act(async () => void theDialog().dispatchEvent(new Event("close"))); + expect(closed).toEqual([true]); + }); +}); diff --git a/cloud-v2/packages/workspace-ui/src/controls.test.tsx b/cloud-v2/packages/workspace-ui/src/controls.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..ae82db86a4560da47f79bfaaa4b48edd9b8fe3d6 --- /dev/null +++ b/cloud-v2/packages/workspace-ui/src/controls.test.tsx @@ -0,0 +1,716 @@ +import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from "bun:test"; +import { act, useState, type ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { Notice, Fact, HostedPageButton, Skeleton, StatusBadge } from "./components/licenses/parts"; +import { Checkbox } from "./ui/checkbox"; +import { Menu } from "./ui/menu"; +import { Meter } from "./ui/meter"; +import { SidePanel } from "./ui/side-panel"; +import { Stepper } from "./ui/stepper"; +import { Switch } from "./ui/switch"; +import { + activeElement, + byText, + cleanup, + click, + find, + findAll, + focus, + pointerDown, + press, + render, + setupDom, + teardownDom, + typeInto, +} from "./test-dom"; + +beforeAll(setupDom); +afterAll(teardownDom); +afterEach(cleanup); + +describe("Checkbox and Switch are native inputs", () => { + test("a Checkbox is an in the tab order, and Space toggles it", async () => { + const onChange = mock((event: { target: { checked: boolean } }) => event.target.checked); + await render(); + const input = find("input"); + expect(input.type).toBe("checkbox"); + expect(input.getAttribute("role")).toBeNull(); + expect(input.getAttribute("aria-label")).toBe("Choose Dana"); + expect(input.tabIndex).toBe(0); + await focus(input); + await press(input, " "); + expect(input.checked).toBe(true); + await press(input, " "); + expect(input.checked).toBe(false); + expect(onChange.mock.results.map((result) => result.value)).toEqual([true, false]); + }); + + test("a Switch is a checkbox with role=switch, and Space toggles it", async () => { + const seen: boolean[] = []; + await render( seen.push(event.target.checked)} />); + const input = find("input"); + expect(input.type).toBe("checkbox"); + expect(input.getAttribute("role")).toBe("switch"); + expect(input.checked).toBe(true); + await press(input, " "); + await press(input, " "); + expect(seen).toEqual([false, true]); + }); + + test("a controlled one shows what it is given and asks to change", async () => { + function Controlled() { + const [on, setOn] = useState(false); + return setOn(event.target.checked)} />; + } + await render(); + const input = find("input"); + await click(input); + expect(input.checked).toBe(true); + await click(input); + expect(input.checked).toBe(false); + }); + + test("a disabled one doesn't toggle and is skipped by the keyboard", async () => { + const onChange = mock(() => {}); + await render( + <> + + + , + ); + for (const input of findAll("input")) { + expect(input.disabled).toBe(true); + await click(input); + expect(input.checked).toBe(false); + } + expect(onChange).not.toHaveBeenCalled(); + }); + + test("given a label, the whole label is the click target and the checkbox's name", async () => { + const seen: boolean[] = []; + await render( seen.push(event.target.checked)} />); + const label = find("label"); + const input = find("input"); + expect(label.contains(input)).toBe(true); + expect(label.textContent).toBe("Luis Ortega"); + // At least 24px tall, so the label is a target a thumb can hit. + expect(label.className).toMatch(/\bmin-h-6\b/); + await click(byText("Luis Ortega", "span")); + expect(input.checked).toBe(true); + await click(label); + expect(input.checked).toBe(false); + expect(seen).toEqual([true, false]); + }); + + test("a labelled Checkbox that is disabled can't be toggled from its label either", async () => { + await render(); + await click(find("label")); + expect(find("input").checked).toBe(false); + }); + + test("the text beside one toggles it, when it is in a label", async () => { + await render( + , + ); + await click(find("label")); + expect(find("input").checked).toBe(true); + }); + + test("the box and the track draw from the tokens, with no fixed colours", () => { + const markup = renderToStaticMarkup( + <> + + + , + ); + expect(markup).not.toMatch(/#[0-9a-f]{3,8}\b/i); + expect(markup).toContain("appearance-none"); + }); +}); + +describe("Meter", () => { + const widths = (markup: string) => [...markup.matchAll(/width:([\d.]+)%/g)].map((match) => Number(match[1])); + + test("fills to the share in use, hidden from assistive technology (the text beside it says the same)", () => { + const markup = renderToStaticMarkup(); + expect(markup).toContain('aria-hidden="true"'); + expect(widths(markup)).toEqual([60]); + expect(markup).not.toContain("error-foreground"); + }); + + test("past the quantity, the covered part stays dark and the licenses past it are amber", () => { + const markup = renderToStaticMarkup(); + expect(widths(markup)).toEqual([80]); + expect(markup).toContain("bg-error-foreground"); + }); + + test("an empty license is an empty bar, not a division by zero", () => { + expect(widths(renderToStaticMarkup())).toEqual([0]); + }); +}); + +describe("Stepper", () => { + function Seats(props: { min?: number; max?: number; start?: number; onChange?: (n: number) => void }) { + const [n, setN] = useState(props.start ?? 5); + return ( + { + props.onChange?.(next); + setN(next); + }} + /> + ); + } + const field = () => find('input[aria-label="Licenses"]'); + const fewer = () => find('button[aria-label="One license fewer"]'); + const more = () => find('button[aria-label="One license more"]'); + + test("shows − n + and moves one at a time", async () => { + await render(); + expect(field().value).toBe("5"); + await click(more()); + await click(more()); + await click(fewer()); + expect(field().value).toBe("6"); + }); + + test("stops at its bounds: the buttons are disabled and nothing is asked for past them", async () => { + const onChange = mock((_n: number) => {}); + await render(); + await click(more()); + expect(field().value).toBe("4"); + expect(more().disabled).toBe(true); + await click(more()); + await click(fewer()); + await click(fewer()); + expect(field().value).toBe("2"); + expect(fewer().disabled).toBe(true); + await click(fewer()); + expect(onChange.mock.calls.map((call) => call[0])).toEqual([4, 3, 2]); + }); + + test("has no upper bound without a maximum", async () => { + await render(); + await click(more()); + expect(field().value).toBe("1000"); + expect(more().disabled).toBe(false); + }); + + test("the arrow keys step it, within the bounds, and it reads as a spinbutton", async () => { + await render(); + const input = field(); + expect(input.getAttribute("role")).toBe("spinbutton"); + expect([input.getAttribute("aria-valuemin"), input.getAttribute("aria-valuemax"), input.getAttribute("aria-valuenow")]).toEqual(["1", "3", "2"]); + await press(input, "ArrowUp"); + await press(input, "ArrowUp"); + expect(input.value).toBe("3"); + await press(input, "ArrowDown"); + await press(input, "ArrowDown"); + await press(input, "ArrowDown"); + expect(input.value).toBe("1"); + }); + + test("a typed number is taken when they leave the field or press Enter, and is held to the bounds", async () => { + const onChange = mock((_n: number) => {}); + await render(); + const input = field(); + await focus(input); + await typeInto(input, "12"); + expect(onChange).not.toHaveBeenCalled(); + await press(input, "Enter"); + expect(input.value).toBe("12"); + await typeInto(input, "900"); + await act(async () => input.blur()); + expect(input.value).toBe("50"); + await typeInto(input, "0"); + await press(input, "Enter"); + expect(input.value).toBe("1"); + expect(onChange.mock.calls.map((call) => call[0])).toEqual([12, 50, 1]); + }); + + test("something that isn't a number goes back to the last count", async () => { + await render(); + const input = field(); + await focus(input); + await typeInto(input, ""); + await press(input, "Enter"); + expect(input.value).toBe("5"); + await typeInto(input, "ab"); + expect(input.value).toBe(""); + await act(async () => input.blur()); + expect(input.value).toBe("5"); + }); + + test("a stepper is never a submit button inside a form", async () => { + await render( +
+ + , + ); + expect(fewer().type).toBe("button"); + expect(more().type).toBe("button"); + }); +}); + +describe("Menu", () => { + const items = (onSelect: (key: string) => void = () => {}) => [ + { key: "change", label: "Change license count", onSelect: () => onSelect("change") }, + { key: "cancel", label: "Cancel", onSelect: () => onSelect("cancel") }, + { key: "locked", label: "Locked", disabled: true, onSelect: () => onSelect("locked") }, + { key: "other", label: "Pause billing", onSelect: () => onSelect("other") }, + ]; + const trigger = () => find('button[aria-haspopup="menu"]'); + const menuItems = () => findAll('[role="menuitem"]'); + + async function mountMenu(onSelect?: (key: string) => void) { + await render( +
+ + +
, + ); + } + + test("is a button that names itself, collapsed until opened", async () => { + await mountMenu(); + expect(trigger().getAttribute("aria-label")).toBe("More for Mentra Call"); + expect(trigger().getAttribute("aria-expanded")).toBe("false"); + expect(findAll('[role="menu"]')).toHaveLength(0); + }); + + test("opens with Enter and puts focus on the first item", async () => { + await mountMenu(); + await focus(trigger()); + await press(trigger(), "Enter"); + expect(trigger().getAttribute("aria-expanded")).toBe("true"); + expect(menuItems().map((item) => item.textContent)).toEqual(["Change license count", "Cancel", "Locked", "Pause billing"]); + expect(activeElement()).toBe(menuItems()[0]!); + }); + + test("ArrowDown on the closed button opens it too, and ArrowUp opens it on the last item", async () => { + await mountMenu(); + await focus(trigger()); + await press(trigger(), "ArrowDown"); + expect(activeElement()).toBe(menuItems()[0]!); + await press(menuItems()[0]!, "Escape"); + await press(trigger(), "ArrowUp"); + expect(activeElement()).toBe(menuItems().at(-1)!); + }); + + test("the arrow keys move between items, skip a disabled one, wrap, and Home and End jump", async () => { + await mountMenu(); + await focus(trigger()); + await press(trigger(), "Enter"); + const [change, cancel, , other] = menuItems(); + await press(activeElement()!, "ArrowDown"); + expect(activeElement()).toBe(cancel!); + await press(activeElement()!, "ArrowDown"); + expect(activeElement()).toBe(other!); + await press(activeElement()!, "ArrowDown"); + expect(activeElement()).toBe(change!); + await press(activeElement()!, "ArrowUp"); + expect(activeElement()).toBe(other!); + await press(activeElement()!, "Home"); + expect(activeElement()).toBe(change!); + await press(activeElement()!, "End"); + expect(activeElement()).toBe(other!); + }); + + test("Escape closes it and gives focus back to the button", async () => { + await mountMenu(); + await focus(trigger()); + await press(trigger(), "Enter"); + await press(activeElement()!, "Escape"); + expect(findAll('[role="menu"]')).toHaveLength(0); + expect(trigger().getAttribute("aria-expanded")).toBe("false"); + expect(activeElement()).toBe(trigger()); + }); + + test("an outside click closes it", async () => { + await mountMenu(); + await click(trigger()); + expect(findAll('[role="menu"]')).toHaveLength(1); + await pointerDown(byText("elsewhere", "button")); + expect(findAll('[role="menu"]')).toHaveLength(0); + }); + + test("a click inside doesn't close it before the item is chosen", async () => { + await mountMenu(); + await click(trigger()); + await pointerDown(menuItems()[0]!); + expect(findAll('[role="menu"]')).toHaveLength(1); + }); + + test("choosing an item runs it once, closes the menu and returns focus", async () => { + const chosen: string[] = []; + await mountMenu((key) => chosen.push(key)); + await focus(trigger()); + await press(trigger(), "Enter"); + await press(activeElement()!, "ArrowDown"); + await press(activeElement()!, "Enter"); + expect(chosen).toEqual(["cancel"]); + expect(findAll('[role="menu"]')).toHaveLength(0); + expect(activeElement()).toBe(trigger()); + }); + + test("a disabled item can't be chosen", async () => { + const chosen: string[] = []; + await mountMenu((key) => chosen.push(key)); + await click(trigger()); + expect(byText("Locked", '[role="menuitem"]').disabled).toBe(true); + await click(byText("Locked", '[role="menuitem"]')); + expect(chosen).toEqual([]); + }); + + test("Tab closes it and leaves focus to move on", async () => { + await mountMenu(); + await click(trigger()); + expect(await press(activeElement()!, "Tab")).toBe(false); + expect(findAll('[role="menu"]')).toHaveLength(0); + }); + + test("a menu in a panel doesn't let Escape close the panel too", async () => { + const onClose = mock(() => {}); + await render( + + + , + ); + await click(byText("Change role", "button")); + expect(findAll('[role="menu"]')).toHaveLength(1); + await press(activeElement()!, "Escape"); + expect(findAll('[role="menu"]')).toHaveLength(0); + expect(onClose).not.toHaveBeenCalled(); + await press(byText("Change role", "button"), "Escape"); + expect(onClose).toHaveBeenCalledTimes(1); + }); +}); + +describe("SidePanel", () => { + function Host(props: { onClosed?: () => void; startOpen?: boolean }) { + const [open, setOpen] = useState(props.startOpen ?? false); + return ( +
+ + { + props.onClosed?.(); + setOpen(false); + }} + title="Luis Ortega" + description="luis.ortega@example.com" + > + + + + +
+ ); + } + const dialog = () => find("dialog"); + + test("is a modal dialog named by its title and described by its description", async () => { + await render(); + expect(dialog().open).toBe(true); + const labelledBy = dialog().getAttribute("aria-labelledby")!; + expect(find(`#${CSS.escape(labelledBy)}`).textContent).toBe("Luis Ortega"); + const describedBy = dialog().getAttribute("aria-describedby")!; + expect(find(`#${CSS.escape(describedBy)}`).textContent).toBe("luis.ortega@example.com"); + }); + + test("draws nothing but the shell while closed, so what is inside starts fresh each time", async () => { + await render(); + expect(dialog().open).toBe(false); + expect(findAll("button", dialog())).toHaveLength(0); + }); + + test("opening puts focus inside it", async () => { + await render(); + const opener = byText("Open panel", "button"); + await focus(opener); + await click(opener); + expect(dialog().open).toBe(true); + expect(dialog().contains(activeElement())).toBe(true); + }); + + test("traps focus: Tab from the last control goes to the first, and Shift+Tab from the first goes to the last", async () => { + await render(); + const controls = findAll("button, input", dialog()); + const first = controls[0]!; + const last = controls.at(-1)!; + expect(first.getAttribute("aria-label")).toBe("Close"); + await focus(last); + expect(await press(last, "Tab")).toBe(true); + expect(activeElement()).toBe(first); + expect(await press(first, "Tab", { shift: true })).toBe(true); + expect(activeElement()).toBe(last); + }); + + test("Tab between its controls is left to the browser", async () => { + await render(); + const middle = find("input", dialog()); + await focus(middle); + expect(await press(middle, "Tab")).toBe(false); + }); + + test("closes on Escape, and focus returns to what opened it", async () => { + const onClosed = mock(() => {}); + await render(); + const opener = byText("Open panel", "button"); + await focus(opener); + await click(opener); + await press(find("input", dialog()), "Escape"); + expect(onClosed).toHaveBeenCalledTimes(1); + expect(dialog().open).toBe(false); + expect(activeElement()).toBe(opener); + }); + + test("closes from its × and from a click on the backdrop, once each", async () => { + const onClosed = mock(() => {}); + await render(); + await click(find('button[aria-label="Close"]', dialog())); + expect(onClosed).toHaveBeenCalledTimes(1); + await click(byText("Open panel", "button")); + await click(dialog()); + expect(onClosed).toHaveBeenCalledTimes(2); + }); + + test("a click inside it is not a click on the backdrop", async () => { + const onClosed = mock(() => {}); + await render(); + await click(byText("First action", "button")); + expect(onClosed).not.toHaveBeenCalled(); + }); + + test("the browser's own cancel (a close request) is handed to the host, which decides", async () => { + const onClosed = mock(() => {}); + await render(); + const cancel = new Event("cancel", { cancelable: true }); + await act(async () => void dialog().dispatchEvent(cancel)); + expect(cancel.defaultPrevented).toBe(true); + expect(onClosed).toHaveBeenCalledTimes(1); + }); + + test("Escape inside a dialog opened from the panel closes that one, not the panel", async () => { + const onClosed = mock(() => {}); + await render( + + + + + , + ); + await press(byText("Confirm", "button"), "Escape"); + expect(onClosed).not.toHaveBeenCalled(); + }); + + // Whatever follows the last reachable control must not be taken for the end of the tab order. + const UNREACHABLE: Array<[string, ReactNode]> = [ + ["a control with tabindex -1 (a menu's items)", ], + ["a control in a disabled fieldset",
], + ["a control in hidden content", ], + ["a control in inert content",
], + ["a control in aria-hidden content", ], + ]; + + for (const [name, trailing] of UNREACHABLE) { + test(`Tab wraps at the last control a person can reach, not at ${name}`, async () => { + await render( + {}} title="Luis Ortega"> + + + {trailing} + , + ); + const last = byText("Last action", "button"); + await focus(last); + expect(await press(last, "Tab")).toBe(true); + expect(activeElement()).toBe(find('button[aria-label="Close"]')); + await press(activeElement()!, "Tab", { shift: true }); + expect(activeElement()).toBe(last); + }); + } + + test("Escape calls onClose once, even when the browser also sends its own cancel for the same press", async () => { + const onClosed = mock(() => {}); + await render( + + + , + ); + await act(async () => { + const input = find("input", dialog()); + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })); + // A browser that doesn't honour the cancelled keydown sends the close request as well. + dialog().dispatchEvent(new Event("cancel", { cancelable: true })); + }); + expect(onClosed).toHaveBeenCalledTimes(1); + }); + + test("and a later Escape asks again, for a host that stayed open to ask the person first", async () => { + const onClosed = mock(() => {}); + await render( + + + , + ); + await press(find("input", dialog()), "Escape"); + await act(async () => void (await new Promise((resolve) => setTimeout(resolve, 20)))); + await press(find("input", dialog()), "Escape"); + expect(onClosed).toHaveBeenCalledTimes(2); + }); + + test("is full-screen on a phone and a right-hand sheet from the small breakpoint", () => { + const markup = renderToStaticMarkup( + {}} title="Luis Ortega"> + body + , + ); + expect(markup).toMatch(/class="[^"]*\bw-full\b/); + expect(markup).toMatch(/class="[^"]*\bh-dvh\b/); + expect(markup).toMatch(/class="[^"]*\bsm:max-w-/); + expect(markup).toMatch(/class="[^"]*\bml-auto\b/); + }); +}); + +describe("the licenses' small pieces", () => { + test("a Notice is a status in every tone: nothing on these pages interrupts the person, so none is an alert", () => { + const warn = renderToStaticMarkup( + Update payment method}> + Update the payment method to keep them. + , + ); + expect(warn).toContain('role="status"'); + expect(warn).not.toContain('role="alert"'); + expect(warn).toContain("bg-error"); + expect(warn).toContain("Update the payment method to keep them."); + expect(renderToStaticMarkup()).toContain('role="status"'); + expect(renderToStaticMarkup()).toContain('role="status"'); + }); + + test("a Notice's buttons wrap on a row of their own on a phone instead of running out of the notice", () => { + const markup = renderToStaticMarkup( + } />, + ); + const actions = /