Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(companion): accept the bridge token on the feed, reply, contacts and poll routes, scoped to its owner

nirholas513080582137
diff --git a/api/_lib/companion/caller.js b/api/_lib/companion/caller.js
new file mode 100644
index 000000000..52cf1fb0d
--- /dev/null
+++ b/api/_lib/companion/caller.js
@@ -0,0 +1,79 @@
+// Who is calling a companion route, and with which credential.
+//
+// Two kinds of credential reach /api/companion/*:
+//
+// - The bridge token (`cmp_...`), which a device holds: the desktop app, the
+// CLI, the MCP server, a browser extension, a Raspberry Pi in the hallway.
+// It is the whole of what @three-ws/companion is given, so every call that
+// package makes (list the feed, mark a delivery spoken, answer one, read the
+// contacts, check sources now) has to accept it. It resolves to exactly one
+// account, and every store query downstream is scoped to that account's
+// user id, so it reaches its owner's companion and nothing else.
+// - A session cookie, an API key, or an OAuth access token, for everything.
+// A cookie session carries every scope; a bearer needs `profile`, because
+// private messages and the bridge token itself live behind these routes.
+//
+// Routes that change what the companion is (sources, settings, contact edits,
+// rotating the token) do not take the bridge token: a leaked phone shortcut must
+// not be able to swap a Telegram bot, read a stored credential, or rotate itself
+// out from under its owner. Those answer a plain 403 that says so, instead of a
+// 401 that reads like the token is wrong.
+
+import { extractBearer, getRequestUser, requestUserHasScope } from '../auth.js';
+import { error } from '../http.js';
+import { userForIngestToken } from './store.js';
+
+const BRIDGE_TOKEN_PREFIX = 'cmp_';
+
+export function isBridgeToken(token) {
+ return typeof token === 'string' && token.startsWith(BRIDGE_TOKEN_PREFIX);
+}
+
+/**
+ * Resolve the caller, or answer the request with 401/403 and return null.
+ *
+ * @param {import('node:http').IncomingMessage} req
+ * @param {import('node:http').ServerResponse} res
+ * @param {{ bridge?: boolean }} [options] bridge: whether this route accepts the bridge token.
+ * @returns {Promise<{ id: string, via: 'bridge_token' | 'session' | 'bearer' } | null>}
+ */
+export async function companionCaller(req, res, { bridge = false } = {}) {
+ const bearer = extractBearer(req);
+ if (isBridgeToken(bearer)) {
+ if (!bridge) {
+ error(
+ res,
+ 403,
+ 'bridge_token_not_accepted',
+ 'the companion bridge token cannot change sources, settings, or contacts; sign in at three.ws/companion or use an API key with the profile scope',
+ );
+ return null;
+ }
+ const settings = await userForIngestToken(bearer);
+ if (!settings) {
+ error(res, 401, 'unauthorized', 'unknown bridge token, check three.ws/companion for the current one');
+ return null;
+ }
+ return { id: settings.user_id, via: 'bridge_token' };
+ }
+
+ const user = await getRequestUser(req, res);
+ if (!user) {
+ error(res, 401, 'unauthorized', bridge ? 'sign in, or send your companion bridge token as a Bearer header' : 'sign in required');
+ return null;
+ }
+ if (!requestUserHasScope(user, 'profile')) {
+ error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
+ return null;
+ }
+ return { id: user.id, via: user.source === 'bearer' ? 'bearer' : 'session' };
+}
+
+/**
+ * A bridge token travels in an Authorization header a browser never attaches on
+ * its own, so a request authenticated by one carries no cross-site risk and
+ * needs no CSRF token. Everything else goes through the normal check.
+ */
+export function needsCsrf(caller) {
+ return caller.via !== 'bridge_token';
+}
diff --git a/api/_lib/companion/store.js b/api/_lib/companion/store.js
index 162a3ceba..8ec5e5e58 100644
--- a/api/_lib/companion/store.js
+++ b/api/_lib/companion/store.js
@@ -10,7 +10,8 @@ import { encryptConfig, decryptConfig, redactConfig } from './crypto.js';
export const SOURCE_KINDS = ['telegram', 'calendar', 'email'];
-// A bridge token is a bearer for POST /api/companion/ingest, typed by hand into
+// A bridge token is the bearer a device holds (ingest, the delivery stream, the
+// feed, replies; see ./caller.js for exactly which routes), typed by hand into
// an iOS Shortcut or a shell script, so it is URL-safe and copy-pasteable.
export function newIngestToken() {
return `cmp_${randomBytes(24).toString('base64url')}`;
@@ -65,11 +66,16 @@ export async function rotateIngestToken(userId) {
return row.ingest_token;
}
+// The bridge token resolves to its owner the way a session does: a deleted
+// account's token stops working with the account, instead of outliving it on
+// every phone shortcut and desktop app it was pasted into.
export async function userForIngestToken(token) {
const [row] = await sql`
- select user_id, enabled, threshold, quiet_start, quiet_end, timezone,
- avatar_glb_url, voice, push_enabled
- from companion_settings where ingest_token = ${token}
+ select s.user_id, s.enabled, s.threshold, s.quiet_start, s.quiet_end, s.timezone,
+ s.avatar_glb_url, s.voice, s.push_enabled
+ from companion_settings s
+ join users u on u.id = s.user_id
+ where s.ingest_token = ${token} and u.deleted_at is null
`;
return row || null;
}
diff --git a/api/companion/checkout.js b/api/companion/checkout.js
index c465fa687..ab66f6e48 100644
--- a/api/companion/checkout.js
+++ b/api/companion/checkout.js
@@ -33,13 +33,12 @@
// }
import { z } from 'zod';
-import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
+import { cors, json, method, wrap, readJson, rateLimited } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
-import { getRequestUser, requestUserHasScope } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
import { loadUserProviderKeys } from '../_lib/provider-keys.js';
-import { userForIngestToken } from '../_lib/companion/store.js';
+import { companionCaller } from '../_lib/companion/caller.js';
import { analyzeCheckout } from '../_lib/companion/checkout.js';
import { llmComplete, llmConfigured } from '../_lib/llm.js';
@@ -87,23 +86,6 @@ async function anthropicKeyFor(userId) {
}
}
-/**
- * Resolve the caller from a session or the companion bridge token.
- * Returns the user row, or null when neither credential is present or valid.
- */
-async function callerFor(req, res) {
- const auth = req.headers.authorization || '';
- const bearer = auth.startsWith('Bearer ') ? auth.slice(7).trim() : null;
- if (bearer) {
- const user = await userForIngestToken(bearer);
- if (user) return user;
- }
- // A narrow bearer (an inference-only key, an avatars-only OAuth client)
- // must not spend the account's own model key; it needs profile.
- const user = await getRequestUser(req, res);
- return user && requestUserHasScope(user, 'profile') ? user : null;
-}
-
export default wrap(async function handler(req, res) {
// The extension calls from its own origin, which is not a three.ws page, so
// the browser sends `Origin: chrome-extension://<id>` and this must answer
@@ -113,10 +95,12 @@ export default wrap(async function handler(req, res) {
if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
- const user = await callerFor(req, res);
- if (!user) {
- return error(res, 401, 'unauthorized', 'sign in to three.ws or send your companion bridge token');
- }
+ // A narrow bearer (an inference-only key, an avatars-only OAuth client)
+ // must not spend the account's own model key; the shared resolver holds it
+ // to the profile scope. The bridge token resolves to its owner's user id,
+ // which is what the rate limit, the model key lookup and spend tracking key on.
+ const user = await companionCaller(req, res, { bridge: true });
+ if (!user) return;
const limit = await limits.companionCheckout(user.id);
if (!limit.success) return rateLimited(res, limit);
diff --git a/api/companion/contacts/[id].js b/api/companion/contacts/[id].js
index 2e01c5acc..898059f90 100644
--- a/api/companion/contacts/[id].js
+++ b/api/companion/contacts/[id].js
@@ -1,21 +1,18 @@
// DELETE /api/companion/contacts/:id → forget a contact. Messages already
// stored keep their text; they simply stop being attributed to that person.
-import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
import { deleteContact } from '../../_lib/companion/store.js';
+import { companionCaller } from '../../_lib/companion/caller.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
if (!method(req, res, ['DELETE'])) return;
- const user = await getRequestUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- // Private messages and the bridge token live behind this surface, so a
- // bearer needs the account-level profile scope, not just any grant.
- if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
+ const user = await companionCaller(req, res);
+ if (!user) return;
if (!(await requireCsrf(req, res, user.id))) return;
const rl = await limits.companionWrite(user.id);
diff --git a/api/companion/contacts/index.js b/api/companion/contacts/index.js
index 2fa6a2290..38a7ecea7 100644
--- a/api/companion/contacts/index.js
+++ b/api/companion/contacts/index.js
@@ -6,12 +6,12 @@
// speaks in, and how much her messages outrank everything else.
import { z } from 'zod';
-import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
+import { cors, json, method, wrap, readJson, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { listContacts, upsertContact } from '../../_lib/companion/store.js';
+import { companionCaller } from '../../_lib/companion/caller.js';
import { TTS_VOICE_IDS } from '../../_lib/tts-voices.js';
const contactBody = z.object({
@@ -27,11 +27,11 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const user = await getRequestUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- // Private messages and the bridge token live behind this surface, so a
- // bearer needs the account-level profile scope, not just any grant.
- if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
+ // A device holding the bridge token may read the contacts (it stages each
+ // sender's body and voice from them) but not edit them: changing who gets a
+ // face and how loudly is the owner's call, made from a signed-in surface.
+ const user = await companionCaller(req, res, { bridge: req.method === 'GET' });
+ if (!user) return;
if (req.method === 'GET') {
const rl = await limits.companionRead(user.id);
diff --git a/api/companion/events/[id].js b/api/companion/events/[id].js
index 7b5e184ac..ea176aa04 100644
--- a/api/companion/events/[id].js
+++ b/api/companion/events/[id].js
@@ -4,12 +4,12 @@
// so a message spoken on a laptop is not repeated by the phone an hour later.
import { z } from 'zod';
-import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { markEvent } from '../../_lib/companion/store.js';
+import { companionCaller, needsCsrf } from '../../_lib/companion/caller.js';
const patchBody = z.object({
delivered: z.boolean().optional(),
@@ -20,12 +20,11 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'PATCH,OPTIONS', credentials: true })) return;
if (!method(req, res, ['PATCH'])) return;
- const user = await getRequestUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- // Private messages and the bridge token live behind this surface, so a
- // bearer needs the account-level profile scope, not just any grant.
- if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
- if (!(await requireCsrf(req, res, user.id))) return;
+ // The bridge token reaches this route: it is the credential the desktop app,
+ // the CLI and the MCP server hold. It resolves to its owner only.
+ const user = await companionCaller(req, res, { bridge: true });
+ if (!user) return;
+ if (needsCsrf(user) && !(await requireCsrf(req, res, user.id))) return;
const rl = await limits.companionRead(user.id);
if (!rl.success) return rateLimited(res, rl);
diff --git a/api/companion/events/[id]/reply.js b/api/companion/events/[id]/reply.js
index baa11e0cc..57d3c60ec 100644
--- a/api/companion/events/[id]/reply.js
+++ b/api/companion/events/[id]/reply.js
@@ -11,12 +11,12 @@
// are refused with a message that says which lane could not do it.
import { z } from 'zod';
-import { getRequestUser, requestUserHasScope } from '../../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../../../_lib/http.js';
import { requireCsrf } from '../../../_lib/csrf.js';
import { limits } from '../../../_lib/rate-limit.js';
import { parse } from '../../../_lib/validate.js';
import { getReplyTarget, recordReply } from '../../../_lib/companion/store.js';
+import { companionCaller, needsCsrf } from '../../../_lib/companion/caller.js';
import { laneFor } from '../../../_lib/companion/poll.js';
const replyBody = z.object({
@@ -27,12 +27,11 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const user = await getRequestUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- // Private messages and the bridge token live behind this surface, so a
- // bearer needs the account-level profile scope, not just any grant.
- if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
- if (!(await requireCsrf(req, res, user.id))) return;
+ // The bridge token reaches this route: it is the credential the desktop app,
+ // the CLI and the MCP server hold. It resolves to its owner only.
+ const user = await companionCaller(req, res, { bridge: true });
+ if (!user) return;
+ if (needsCsrf(user) && !(await requireCsrf(req, res, user.id))) return;
// A reply opens a connection to the user's own provider, so it shares the
// bucket with "check now" rather than the cheap read bucket.
diff --git a/api/companion/events/index.js b/api/companion/events/index.js
index 499eeed99..68363ad34 100644
--- a/api/companion/events/index.js
+++ b/api/companion/events/index.js
@@ -6,20 +6,19 @@
// pending=1 only what has not been delivered or dismissed
// min_importance=<0-100> floor, for the "only the loud ones" view
-import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
+import { cors, json, method, wrap, rateLimited } from '../../_lib/http.js';
import { limits } from '../../_lib/rate-limit.js';
import { listEvents, getSettings } from '../../_lib/companion/store.js';
+import { companionCaller } from '../../_lib/companion/caller.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
- const user = await getRequestUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- // Private messages and the bridge token live behind this surface, so a
- // bearer needs the account-level profile scope, not just any grant.
- if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
+ // The bridge token reaches this route: it is the credential the desktop app,
+ // the CLI and the MCP server hold. It resolves to its owner only.
+ const user = await companionCaller(req, res, { bridge: true });
+ if (!user) return;
const rl = await limits.companionRead(user.id);
if (!rl.success) return rateLimited(res, rl);
diff --git a/api/companion/poll.js b/api/companion/poll.js
index 5d878b742..d73932ced 100644
--- a/api/companion/poll.js
+++ b/api/companion/poll.js
@@ -4,11 +4,11 @@
// the button on the setup page, so a user who just connected something sees it
// work in the same breath rather than waiting for the next tick.
-import { getRequestUser, requestUserHasScope } from '../_lib/auth.js';
-import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { limits } from '../_lib/rate-limit.js';
import { pollUser } from '../_lib/companion/poll.js';
+import { companionCaller, needsCsrf } from '../_lib/companion/caller.js';
export const maxDuration = 60;
@@ -16,12 +16,11 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const user = await getRequestUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- // Private messages and the bridge token live behind this surface, so a
- // bearer needs the account-level profile scope, not just any grant.
- if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
- if (!(await requireCsrf(req, res, user.id))) return;
+ // The bridge token reaches this route: it is the credential the desktop app,
+ // the CLI and the MCP server hold. It resolves to its owner only.
+ const user = await companionCaller(req, res, { bridge: true });
+ if (!user) return;
+ if (needsCsrf(user) && !(await requireCsrf(req, res, user.id))) return;
const rl = await limits.companionPoll(user.id);
if (!rl.success) return rateLimited(res, rl);
diff --git a/api/companion/settings.js b/api/companion/settings.js
index 00f340120..34641a61d 100644
--- a/api/companion/settings.js
+++ b/api/companion/settings.js
@@ -6,12 +6,12 @@
// or a Mac script posts with, so the setup page has to be able to show it.
import { z } from 'zod';
-import { getRequestUser, requestUserHasScope } from '../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { limits } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
import { getSettings, updateSettings, rotateIngestToken } from '../_lib/companion/store.js';
+import { companionCaller } from '../_lib/companion/caller.js';
import { TTS_VOICE_IDS } from '../_lib/tts-voices.js';
const patchBody = z.object({
@@ -64,11 +64,8 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,PATCH,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'PATCH', 'POST'])) return;
- const user = await getRequestUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- // Private messages and the bridge token live behind this surface, so a
- // bearer needs the account-level profile scope, not just any grant.
- if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
+ const user = await companionCaller(req, res);
+ if (!user) return;
if (req.method === 'GET') {
const rl = await limits.companionRead(user.id);
diff --git a/api/companion/sources/[id].js b/api/companion/sources/[id].js
index 93cd45fa9..6deff6af4 100644
--- a/api/companion/sources/[id].js
+++ b/api/companion/sources/[id].js
@@ -3,12 +3,12 @@
// POST /api/companion/sources/:id → poll it right now ("check now").
import { z } from 'zod';
-import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { getSource, updateSource, deleteSource } from '../../_lib/companion/store.js';
+import { companionCaller } from '../../_lib/companion/caller.js';
import { pollSource } from '../../_lib/companion/poll.js';
const patchBody = z.object({
@@ -20,11 +20,8 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'PATCH,DELETE,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['PATCH', 'DELETE', 'POST'])) return;
- const user = await getRequestUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- // Private messages and the bridge token live behind this surface, so a
- // bearer needs the account-level profile scope, not just any grant.
- if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
+ const user = await companionCaller(req, res);
+ if (!user) return;
if (!(await requireCsrf(req, res, user.id))) return;
const id = String(req.query?.id || '').trim();
diff --git a/api/companion/sources/index.js b/api/companion/sources/index.js
index e7eb03ec7..30a76faad 100644
--- a/api/companion/sources/index.js
+++ b/api/companion/sources/index.js
@@ -7,12 +7,12 @@
// cron run three minutes later.
import { z } from 'zod';
-import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { listSources, createSource } from '../../_lib/companion/store.js';
+import { companionCaller } from '../../_lib/companion/caller.js';
import { laneFor } from '../../_lib/companion/poll.js';
import { normalizeIcsUrl } from '../../_lib/companion/lanes/calendar.js';
import { SsrfError } from '../../_lib/ssrf.js';
@@ -71,11 +71,8 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const user = await getRequestUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- // Private messages and the bridge token live behind this surface, so a
- // bearer needs the account-level profile scope, not just any grant.
- if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
+ const user = await companionCaller(req, res);
+ if (!user) return;
if (req.method === 'GET') {
const rl = await limits.companionRead(user.id);
diff --git a/data/changelog.json b/data/changelog.json
index 91bbc4502..615100c48 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -29148,6 +29148,15 @@
"summary": "Text to 3D first paints a concept image, then sculpts it. When the painting service quietly returned a blank black frame instead of a picture, the studio used it anyway, and every 3D engine then failed because there was nothing in the image to sculpt. The studio now spots a blank or withheld frame and paints the concept with the next image service instead, so those prompts finish as real models.",
"tags": ["fix"],
"link": "/forge"
+ },
+ {
+ "date": "2026-10-09",
+ "title": "The desktop companion, CLI and MCP server now work with just the bridge token",
+ "summary": "The companion bridge token is the one credential the desktop app, the companion command line and its MCP server are given, but the feed, marking a message as spoken, replying, reading contacts and checking sources all refused it, so pasting the token into the desktop app said it was wrong and an agent asking what you had heard got turned away. Those calls now accept the bridge token and only ever show the messages and contacts of the person it belongs to. It still cannot connect sources, edit contacts, change settings or rotate itself; those stay behind your signed-in account, and they now say so plainly instead of answering as if the token were wrong.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/companion"
}
]
}
diff --git a/docs/companion.md b/docs/companion.md
index 3ef9b63c0..c081f850b 100644
--- a/docs/companion.md
+++ b/docs/companion.md
@@ -287,21 +287,42 @@ did not matter.
## The API
-Everything the page does, you can do. Session cookie or bridge token.
-
-| Endpoint | Method | What it does |
-|---|---|---|
-| `/api/companion/ingest` | POST | Hand it a message (bridge token). Returns the triage verdict. |
-| `/api/companion/stream` | GET | Live deliveries as Server-Sent Events. |
-| `/api/companion/events` | GET | The feed, with scores and reasons. |
-| `/api/companion/events/:id` | PATCH | Mark delivered or dismissed. |
-| `/api/companion/events/:id/reply` | POST | Answer through the connection it arrived on. |
-| `/api/companion/sources` | GET, POST | List or connect a source (verified before saving). |
-| `/api/companion/sources/:id` | PATCH, DELETE, POST | Rename, pause, disconnect, or check now. |
-| `/api/companion/contacts` | GET, POST | The people who get a face. |
-| `/api/companion/contacts/:id` | DELETE | Forget one. |
-| `/api/companion/settings` | GET, PATCH, POST | Threshold, quiet hours, default body and voice; POST rotates the bridge token. |
-| `/api/companion/poll` | POST | Poll every connected source now. |
+Everything the page does, you can do. Two kinds of credential reach it:
+
+- **The bridge token** (`cmp_…`) is what a device holds: the desktop app, the
+ CLI, the MCP server, a phone shortcut, the
+ [checkout companion](checkout-companion.md) extension. It reaches everything
+ a body needs to do its job: post a message (`ingest`), watch deliveries
+ (`stream`), read the feed, mark a delivery spoken or dismissed, answer one,
+ read the contacts it stages senders with, check sources now, and the
+ extension's `checkout` call. It resolves to exactly one account, so it only
+ ever sees that account's messages. It cannot change what the companion is: a
+ leaked phone shortcut cannot connect or remove sources, edit or forget
+ contacts, change settings, or read or rotate the token itself. Those routes
+ answer `403 bridge_token_not_accepted`. A bridge-token request carries no
+ cookie, so it needs no CSRF token.
+- **A session cookie, an API key, or an OAuth access token** reaches every route
+ except `ingest` (bridge token only); `stream` takes a session cookie but not an
+ API key or OAuth token. A cookie session carries every scope; an API key
+ or OAuth token must have been granted the `profile` scope, because private
+ messages and the bridge token live behind these routes. A narrower token (an
+ `inference`-only key, an `avatars:read` MCP client) gets
+ `403 insufficient_scope`.
+
+| Endpoint | Method | Bridge token | What it does |
+|---|---|---|---|
+| `/api/companion/ingest` | POST | yes (only) | Hand it a message. Returns the triage verdict. |
+| `/api/companion/stream` | GET | yes | Live deliveries as Server-Sent Events (bridge token or session cookie). |
+| `/api/companion/events` | GET | yes | The feed, with scores and reasons. |
+| `/api/companion/events/:id` | PATCH | yes | Mark delivered or dismissed. |
+| `/api/companion/events/:id/reply` | POST | yes | Answer through the connection it arrived on. |
+| `/api/companion/contacts` | GET, POST | GET only | The people who get a face. |
+| `/api/companion/contacts/:id` | DELETE | no | Forget one. |
+| `/api/companion/poll` | POST | yes | Poll every connected source now. |
+| `/api/companion/checkout` | POST | yes | Read a payment screen ([checkout companion](checkout-companion.md)). |
+| `/api/companion/sources` | GET, POST | no | List or connect a source (verified before saving). |
+| `/api/companion/sources/:id` | PATCH, DELETE, POST | no | Rename, pause, disconnect, or check now. |
+| `/api/companion/settings` | GET, PATCH, POST | no | Threshold, quiet hours, default body and voice; POST rotates the bridge token. |
A delivery on the stream carries everything a body needs to perform it:
diff --git a/packages/companion-sdk/README.md b/packages/companion-sdk/README.md
index 073c13dad..8949a8d26 100644
--- a/packages/companion-sdk/README.md
+++ b/packages/companion-sdk/README.md
@@ -243,6 +243,15 @@ Needs `@modelcontextprotocol/sdk` installed alongside this package.
Returns `{ send, list, markDelivered, dismiss, reply, contacts, checkNow, stream }`.
Every method rejects with a `CompanionError` carrying `.status` and `.code`.
+Every one of these works with the bridge token alone. The token resolves to the
+one person it belongs to, so `list`, `reply`, and `contacts` only ever see that
+person's messages and contacts. It deliberately cannot change what the companion
+is: connecting sources, editing contacts, changing settings, and rotating the
+token itself need a signed-in session at
+[three.ws/companion](https://three.ws/companion), and the API answers a bridge
+token there with `403` and the code `bridge_token_not_accepted`. A token that
+was rotated away fails with `401` and the code `unauthorized`.
+
### `createCompanionStage(options)`
| Option | Default | Meaning |
diff --git a/packages/companion-sdk/src/client.js b/packages/companion-sdk/src/client.js
index 967012955..1cf2bab1f 100644
--- a/packages/companion-sdk/src/client.js
+++ b/packages/companion-sdk/src/client.js
@@ -16,9 +16,10 @@
* onDelivery: (d) => console.log(`${d.speaker}: ${d.spoken_line}`),
* });
*
- * The token is the bridge token from three.ws/companion. It can post messages
- * and receive that user's deliveries, and rotating it on that page revokes
- * every device at once. A browser page that already has a signed-in session can
+ * The token is the bridge token from three.ws/companion. It can post messages,
+ * receive that user's deliveries, read the feed and the contacts, mark or answer
+ * a delivery, and check sources now, all scoped to the one user it belongs to.
+ * Rotating it on that page revokes every device at once. A browser page that already has a signed-in session can
* omit it entirely and pass `credentials: 'include'` behaviour by default.
*/
diff --git a/tests/api/authz-hardening-2026-10.test.js b/tests/api/authz-hardening-2026-10.test.js
index afa55f7c7..43bb238e7 100644
--- a/tests/api/authz-hardening-2026-10.test.js
+++ b/tests/api/authz-hardening-2026-10.test.js
@@ -196,6 +196,9 @@ describe('bearer scope on the knock door and the chat gateway', () => {
});
it('every companion account route checks the profile scope', () => {
+ // The routes resolve their caller through one shared resolver, which holds
+ // API keys and OAuth tokens to profile and the bridge token to its owner.
+ expect(src('api/_lib/companion/caller.js')).toMatch(/requestUserHasScope\(user, 'profile'\)/);
for (const rel of [
'api/companion/settings.js',
'api/companion/poll.js',
@@ -208,7 +211,7 @@ describe('bearer scope on the knock door and the chat gateway', () => {
'api/companion/contacts/[id].js',
'api/companion/checkout.js',
]) {
- expect(src(rel), rel).toMatch(/requestUserHasScope\(user, 'profile'\)/);
+ expect(src(rel), rel).toMatch(/await companionCaller\(req, res/);
}
});
});
diff --git a/tests/companion-bridge-auth.test.js b/tests/companion-bridge-auth.test.js
new file mode 100644
index 000000000..c67c52a50
--- /dev/null
+++ b/tests/companion-bridge-auth.test.js
@@ -0,0 +1,413 @@
+// The companion bridge token is the credential a device holds. The desktop app,
+// the CLI (`companion login`, `list`, `check`, `doctor`), the MCP server's
+// `list_deliveries` tool and the stage all hand @three-ws/companion nothing but
+// that token, so every route the SDK calls has to accept it, and each one must
+// resolve it to exactly its owner: never to another account's feed, contacts,
+// or messages. The routes that change what the companion is (contact edits,
+// settings, sources) refuse it with a 403 that says so.
+//
+// The store is replaced by an in-memory one with the same user-scoped contract
+// as api/_lib/companion/store.js (every lookup takes the caller's user id and
+// misses on a row another account owns), so these tests exercise the real
+// handlers, the real caller resolver, and the real SDK client end to end.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const ALICE = 'aaaaaaaa-0000-4000-8000-000000000001';
+const BOB = 'bbbbbbbb-0000-4000-8000-000000000002';
+const ALICE_TOKEN = 'cmp_alice_bridge_token_0123456789abcdef';
+const BOB_TOKEN = 'cmp_bob_bridge_token_0123456789abcdefgh';
+const ALICE_EVENT = 'a1a1a1a1-1111-4111-8111-111111111111';
+const BOB_EVENT = 'b2b2b2b2-2222-4222-8222-222222222222';
+
+const state = {
+ session: null,
+ csrfCalls: [],
+ rateKeys: [],
+ marked: [],
+ replies: [],
+ polled: [],
+ upserts: [],
+};
+
+function freshDb() {
+ return {
+ settings: {
+ [ALICE]: { user_id: ALICE, ingest_token: ALICE_TOKEN, threshold: 60, enabled: true },
+ [BOB]: { user_id: BOB, ingest_token: BOB_TOKEN, threshold: 40, enabled: true },
+ },
+ events: [
+ { id: ALICE_EVENT, user_id: ALICE, source_kind: 'telegram', title: 'Sarah: at the door', importance: 88, reply_to: { chat_id: 1, message_id: 7 } },
+ { id: BOB_EVENT, user_id: BOB, source_kind: 'telegram', title: 'Bob private message', importance: 91, reply_to: { chat_id: 2, message_id: 9 } },
+ ],
+ contacts: [
+ { id: 'c-alice', user_id: ALICE, identifier: 'sarah', display_name: 'Sarah' },
+ { id: 'c-bob', user_id: BOB, identifier: 'carol', display_name: 'Carol' },
+ ],
+ };
+}
+let db = freshDb();
+
+// What the real queries select: the owner id and the reply routing stay server side.
+function strip(row) {
+ const out = { ...row };
+ delete out.user_id;
+ delete out.reply_to;
+ return out;
+}
+
+vi.mock('../api/_lib/auth.js', () => ({
+ extractBearer(req) {
+ const h = req.headers.authorization || '';
+ if (!h.toLowerCase().startsWith('bearer ')) return null;
+ return h.slice(7).trim();
+ },
+ getRequestUser: vi.fn(async () => state.session),
+ requestUserHasScope(user, required) {
+ if (!user) return false;
+ if (user.source !== 'bearer') return true;
+ return String(user.scope || '').split(/\s+/).includes(required);
+ },
+}));
+
+vi.mock('../api/_lib/companion/store.js', () => ({
+ userForIngestToken: vi.fn(async (token) => {
+ const row = Object.values(db.settings).find((s) => s.ingest_token === token);
+ return row ? { ...row } : null;
+ }),
+ getSettings: vi.fn(async (userId) => db.settings[userId]),
+ updateSettings: vi.fn(),
+ rotateIngestToken: vi.fn(),
+ listEvents: vi.fn(async (userId) => db.events.filter((e) => e.user_id === userId).map(strip)),
+ markEvent: vi.fn(async (userId, id, flags) => {
+ const row = db.events.find((e) => e.id === id && e.user_id === userId);
+ if (!row) return null;
+ state.marked.push({ userId, id, flags });
+ return { id, delivered_at: flags.delivered ? '2026-10-09T00:00:00.000Z' : null, dismissed_at: null };
+ }),
+ getReplyTarget: vi.fn(async (userId, id) => {
+ const row = db.events.find((e) => e.id === id && e.user_id === userId);
+ if (!row) return null;
+ return { ...row, source_kind_actual: 'telegram', config: { bot_token: `bot-of-${userId}` }, sender: 'Sarah' };
+ }),
+ recordReply: vi.fn(async (userId, id, text) => ({ id, replied_at: '2026-10-09T00:00:00.000Z', reply_text: text })),
+ listContacts: vi.fn(async (userId) => db.contacts.filter((c) => c.user_id === userId).map(strip)),
+ upsertContact: vi.fn(async (userId, contact) => {
+ state.upserts.push({ userId, contact });
+ return { id: 'c-new', ...contact };
+ }),
+}));
+
+vi.mock('../api/_lib/companion/poll.js', () => ({
+ pollUser: vi.fn(async (userId) => {
+ state.polled.push(userId);
+ return { sources: [{ kind: 'telegram', label: `bot of ${userId}`, ok: true, ingested: 0 }] };
+ }),
+ laneFor: () => ({
+ reply: async (config, replyTo, text) => {
+ state.replies.push({ config, replyTo, text });
+ return { chat: 'Sarah' };
+ },
+ }),
+}));
+
+vi.mock('../api/_lib/csrf.js', () => ({
+ requireCsrf: vi.fn(async (_req, _res, userId) => {
+ state.csrfCalls.push(userId);
+ return true;
+ }),
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: new Proxy({}, {
+ get: (_target, bucket) => async (key) => {
+ state.rateKeys.push({ bucket, key });
+ return { success: true };
+ },
+ }),
+}));
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => []),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: async () => ({ pressured: false }),
+}));
+
+vi.mock('../api/_lib/llm.js', () => ({
+ llmConfigured: () => false,
+ llmComplete: vi.fn(),
+}));
+
+const { default: eventsHandler } = await import('../api/companion/events/index.js');
+const { default: eventHandler } = await import('../api/companion/events/[id].js');
+const { default: replyHandler } = await import('../api/companion/events/[id]/reply.js');
+const { default: contactsHandler } = await import('../api/companion/contacts/index.js');
+const { default: pollHandler } = await import('../api/companion/poll.js');
+const { default: settingsHandler } = await import('../api/companion/settings.js');
+const { default: checkoutHandler } = await import('../api/companion/checkout.js');
+const { createCompanionClient, CompanionError } = await import('../packages/companion-sdk/src/client.js');
+
+function makeReq({ method = 'GET', url, token = null, headers = {}, body = null, query = {} }) {
+ const req = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
+ req.method = method;
+ req.url = url;
+ req.query = query;
+ req.headers = {
+ host: 'three.ws',
+ ...(body ? { 'content-type': 'application/json' } : {}),
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
+ ...headers,
+ };
+ return req;
+}
+
+function makeRes() {
+ const headers = {};
+ return {
+ statusCode: 200,
+ body: '',
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) {
+ headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(handler, opts) {
+ const res = makeRes();
+ await handler(makeReq(opts), res);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+// Routes the SDK's fetch straight into the handlers, so the client is tested
+// against the real server code rather than a canned response.
+const ROUTES = [
+ [/^\/api\/companion\/events$/, eventsHandler],
+ [/^\/api\/companion\/events\/([^/]+)\/reply$/, replyHandler],
+ [/^\/api\/companion\/events\/([^/]+)$/, eventHandler],
+ [/^\/api\/companion\/contacts$/, contactsHandler],
+ [/^\/api\/companion\/poll$/, pollHandler],
+];
+
+async function inProcessFetch(href, init = {}) {
+ const url = new URL(href);
+ const match = ROUTES.map(([re, handler]) => [url.pathname.match(re), handler]).find(([m]) => m);
+ if (!match) throw new Error(`no route for ${url.pathname}`);
+ const [m, handler] = match;
+ const res = makeRes();
+ const req = makeReq({
+ method: init.method || 'GET',
+ url: `${url.pathname}${url.search}`,
+ headers: init.headers || {},
+ body: init.body ? JSON.parse(init.body) : null,
+ query: m[1] ? { id: decodeURIComponent(m[1]) } : {},
+ });
+ await handler(req, res);
+ return { ok: res.statusCode >= 200 && res.statusCode < 300, status: res.statusCode, text: async () => res.body };
+}
+
+beforeEach(() => {
+ db = freshDb();
+ state.session = null;
+ state.csrfCalls = [];
+ state.rateKeys = [];
+ state.marked = [];
+ state.replies = [];
+ state.polled = [];
+ state.upserts = [];
+});
+
+describe('GET /api/companion/events with the bridge token', () => {
+ it('lists only the token owner\'s deliveries', async () => {
+ const { status, body } = await invoke(eventsHandler, { url: '/api/companion/events?limit=10', token: ALICE_TOKEN });
+ expect(status).toBe(200);
+ expect(body.events.map((e) => e.id)).toEqual([ALICE_EVENT]);
+ expect(body.threshold).toBe(60);
+ expect(state.rateKeys).toContainEqual({ bucket: 'companionRead', key: ALICE });
+ });
+
+ it('gives another account\'s token that account\'s feed, never alice\'s', async () => {
+ const { body } = await invoke(eventsHandler, { url: '/api/companion/events', token: BOB_TOKEN });
+ expect(body.events.map((e) => e.id)).toEqual([BOB_EVENT]);
+ });
+
+ it('refuses an unknown bridge token with 401, even next to a live session', async () => {
+ state.session = { id: ALICE };
+ const { status, body } = await invoke(eventsHandler, { url: '/api/companion/events', token: 'cmp_revoked_token_value' });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+});
+
+describe('PATCH /api/companion/events/:id with the bridge token', () => {
+ it('marks the owner\'s delivery spoken without a CSRF token', async () => {
+ const { status, body } = await invoke(eventHandler, {
+ method: 'PATCH',
+ url: `/api/companion/events/${ALICE_EVENT}`,
+ query: { id: ALICE_EVENT },
+ token: ALICE_TOKEN,
+ body: { delivered: true },
+ });
+ expect(status).toBe(200);
+ expect(body.event.id).toBe(ALICE_EVENT);
+ expect(state.marked).toEqual([{ userId: ALICE, id: ALICE_EVENT, flags: { delivered: true, dismissed: false } }]);
+ expect(state.csrfCalls).toEqual([]);
+ });
+
+ it('cannot touch another account\'s delivery', async () => {
+ const { status } = await invoke(eventHandler, {
+ method: 'PATCH',
+ url: `/api/companion/events/${BOB_EVENT}`,
+ query: { id: BOB_EVENT },
+ token: ALICE_TOKEN,
+ body: { dismissed: true },
+ });
+ expect(status).toBe(404);
+ expect(state.marked).toEqual([]);
+ });
+});
+
+describe('POST /api/companion/events/:id/reply with the bridge token', () => {
+ it('answers the owner\'s message through the owner\'s own lane', async () => {
+ const { status, body } = await invoke(replyHandler, {
+ method: 'POST',
+ url: `/api/companion/events/${ALICE_EVENT}/reply`,
+ query: { id: ALICE_EVENT },
+ token: ALICE_TOKEN,
+ body: { text: 'on my way down' },
+ });
+ expect(status).toBe(200);
+ expect(body.sent).toBe(true);
+ expect(state.replies).toEqual([{ config: { bot_token: `bot-of-${ALICE}` }, replyTo: { chat_id: 1, message_id: 7 }, text: 'on my way down' }]);
+ expect(state.csrfCalls).toEqual([]);
+ });
+
+ it('cannot answer another account\'s message', async () => {
+ const { status } = await invoke(replyHandler, {
+ method: 'POST',
+ url: `/api/companion/events/${BOB_EVENT}/reply`,
+ query: { id: BOB_EVENT },
+ token: ALICE_TOKEN,
+ body: { text: 'hijack' },
+ });
+ expect(status).toBe(404);
+ expect(state.replies).toEqual([]);
+ });
+});
+
+describe('/api/companion/contacts with the bridge token', () => {
+ it('reads only the owner\'s contacts', async () => {
+ const { status, body } = await invoke(contactsHandler, { url: '/api/companion/contacts', token: ALICE_TOKEN });
+ expect(status).toBe(200);
+ expect(body.contacts.map((c) => c.display_name)).toEqual(['Sarah']);
+ });
+
+ it('cannot edit contacts', async () => {
+ const { status, body } = await invoke(contactsHandler, {
+ method: 'POST',
+ url: '/api/companion/contacts',
+ token: ALICE_TOKEN,
+ body: { identifier: 'mallory', display_name: 'Mallory' },
+ });
+ expect(status).toBe(403);
+ expect(body.error).toBe('bridge_token_not_accepted');
+ expect(state.upserts).toEqual([]);
+ });
+});
+
+describe('POST /api/companion/poll with the bridge token', () => {
+ it('checks only the owner\'s sources, without a CSRF token', async () => {
+ const { status, body } = await invoke(pollHandler, { method: 'POST', url: '/api/companion/poll', token: BOB_TOKEN });
+ expect(status).toBe(200);
+ expect(state.polled).toEqual([BOB]);
+ expect(body.sources[0].label).toBe(`bot of ${BOB}`);
+ expect(state.csrfCalls).toEqual([]);
+ });
+});
+
+describe('routes the bridge token does not reach', () => {
+ it('settings answers 403 bridge_token_not_accepted, so the token cannot read or rotate itself', async () => {
+ const { status, body } = await invoke(settingsHandler, { url: '/api/companion/settings', token: ALICE_TOKEN });
+ expect(status).toBe(403);
+ expect(body.error).toBe('bridge_token_not_accepted');
+ });
+});
+
+describe('session and API-key callers keep their rules', () => {
+ it('a session still reads its own feed and still passes CSRF on a write', async () => {
+ state.session = { id: ALICE };
+ const list = await invoke(eventsHandler, { url: '/api/companion/events' });
+ expect(list.body.events.map((e) => e.id)).toEqual([ALICE_EVENT]);
+
+ await invoke(eventHandler, {
+ method: 'PATCH',
+ url: `/api/companion/events/${ALICE_EVENT}`,
+ query: { id: ALICE_EVENT },
+ body: { delivered: true },
+ });
+ expect(state.csrfCalls).toEqual([ALICE]);
+ });
+
+ it('an API key without the profile scope is refused with 403 insufficient_scope', async () => {
+ state.session = { id: ALICE, source: 'bearer', scope: 'inference' };
+ const { status, body } = await invoke(eventsHandler, { url: '/api/companion/events', token: 'sk_live_narrow' });
+ expect(status).toBe(403);
+ expect(body.error).toBe('insufficient_scope');
+ });
+
+ it('no credential at all is a 401', async () => {
+ const { status } = await invoke(pollHandler, { method: 'POST', url: '/api/companion/poll' });
+ expect(status).toBe(401);
+ });
+});
+
+describe('POST /api/companion/checkout with the bridge token', () => {
+ it('keys the rate limit and the model-key lookup on the owner\'s user id', async () => {
+ const { status } = await invoke(checkoutHandler, {
+ method: 'POST',
+ url: '/api/companion/checkout',
+ token: ALICE_TOKEN,
+ body: { url: 'https://shop.example/checkout', text: 'Total $49.99', amounts: [{ value: 4999, role: 'total' }] },
+ });
+ expect(status).toBe(200);
+ expect(state.rateKeys).toContainEqual({ bucket: 'companionCheckout', key: ALICE });
+ });
+});
+
+describe('@three-ws/companion given only a bridge token', () => {
+ const client = (token) => createCompanionClient({ token, apiBase: 'https://three.ws', fetch: inProcessFetch });
+
+ it('list, markDelivered, reply, contacts and checkNow all succeed for the owner', async () => {
+ const companion = client(ALICE_TOKEN);
+ const feed = await companion.list({ limit: 1 });
+ expect(feed.events.map((e) => e.id)).toEqual([ALICE_EVENT]);
+ await expect(companion.markDelivered(ALICE_EVENT)).resolves.toMatchObject({ event: { id: ALICE_EVENT } });
+ await expect(companion.reply(ALICE_EVENT, 'on my way')).resolves.toMatchObject({ sent: true });
+ await expect(companion.contacts()).resolves.toMatchObject({ contacts: [{ display_name: 'Sarah' }] });
+ await expect(companion.checkNow()).resolves.toMatchObject({ sources: [{ ok: true }] });
+ expect(state.polled).toEqual([ALICE]);
+ });
+
+ it('cannot reach another account\'s delivery through the SDK either', async () => {
+ const err = await client(ALICE_TOKEN).reply(BOB_EVENT, 'hijack').catch((e) => e);
+ expect(err).toBeInstanceOf(CompanionError);
+ expect(err.status).toBe(404);
+ expect(state.replies).toEqual([]);
+ });
+
+ it('a rotated token fails with a message that says where to get the new one', async () => {
+ const err = await client('cmp_rotated_away_token').list().catch((e) => e);
+ expect(err.status).toBe(401);
+ expect(err.message).toMatch(/three\.ws\/companion/);
+ });
+});