Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Give every refused pairing a code
milind-soni3d347f021350
diff --git a/companion/src/devices.ts b/companion/src/devices.tsindex 7c00817fcb..3dd9bce479 100644--- a/companion/src/devices.ts+++ b/companion/src/devices.ts@@ -30,6 +30,12 @@ export type DeviceRoutes = "any" | "local";export type PublicDevice = Omit<DeviceRecord, "tokenHash">;+/** A refused `POST /api/pair`: `code` is one of the phone protocol's PairingErrorCode values. */+export interface PairingRefusal {+ error: string;+ code: "pairing_bad_request" | "pairing_not_open" | "pairing_too_many" | "pairing_code_wrong" | "pairing_device_limit" | "pairing_failed";+}+/** `token` rides in the QR, has enough entropy to stand alone and is never* persisted. `code` is six digits, so it lives two minutes and dies after a* few wrong guesses. Redeeming either burns both. */@@ -277,7 +283,7 @@ export class DeviceRegistry {credential: string,name: unknown,pairRequestId?: unknown,- ): { device: PublicDevice; token: string } | { error: string } {+ ): { device: PublicDevice; token: string } | PairingRefusal {const presented = String(credential ?? "");const requestId =typeof pairRequestId === "string" && /^[A-Za-z0-9._-]{16,128}$/.test(pairRequestId)@@ -296,19 +302,19 @@ export class DeviceRegistry {const windows = this.pairingWindows();const window = windows.find((candidate) => sameCredential(candidate.code, presented) || sameCredential(candidate.token, presented));- if (windows.length === 0) return { error: "no pairing is in progress — open Phone settings on your computer" };+ if (windows.length === 0) return { error: "no pairing is in progress — open Phone settings on your computer", code: "pairing_not_open" };if (!window) {// Every open window pays for a wrong guess: without burning them, six digits is seconds of guessing.for (const open of windows) open.attemptsLeft -= 1;if (windows.some((open) => open.attemptsLeft <= 0)) {this.closePairing();- return { error: "too many incorrect codes — start pairing again" };+ return { error: "too many incorrect codes — start pairing again", code: "pairing_too_many" };}- return { error: "that pairing credential is not right" };+ return { error: "that pairing credential is not right", code: "pairing_code_wrong" };}// After the code check: a full fleet must not answer wrong guesses, which// would leak state and cost no attempts.- if (this.devices.length >= MAX_DEVICES) return { error: "too many paired devices — remove one first" };+ if (this.devices.length >= MAX_DEVICES) return { error: "too many paired devices — remove one first", code: "pairing_device_limit" };// Consume every open window without clearing a replay; `closePairing` clears both.this.window = null;this.previousWindow = null;@@ -331,7 +337,7 @@ export class DeviceRegistry {this.persist();} catch (e) {this.devices.pop();- return { error: `could not save the pairing: ${(e as Error).message}` };+ return { error: `could not save the pairing: ${(e as Error).message}`, code: "pairing_failed" };}this.changed();const unconfirmed = setTimeout(() => {diff --git a/companion/src/proxy.ts b/companion/src/proxy.tsindex 56dc651ec9..0ac13168dd 100644--- a/companion/src/proxy.ts+++ b/companion/src/proxy.ts@@ -6,7 +6,7 @@ import type { Duplex, Readable } from "node:stream";import { StringDecoder } from "node:string_decoder";import { createGzip, type Gzip } from "node:zlib";-import { bearerToken } from "./devices.ts";+import { bearerToken, type PairingRefusal } from "./devices.ts";import type { E2EDescriptor } from "./e2e/descriptor.ts";import { e2eContextOf } from "./e2e/origin.ts";import type { E2EContext } from "./e2e/registry.ts";@@ -38,7 +38,7 @@ export interface ProxyOptions {code: string,deviceName: unknown,pairRequestId?: unknown,- ) => { token: string; device: unknown } | { error: string };+ ) => { token: string; device: unknown } | PairingRefusal;serverName: () => string;/** The desktop app's version: told only to a paired device. */version?: string;@@ -455,14 +455,14 @@ export function createProxyHandler(options: ProxyOptions) {(body) => {const credential = body.credential ?? body.code;if (!isPlainValue(credential) || !isPlainValue(body.deviceName)) {- return sendJson(res, 400, { error: "invalid pairing request" });+ return sendJson(res, 400, { error: "invalid pairing request", code: "pairing_bad_request" } satisfies PairingRefusal);}const result = options.redeem(String(credential ?? ""),body.deviceName,body.pairRequestId,);- if ("error" in result) return sendJson(res, 401, { error: result.error });+ if ("error" in result) return sendJson(res, 401, { error: result.error, code: result.code } satisfies PairingRefusal);const pairedId = (result.device as { id?: unknown } | null)?.id;if (e2e && typeof pairedId === "string") options.e2ePaired?.(e2e, pairedId);const hosts = options.hosts?.() ?? [];@@ -482,10 +482,10 @@ export function createProxyHandler(options: ProxyOptions) {if (descriptor) response.e2e = descriptor;return sendJson(res, 201, response);},- (error: Error) => sendJson(res, 400, { error: error.message }),+ (error: Error) => sendJson(res, 400, { error: error.message, code: "pairing_bad_request" } satisfies PairingRefusal),).catch((error: unknown) => {console.error("companion: pairing failed", error);- sendJson(res, 500, { error: "could not complete the pairing" });+ sendJson(res, 500, { error: "could not complete the pairing", code: "pairing_failed" } satisfies PairingRefusal);});return;}diff --git a/companion/test/browser-revocation.test.ts b/companion/test/browser-revocation.test.tsindex 5e3b1ead1f..e91e2d5983 100644--- a/companion/test/browser-revocation.test.ts+++ b/companion/test/browser-revocation.test.ts@@ -38,7 +38,7 @@ describe("browser authorization while the harness is responding", () => {harnessPort: upstreamPort,authenticate: (token) => token === "fixture-token" && valid? { id: "fixture-phone", cloudDesktopAccess: false, browserControlAccess: allowed } : null,- redeem: () => ({ error: "offline fixture" }),+ redeem: () => ({ error: "offline fixture", code: "pairing_code_wrong" }),serverName: () => "Synthetic computer",});const relay = createServer(handler);diff --git a/companion/test/devices.test.ts b/companion/test/devices.test.tsindex 05e352d399..932d5f25b8 100644--- a/companion/test/devices.test.ts+++ b/companion/test/devices.test.ts@@ -127,13 +127,13 @@ describe("DeviceRegistry", () => {const wrong = code === "000000" ? "111111" : "000000";for (let i = 1; i < MAX_PAIRING_ATTEMPTS; i++) {- expect(registry.redeem(wrong, "iPhone")).toEqual({ error: "that pairing credential is not right" });+ expect(registry.redeem(wrong, "iPhone")).toEqual({ error: "that pairing credential is not right", code: "pairing_code_wrong" });expect(registry.pairing()).not.toBeNull();}- expect(registry.redeem(wrong, "iPhone")).toMatchObject({ error: expect.stringContaining("start pairing again") });+ expect(registry.redeem(wrong, "iPhone")).toMatchObject({ error: expect.stringContaining("start pairing again"), code: "pairing_too_many" });expect(registry.pairing()).toBeNull();- expect(registry.redeem(code, "iPhone")).toMatchObject({ error: expect.stringContaining("no pairing") });+ expect(registry.redeem(code, "iPhone")).toMatchObject({ error: expect.stringContaining("no pairing"), code: "pairing_not_open" });expect(registry.count()).toBe(0);});@@ -148,6 +148,7 @@ describe("DeviceRegistry", () => {it("points an out-of-window pairing attempt to Phone settings", () => {expect(new DeviceRegistry().redeem("000000", "iPhone")).toEqual({error: "no pairing is in progress — open Phone settings on your computer",+ code: "pairing_not_open",});});diff --git a/companion/test/large-json.test.ts b/companion/test/large-json.test.tsindex 7f7aeab092..29bc627b67 100644--- a/companion/test/large-json.test.ts+++ b/companion/test/large-json.test.ts@@ -91,7 +91,7 @@ beforeAll(async () => {const options = (extra: Partial<ProxyOptions> = {}): ProxyOptions => ({harnessPort: 0,authenticate: (t) => (t === TOKEN ? { id: "phone-1", cloudDesktopAccess: true, browserControlAccess: true } : null),- redeem: () => ({ error: "not used here" }),+ redeem: () => ({ error: "not used here", code: "pairing_code_wrong" }),serverName: () => "Test computer",...extra,});diff --git a/companion/test/malformed-requests.test.ts b/companion/test/malformed-requests.test.tsindex 26a0c69a36..78729bb888 100644--- a/companion/test/malformed-requests.test.ts+++ b/companion/test/malformed-requests.test.ts@@ -36,7 +36,7 @@ const sidecar = async (redeemed: unknown[] = []) => {authenticate: (token) => token === "paired" ? { id: "phone", cloudDesktopAccess: true, browserControlAccess: false } : null,redeem: (code, deviceName) => {redeemed.push([code, deviceName]);- return { error: "that pairing credential is not right" };+ return { error: "that pairing credential is not right", code: "pairing_code_wrong" };},serverName: () => "Fixture",});diff --git a/companion/test/phone-protocol.test.ts b/companion/test/phone-protocol.test.tsindex 1551ac5ee2..b70f31e8ef 100644--- a/companion/test/phone-protocol.test.ts+++ b/companion/test/phone-protocol.test.ts@@ -1,7 +1,8 @@import { describe, expectTypeOf, it } from "vitest";import type { CompanionEndpointsSnapshot, PairResponse, ServerFrame } from "../../packages/phone-protocol/src/wire.ts";-import type { PublicDevice } from "../src/devices.ts";+import type { PairingErrorCode } from "../../packages/phone-protocol/src/pairing-code.ts";+import type { PairingRefusal, PublicDevice } from "../src/devices.ts";import type { E2EDescriptor } from "../src/e2e/descriptor.ts";import type { CompanionEndpoint } from "../src/endpoints.ts";import type { CompanionEndpointSnapshot } from "../src/proxy.ts";@@ -13,5 +14,6 @@ describe("the phone protocol's types", () => {expectTypeOf<{ kind: "companion.endpoints" } & Endpoints>().toExtend<ServerFrame>();type Paired = { device: PublicDevice; token: string } & { serverName: string; hosts?: string[]; endpoints?: CompanionEndpoint[]; e2e?: E2EDescriptor };expectTypeOf<Paired>().toExtend<PairResponse>();+ expectTypeOf<PairingRefusal["code"]>().toExtend<PairingErrorCode>();});});diff --git a/companion/test/proxy-response.test.ts b/companion/test/proxy-response.test.tsindex a1628a7428..fc6218da8b 100644--- a/companion/test/proxy-response.test.ts+++ b/companion/test/proxy-response.test.ts@@ -61,7 +61,7 @@ beforeAll(async () => {createProxyHandler({harnessPort,authenticate: (t) => (t === TOKEN ? { id: "phone-1", cloudDesktopAccess, browserControlAccess: false } : null),- redeem: () => ({ error: "not used here" }),+ redeem: () => ({ error: "not used here", code: "pairing_code_wrong" }),serverName: () => "Test computer",endpoints: () => endpointCandidates,}),diff --git a/companion/test/proxy.test.ts b/companion/test/proxy.test.tsindex 3c2917abe0..e5ab0b41f3 100644--- a/companion/test/proxy.test.ts+++ b/companion/test/proxy.test.ts@@ -147,7 +147,7 @@ beforeAll(async () => {redeem: (code, deviceName) =>code === "424242"? { token: TOKEN, device: { id: "d1", name: String(deviceName) } }- : { error: "that code is not right" },+ : { error: "that code is not right", code: "pairing_code_wrong" },serverName: () => "Test computer",version: DESKTOP_VERSION,connected: connectedDevices.open,@@ -205,7 +205,7 @@ describe("the sidecar in front of an unmodified harness", () => {const delayedProxy = createServer(createProxyHandler({harnessPort: delayedHarnessPort,authenticate: () => valid ? { id: "phone-delayed", cloudDesktopAccess: false, browserControlAccess: false } : null,- redeem: () => ({ error: "not pairing" }),+ redeem: () => ({ error: "not pairing", code: "pairing_code_wrong" }),serverName: () => "Test computer",connected: connections.open,}));@@ -542,7 +542,7 @@ describe("the sidecar in front of an unmodified harness", () => {createProxyHandler({harnessPort: 1,authenticate: () => ({ cloudDesktopAccess: true, browserControlAccess: false }),- redeem: () => ({ error: "no" }),+ redeem: () => ({ error: "no", code: "pairing_code_wrong" }),serverName: () => "Test computer",}),);@@ -568,7 +568,7 @@ describe("the sidecar in front of an unmodified harness", () => {createProxyHandler({harnessPort: mutePort,authenticate: () => ({ cloudDesktopAccess: true, browserControlAccess: false }),- redeem: () => ({ error: "no" }),+ redeem: () => ({ error: "no", code: "pairing_code_wrong" }),serverName: () => "Test computer",headersTimeoutMs: 300,}),@@ -609,7 +609,7 @@ describe("the sidecar in front of an unmodified harness", () => {createProxyHandler({harnessPort: slowPort,authenticate: () => ({ cloudDesktopAccess: true, browserControlAccess: false }),- redeem: () => ({ error: "no" }),+ redeem: () => ({ error: "no", code: "pairing_code_wrong" }),serverName: () => "Test computer",}),);@@ -659,7 +659,7 @@ describe("the sidecar in front of an unmodified harness", () => {createProxyHandler({harnessPort: floodPort,authenticate: () => ({ cloudDesktopAccess: true, browserControlAccess: false }),- redeem: () => ({ error: "no" }),+ redeem: () => ({ error: "no", code: "pairing_code_wrong" }),serverName: () => "Test computer",}),);@@ -695,7 +695,7 @@ describe("live companion endpoint refresh", () => {// No harness on port 1: a 200 proves the sidecar answered locally.harnessPort: 1,authenticate: (token) => token === TOKEN ? { cloudDesktopAccess: false, browserControlAccess: false } : null,- redeem: () => ({ error: "not used" }),+ redeem: () => ({ error: "not used", code: "pairing_code_wrong" }),serverName: () => "Test computer",endpoints: () => endpoints,}),@@ -809,6 +809,17 @@ describe("pairing, end to end", () => {body: JSON.stringify({ code: "000000", deviceName: "Impostor" }),});expect(wrong.status).toBe(401);+ expect(await wrong.json()).toEqual({ error: "that pairing credential is not right", code: "pairing_code_wrong" });+ const malformed = await fetch(`${base}/api/pair`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ code: { nested: true }, deviceName: "Impostor" }),+ });+ expect(malformed.status).toBe(400);+ expect(await malformed.json()).toEqual({ error: "invalid pairing request", code: "pairing_bad_request" });+ const notJson = await fetch(`${base}/api/pair`, { method: "POST", headers: { "content-type": "application/json" }, body: "{" });+ expect(notJson.status).toBe(400);+ expect(((await notJson.json()) as { code?: string }).code).toBe("pairing_bad_request");const pairRequestId = "4c825d5b-cf40-4db7-aac5-2455f805a8ec";const pairBody = JSON.stringify({@@ -1057,7 +1068,7 @@ describe("the desktop version the sidecar reports", () => {// No harness on port 1: the endpoint list is the sidecar's own answer.harnessPort: 1,authenticate: (token) => token === TOKEN ? { cloudDesktopAccess: false, browserControlAccess: false } : null,- redeem: () => ({ error: "not used" }),+ redeem: () => ({ error: "not used", code: "pairing_code_wrong" }),serverName: () => "Test computer",version,}));diff --git a/companion/test/relay-auth.test.ts b/companion/test/relay-auth.test.tsindex f5be042110..52ca0cca85 100644--- a/companion/test/relay-auth.test.ts+++ b/companion/test/relay-auth.test.ts@@ -30,7 +30,7 @@ it("adds the private capability only after authenticating and authorizing, neverconst port = await listen(createServer(createProxyHandler({harnessPort, mutationToken: () => capability,authenticate: (token) => token === "paired" ? { id: "real-phone", cloudDesktopAccess: false, browserControlAccess: false } : null,- redeem: () => ({ error: "not pairing" }), serverName: () => "Fixture",+ redeem: () => ({ error: "not pairing", code: "pairing_code_wrong" }), serverName: () => "Fixture",})));const call = async (path: string, token = "paired", method = "POST") => {const res = await fetch(`http://127.0.0.1:${port}${path}`, { method, headers: {diff --git a/companion/test/tunnel-gzip.test.ts b/companion/test/tunnel-gzip.test.tsindex 0fcc676e3a..71b3cb77db 100644--- a/companion/test/tunnel-gzip.test.ts+++ b/companion/test/tunnel-gzip.test.ts@@ -36,7 +36,7 @@ beforeAll(async () => {const proxy = createProxyHandler({harnessPort: await listen(harness),authenticate: (t) => (t === TOKEN ? { id: "phone-1", cloudDesktopAccess: true, browserControlAccess: false } : null),- redeem: () => ({ error: "not used here" }),+ redeem: () => ({ error: "not used here", code: "pairing_code_wrong" }),serverName: () => "Test computer",endpoints: () => ENDPOINTS,});diff --git a/companion/test/upstream-failure.test.ts b/companion/test/upstream-failure.test.tsindex ff7fa62bf4..f8d058ff1d 100644--- a/companion/test/upstream-failure.test.ts+++ b/companion/test/upstream-failure.test.ts@@ -29,7 +29,7 @@ const stand = async (harness: Server): Promise<string> => {createProxyHandler({harnessPort,authenticate: () => ({ cloudDesktopAccess: true, browserControlAccess: false }),- redeem: () => ({ error: "not in this test" }),+ redeem: () => ({ error: "not in this test", code: "pairing_code_wrong" }),serverName: () => "Ada's computer",}),);@@ -115,7 +115,7 @@ describe("an upstream that fails mid-stream", () => {createProxyHandler({harnessPort,authenticate: () => ({ cloudDesktopAccess: true, browserControlAccess: false }),- redeem: () => ({ error: "not in this test" }),+ redeem: () => ({ error: "not in this test", code: "pairing_code_wrong" }),serverName: () => "Ada's computer",}),);diff --git a/packages/phone-protocol/src/pairing-code.ts b/packages/phone-protocol/src/pairing-code.tsindex 9b5078061f..eb1ca78a79 100644--- a/packages/phone-protocol/src/pairing-code.ts+++ b/packages/phone-protocol/src/pairing-code.ts@@ -43,6 +43,36 @@ export const PAIRING_INPUT_PROBLEM_KEY: Record<PairingInputProblem, keyof typeofnotACode: "serverError.pair.notACode",};+/** The `code` on every refused pairing: `POST /api/pair` on a computer, a server or a Cloud, and `POST /api/auth/pair`.+ * `error` stays plain words any client can show; a client branches on `code`, never on `error`. */+export type PairingErrorCode =+ /** Not JSON, or not the fields a pairing sends. */+ | "pairing_bad_request"+ /** No open pairing has this code or credential. */+ | "pairing_code_wrong"+ /** A computer has no pairing open. */+ | "pairing_not_open"+ /** Too many wrong codes: wait (a server or Cloud says until when), or start pairing again (a computer). */+ | "pairing_too_many"+ /** A browser sign-in link that has expired or was used. */+ | "pairing_link_expired"+ | "pairing_email_code"+ | "pairing_old_code"+ | "pairing_script_key"+ /** Through the encrypted relay only the QR code's credential pairs, never a typed code. */+ | "pairing_qr_only"+ /** A computer already has as many paired devices as it allows. */+ | "pairing_device_limit"+ /** A personal Cloud pairs only its owner's devices. */+ | "cloud_personal"+ | "pairing_failed";++export const PAIRING_INPUT_PROBLEM_CODE: Record<Exclude<PairingInputProblem, "notACode">, PairingErrorCode> = {+ emailCode: "pairing_email_code",+ oldCode: "pairing_old_code",+ scriptKey: "pairing_script_key",+};+function fromLink(raw: string): string | null {let url: URL;try {diff --git a/server/index.ts b/server/index.tsindex c8175661e2..56c250e2ea 100644--- a/server/index.ts+++ b/server/index.ts@@ -547,7 +547,7 @@ import {serializeSessionCookie,sessionCookieName, ownerOrAdmin, acceptLegacyOrigins,} from "./request-auth.ts";-import { cookieMaxAgeSeconds, formatPairingCode, pairingRequest, SessionRegistry, type SessionRecord } from "./sessions.ts";+import { cookieMaxAgeSeconds, formatPairingCode, pairingRequest, SessionRegistry, type SessionRecord } from "./sessions.ts"; import type { PairingErrorCode } from "../shared/pairing-code.ts";import { ThreadStarters } from "./thread-starters.ts"; import { createConversationShares } from "./host/conversation-shares.ts"; import { createTeamMemorySaves } from "./host/team-memory-saves.ts"; import { createConversationSharing } from "./routes/conversation-share.ts";import { startPhoneRelay } from "./phone-relay.ts";import {@@ -12577,7 +12577,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (method === "POST" && path === "/api/auth/pair") {// JSON only: a cross-site HTML form cannot send this content type without a preflight, so no unused code is planted as a session.if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) {- return json(res, 415, { error: "send the pairing code as JSON (content-type: application/json)" });+ return json(res, 415, { error: "send the pairing code as JSON (content-type: application/json)", code: "pairing_bad_request" satisfies PairingErrorCode });}const body = await readBody(req);const code = typeof body?.code === "string" ? body.code : "";@@ -12589,13 +12589,13 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (browser && body?.preview === true) {// Shown before the person continues; redeems nothing.const preview = sessions.previewBrowserSignIn(code);- return preview ? json(res, 200, { ...preview, ...(CLOUD_TEAM ? { team: CLOUD_TEAM.name } : {}) }) : json(res, 401, userError("serverError.pair.linkExpired"));+ return preview ? json(res, 200, { ...preview, ...(CLOUD_TEAM ? { team: CLOUD_TEAM.name } : {}) }) : json(res, 401, { ...userError("serverError.pair.linkExpired"), code: "pairing_link_expired" satisfies PairingErrorCode });}- if (browser && !wantsCookie) return json(res, 400, { error: "a browser sign-in sets this browser's cookie; send cookie: true" });+ if (browser && !wantsCookie) return json(res, 400, { error: "a browser sign-in sets this browser's cookie; send cookie: true", code: "pairing_bad_request" satisfies PairingErrorCode });const result = sessions.exchange({ code, label, attemptId, browser, source: requestSource(req), fallbackLabel: labelFromUserAgent(req.headers["user-agent"]) });if (!result.ok) {console.warn(`pairing refused from ${requestSource(req)}: ${result.error}`);- return json(res, result.status, refusalBody(result));+ return json(res, result.status, { ...refusalBody(result), code: result.code });}if (CLOUD_TEAM) teamHost.met(result.session);const environment = environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !CLOUD_HOME && emailSignIn.enabled(), sharedComputers: lendingEnabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, ownHome: ownHome.takesMove() });@@ -12611,17 +12611,17 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {// The companion apps' pairing route: same window, lockout and single-use exchange as /api/auth/pair; redeeming the credential IS the sign-in.if (method === "POST" && path === "/api/pair") {if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) {- return json(res, 415, { error: "send the pairing credential as JSON (content-type: application/json)" });+ return json(res, 415, { error: "send the pairing credential as JSON (content-type: application/json)", code: "pairing_bad_request" satisfies PairingErrorCode });}const body = await readBody(req);const credential = typeof body?.credential === "string" ? body.credential : typeof body?.code === "string" ? body.code : "";const label = typeof body?.deviceName === "string" ? body.deviceName : "";const attemptId = typeof body?.pairRequestId === "string" ? body.pairRequestId : undefined;- const relayRefusal = phoneRelay?.pairingRefusal(req, credential); if (relayRefusal) return json(res, 400, { error: relayRefusal });+ const relayRefusal = phoneRelay?.pairingRefusal(req, credential); if (relayRefusal) return json(res, 400, { error: relayRefusal, code: "pairing_qr_only" satisfies PairingErrorCode });const paired = sessions.exchange({ code: credential, label, attemptId, source: requestSource(req), fallbackLabel: labelFromUserAgent(req.headers["user-agent"]) });if (!paired.ok) {console.warn(`pairing refused from ${requestSource(req)}: ${paired.error}`);- return json(res, paired.status, refusalBody(paired));+ return json(res, paired.status, { ...refusalBody(paired), code: paired.code });}// The shape the companion apps decode: token, device and serverName are required.return json(res, 200, {diff --git a/server/sessions.test.ts b/server/sessions.test.tsindex 1d46668584..08bd7aeee8 100644--- a/server/sessions.test.ts+++ b/server/sessions.test.ts@@ -176,7 +176,7 @@ describe("pairing codes", () => {const again = registry.exchange({ code, label: "x", source: "a" });expect(again.ok).toBe(false);if (!again.ok) expect(again.error).toMatch(/wrong or has expired/);- expect(again).toMatchObject({ status: 401, errorKey: "serverError.pair.codeWrong" });+ expect(again).toMatchObject({ status: 401, code: "pairing_code_wrong", errorKey: "serverError.pair.codeWrong" });const { code: stale } = registry.openPairing();clock += PAIRING_CODE_TTL_MS + 1;expect(registry.exchange({ code: stale, label: "x", source: "b" }).ok).toBe(false);@@ -212,7 +212,7 @@ describe("pairing codes", () => {if (!locked.ok) {expect(locked.status).toBe(429);expect(locked.error).toMatch(/^Too many wrong codes\. Try again at \d{2}:\d{2} UTC\.$/);- expect(locked).toMatchObject({ errorKey: "serverError.pair.tooMany", errorParams: { seconds: 300, until: clock + 300_000 } });+ expect(locked).toMatchObject({ code: "pairing_too_many", errorKey: "serverError.pair.tooMany", errorParams: { seconds: 300, until: clock + 300_000 } });}expect(registry.exchange({ code, label: "", source: "friend" }).ok).toBe(true);clock += PAIRING_LOCKOUT.lockMs + 1;@@ -255,10 +255,10 @@ describe("pairing codes", () => {});it("explains a code of the wrong kind and does not count it as a guess", () => {- for (const [input, key] of [["1234 5678", "serverError.pair.emailCode"], ["123456", "serverError.pair.oldCode"], [`omb_sess_${"a".repeat(43)}`, "serverError.pair.scriptKey"]] as const) {+ for (const [input, key, code] of [["1234 5678", "serverError.pair.emailCode", "pairing_email_code"], ["123456", "serverError.pair.oldCode", "pairing_old_code"], [`omb_sess_${"a".repeat(43)}`, "serverError.pair.scriptKey", "pairing_script_key"]] as const) {for (let i = 0; i < PAIRING_LOCKOUT.failures + 1; i++) {const refused = registry.exchange({ code: input, label: "", source: "mixed-up" });- expect(refused).toMatchObject({ ok: false, status: 400, errorKey: key });+ expect(refused).toMatchObject({ ok: false, status: 400, code, errorKey: key });}}expect(registry.failureSources()).not.toContain("mixed-up");@@ -716,7 +716,7 @@ describe("admin scope only (an OMB Cloud home is personal: server/cloud-owner.tsconst owner = registry.exchange({ code: registry.openPairing().credential, label: "Mac", source: "a" });registry.requireAdmin(userError("serverError.cloud.personal"));expect(() => registry.openPairing({ scopes: ["client"] })).toThrow(PERSONAL);- expect(registry.exchange({ code: openWindow.credential, label: "Guest", source: "b" })).toEqual({ ok: false, status: 403, error: PERSONAL, errorKey: "serverError.cloud.personal" });+ expect(registry.exchange({ code: openWindow.credential, label: "Guest", source: "b" })).toEqual({ ok: false, status: 403, code: "cloud_personal", error: PERSONAL, errorKey: "serverError.cloud.personal" });expect(() => registry.issue({ label: "Friend", scopes: ["client"], email: "[email protected]" })).toThrow(PERSONAL);expect(() => registry.issuePortal({ email: "[email protected]", grant: "g".repeat(43), scopes: ["client"] })).toThrow(PERSONAL);if (!stored.ok || !owner.ok) throw new Error("unreachable");diff --git a/server/sessions.ts b/server/sessions.tsindex 96d36de95f..6a5dd74f82 100644--- a/server/sessions.ts+++ b/server/sessions.ts@@ -11,8 +11,10 @@ import {PAIRING_CODE_ALPHABET,PAIRING_CODE_LENGTH,PAIRING_CREDENTIAL_PREFIX,+ PAIRING_INPUT_PROBLEM_CODE,PAIRING_INPUT_PROBLEM_KEY,readPairingInput,+ type PairingErrorCode,} from "../shared/pairing-code.ts";import { userError, type UserError } from "./user-errors.ts";@@ -136,7 +138,7 @@ export interface PublicPairing {export type ExchangeResult =| { ok: true; token: string; session: PublicSession }- | ({ ok: false; status: 400 | 401 | 403 | 429 } & UserError);+ | ({ ok: false; status: 400 | 401 | 403 | 429; code: PairingErrorCode } & UserError);const sha256 = (value: string) => createHash("sha256").update(value).digest("hex");/** The English fallback's clock; a client words `until` in its own time zone. */@@ -446,7 +448,7 @@ export class SessionRegistry {this.prune();const now = this.now();const read = readPairingInput(input.code);- if (read.kind === "wrong" && read.problem !== "notACode") return { ok: false, status: 400, ...userError(PAIRING_INPUT_PROBLEM_KEY[read.problem]) };+ if (read.kind === "wrong" && read.problem !== "notACode") return { ok: false, status: 400, code: PAIRING_INPUT_PROBLEM_CODE[read.problem], ...userError(PAIRING_INPUT_PROBLEM_KEY[read.problem]) };// A credential is hashed as presented: normalizePairingCode folds 0 to O and 1 to I, which would merge distinct secrets.const presented = sha256(read.kind === "credential" ? read.credential : read.kind === "code" ? read.code : normalizePairingCode(input.code));const browser = input.browser === true;@@ -457,18 +459,18 @@ export class SessionRegistry {const lock = unnamed ? { locked: false, retryAfterMs: 0 } : this.lockState(this.codeFailures, input.source);if (lock.locked) {const until = now + lock.retryAfterMs;- return { ok: false, status: 429, ...userError("serverError.pair.tooMany", { seconds: Math.ceil(lock.retryAfterMs / 1000), until, time: utcClock(until) }) };+ return { ok: false, status: 429, code: "pairing_too_many", ...userError("serverError.pair.tooMany", { seconds: Math.ceil(lock.retryAfterMs / 1000), until, time: utcClock(until) }) };}const index = this.pairings.findIndex((p) => (p.browser === true) === browser &&(sameDigest(p.credentialHash, presented) || (!p.browser && sameDigest(p.codeHash, presented))));if (index < 0) {if (unnamed) this.wrongFromUnnamed();else this.recordFailure(this.codeFailures, PAIRING_LOCKOUT, input.source);- return { ok: false, status: 401, ...userError("serverError.pair.codeWrong") };+ return { ok: false, status: 401, code: "pairing_code_wrong", ...userError("serverError.pair.codeWrong") };}const [pairing] = this.pairings.splice(index, 1);this.codeFailures.delete(input.source);- if (this.personal(pairing.scopes)) return { ok: false, status: 403, ...this.adminOnly! };+ if (this.personal(pairing.scopes)) return { ok: false, status: 403, code: "cloud_personal", ...this.adminOnly! };const token = `omb_sess_${randomBytes(32).toString("base64url")}`;const checkedAt = pairing.memberCheckedAt ?? now;const record: SessionRecord = {