Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(grants): warn when one unscoped token serves several people

garrytanf60a3ad6aa64
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8cadb056cf..30d04724f8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**An install that hands one unscoped credential to an agent several people talk to now says so, loudly, and doctor reports it.** In the HARN-13 host-harness pilot, one bot token over a brain that held many channels' chat made agents answer people with other people's messages: telling the agent gbrain was live cost 9 to 21 points of pass rate, and every added cross-scope failure cited a channel page the bot grant returned. Until per-member keys arrive (gbrain#7812), gbrain cannot tell those people apart, so it warns.
+
+The `unscoped_multi_user_token` safety notice fires from `gbrain setup openclaw|hermes|grok-bot|muse`, from `setup claude-code` when a chat-channel plugin is enabled, from `mcp grant` and `connect` for a bot harness or a grant that reads chat from 2+ channels, from `skillpack scaffold` into an OpenClaw or Hermes workspace, and from `auth create` and `auth register-client` when the new credential reads chat from 2+ channels. It names the fixes that exist today (a one-source grant, `sources unfederate`, `GBRAIN_SOURCE` for a stdio agent, `visibility: private`, `source_ids` or `--source`), and says plainly when the chat sits in one source and no source grant can separate it. The new read-only doctor check `unscoped_multi_user_token` runs the same detection over every active token, OAuth client and wired local agent. No grant, default or scoping behaviour changes, and no exit code moves.
+
+### Itemized changes
+
+- `src/core/grants/shared-exposure.ts` (new): the detection (bot harnesses, Claude Code channel plugins, the chat-channel census over a credential's or stdio server's read set), the notice and its fix.
+- `src/commands/doctor/checks/unscoped-multi-user-token.ts` (new), registered in the doctor registry and categories; doctor goldens regenerated for the new check.
+- The install routes: `src/commands/setup.ts`, `mcp.ts`, `harness-connect.ts`, `skillpack/scaffold.ts`, `auth.ts`. Warnings go to stderr and into `notices` or `warnings` of a `--json` result.
+- `src/core/error-registry.ts`: the notice code. `docs/mcp/ADMIN.md#one-token-several-people`, `skills/mcp-access/SKILL.md`.
+- Tests: `test/shared-exposure.test.ts`, `test/shared-exposure-routes.test.ts` (PGLite brains with no repository).
+
## [0.60.620.0] - 2026-11-09
**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index eb1e400d51..e3004abfbe 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -9,6 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, unlimited delegated spend, and an operator-set `full` surface for every profile except `delegating-agent` (`starter`); only an explicit profile application changes an existing client's surface. `catalogProvenance()` is the operation catalog a snapshot is written against: `service.ts` adds it as `catalogProvenance` to the audit document of every write that sets a new snapshot (registration included), and `readClientCatalogProvenance` returns it only while that audit row's snapshot is still the client's snapshot (null for grants written without it; never synthesized). `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`; an unconverted `source_grant IS NULL` row reads as the conversion `migrateLegacyTokens` would write, and a malformed `permissions` value denies every axis), `GRANT_MIRROR_WINDOW_ENDS` (the date until which the `permissions` mirror is written and drift is enforced; doctor reports it), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens and clients may hold `none`); `ClientGrant.sourcesNone` (`oauth_clients.source_grant = 'none'`: NULL `source_id`, empty `federated_read`, verified as `NO_SOURCES`) and `ClientGrant.takesHolders` (`oauth_clients.takes_holders`, NULL = `['world']`; read by `verifyAccessToken` and `authorizeTakeHolder`), both added by migration v203 (fragment `oauth-client-axes-schema.ts`) and set through `auth rescope --client --sources none|--takes-holders` and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`); v202 (`legacy_token_grant_conversion`) converts every legacy grant in bulk. Tests: `test/legacy-token-grant-conversion.test.ts`. `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy` and schema migration v202) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveTokenGrant` is the HTTP auth read (both transports): a legacy-shape row converts on that read with one `source_grant IS NULL`-guarded UPDATE (concurrent first reads convert once; a failed write such as a read-only role authorizes with the identical in-memory conversion); `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit). GBRA-156 private-pages axis: `PrivatePagesGrant` (`none` | `granted_sources`) lives in `access_tokens.private_pages` and `oauth_clients.private_pages` (migration v280, never in the legacy permissions mirror); `privatePagesSources` counts only explicitly named sources (scalar write source, federated write plus read sources; never the `default` floor), and `privatePagesAuth` builds `AuthInfo.privatePages` for HTTP and OAuth verification; MCP dispatch runs a remote read under `withPrivateReadableSources` (`src/core/search/private-visibility.ts`, an AsyncLocalStorage), whose `*ForCaller` predicate twins and `orPrivateReadableSource` OR those sources in at read sites only, never at stored-visibility decisions.
+- `src/core/grants/shared-exposure.ts` + `src/commands/doctor/checks/unscoped-multi-user-token.ts` — GST-363 warning when one credential with no per-person scope serves an agent several people use. Signals: a bot harness (`BOT_HARNESSES`), a Claude Code chat-channel plugin (settings.json `enabledPlugins`), or chat pages from 2+ channels in the read set (`chatChannelCensus`: chat types incl. `pageTypesForAllowed` slack/iMessage aliases; channel = frontmatter channel/chat/conversation, else a `#name` title, else the source; each DM page alone; private pages hidden unless the remote-private hatch is on). `credentialReadSources` mirrors dispatch: an unscoped legacy token reads default plus federated sources, an unscoped OAuth client `default`, scalar and federated grants what they name; `stdioReadSources` resolves like the stdio server. `sharedTokenNotice` builds the `unscoped_multi_user_token` safety notice (fixes chosen by whether the chat spans 2+ sources; per-member keys named as gbrain#7812); `writeExposureNotice` prints it on stderr. Routes: setup (bot harnesses, claude-code channel plugin), mcp grant, connect, skillpack scaffold, auth create, auth register-client; none changes a grant or an exit code. The doctor check warns on credentials or wired local agents with multi-channel chat in reach, reports a bot harness alone as info, and gives a remote caller a count only. Tests: `test/shared-exposure.test.ts`, `test/shared-exposure-routes.test.ts` (repo-less PGLite).
- `src/core/grants/lifecycle.ts` + `src/commands/serve-http-clients.ts` — owner-authenticated client inspection, setup, export and lifecycle endpoints. Token invalidation/revoke/delete lock the OAuth client row, require reviewed revisions and explicit application, and commit an audit record atomically. Deletion records a tombstone while preserving request history and spending reservations/settlement; missing clients become terminal delegated denials while transient lookup failures remain retryable.
- `src/commands/serve-http-api-keys.ts` — owner-dashboard legacy API keys (`/admin/api/api-keys`). Mint validates the request (`parseApiKeyMintRequest`: name 1-128 printable characters, registered scopes, active source ids, holder grammar) and goes through `mintLegacyToken`, so keys are born on the unified grant columns; omitted fields take the `gbrain auth create` defaults (scopes `read,write`, never `admin` unless listed; no source grant; holders `['world']`), reported in `defaults_applied` beside the effective grant. Refusals are `invalid_params` agent envelopes with `why` and a `fix`; nothing is minted. The token appears only in the mint response, never in logs or SSE. The list returns ids, scopes, sources and holders through `grantFromTokenRow`; revoke takes the row id (`revokeLegacyTokenById`) and refuses a name. Pinned by `test/serve-http-api-keys.test.ts`.
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index 664f96c23f..b7b121b533 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -375,6 +375,60 @@ range and every grant change is refused until it is fixed. Add the
example `gbrain auth rescope-client CLIENT_ID --token-ttl 7776000 --dry-run --json`,
then apply the same flags without `--dry-run`.
+## One token, several people
+
+A credential has no per-person scope until per-member keys arrive
+(gbrain#7812). An agent that several people talk to (a Slack, Telegram or
+Discord bot, a shared OpenClaw or Hermes, Claude Code with a chat-channel
+plugin) reads everything its one grant reaches, so it can answer one person
+with pages only another person may read. In a measured multi-user pilot with
+one unscoped bot token, telling the agent that gbrain was live lowered pass
+rates by 9 to 21 points, and every added cross-scope failure cited a channel
+page the bot grant returned.
+
+gbrain warns with `unscoped_multi_user_token` (a safety notice) when an
+install route sets up such access:
+
+| Route | Warns when |
+|---|---|
+| `gbrain setup openclaw`, `setup hermes`, `setup grok-bot`, `setup muse` | always (a bot harness) |
+| `gbrain setup claude-code` | a chat-channel plugin (telegram, discord, slack, imessage, whatsapp, signal) is enabled |
+| `gbrain mcp grant`, `gbrain connect` | the harness is a bot harness, or the grant reads chat from 2+ channels |
+| `gbrain skillpack scaffold` | the target is OpenClaw's or Hermes's own workspace |
+| `gbrain auth create`, `gbrain auth register-client` | the new credential reads chat from 2+ channels |
+
+Chat pages are the slack, DM, iMessage, Discord, Telegram, WhatsApp, Signal,
+SMS, chat and channel page types that a remote caller can see. A channel is
+the page's `channel`, `chat` or `conversation` frontmatter, a leading
+`#name` in its title, or else its source; every DM page counts as its own
+channel. The warning goes to stderr (an `[AGENT]` block when stdout is not a
+terminal) and into the `notices` or `warnings` list of a `--json` result.
+It never changes a grant or an exit code.
+
+`gbrain doctor --only unscoped_multi_user_token` runs the same detection over
+every active token and OAuth client, and over the local agents setup wired: it
+warns when one of them reads chat from 2+ channels, and reports a wired bot
+harness with no such chat as information. A remote `run_doctor` caller gets a
+count, never credential names.
+
+Fix it with today's commands:
+
+- When the channels sit in different sources, grant one audience's source
+ only: `gbrain auth rescope --token <name> --sources <source>` (or
+ `--client <id>`), or for a new harness grant
+ `gbrain mcp grant <name> --source <source> --federated-read <source>`. Keep
+ a channel's source out of unscoped reads with `gbrain sources unfederate <id>`.
+- For a local stdio agent, set `GBRAIN_SOURCE=<source>` in its MCP server
+ environment.
+- When the chat sits in one source, a source grant cannot separate it: mark
+ the pages nobody else may see `visibility: private` (hidden from every
+ remote caller while `search.remote_private_pages` stays off).
+- Narrow single calls with `source_ids` on search and query (MCP) or
+ `--source` on the CLI.
+
+Per-member keys (`gbrain access member add <id>`, then
+`gbrain auth create <name> --member <id>`) arrive with gbrain#7812.
+
## Dashboard API keys
**Say to your agent:** *"Make a read-only API key for my notes app."* The
diff --git a/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md b/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md
index e5d03430b4..955e3447da 100644
--- a/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md
@@ -62,6 +62,8 @@ process, delete its lock, or start another server to obtain administration.
- **Create:** machine access uses `mcp grant NAME --harness ID` with a private
handoff. Native OAuth uses `mcp admin register NAME --redirect-uri URI`; choose
the actual callback and authentication method, not a guessed vendor default.
+ A `unscoped_multi_user_token` warning means people sharing that agent can see
+ each other's chat: relay it and its fix before several people use the agent.
- **Setup:** `setup ID --harness ID` reads the actual client method. For a mixed
registration, explicitly select `--flow authorization-code` or
`--flow client-credentials`. Ordinary output contains no secret; confidential
diff --git a/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md b/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md
index e5d03430b4..955e3447da 100644
--- a/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md
@@ -62,6 +62,8 @@ process, delete its lock, or start another server to obtain administration.
- **Create:** machine access uses `mcp grant NAME --harness ID` with a private
handoff. Native OAuth uses `mcp admin register NAME --redirect-uri URI`; choose
the actual callback and authentication method, not a guessed vendor default.
+ A `unscoped_multi_user_token` warning means people sharing that agent can see
+ each other's chat: relay it and its fix before several people use the agent.
- **Setup:** `setup ID --harness ID` reads the actual client method. For a mixed
registration, explicitly select `--flow authorization-code` or
`--flow client-credentials`. Ordinary output contains no secret; confidential
diff --git a/plugin/skills/mcp-access/SKILL.md b/plugin/skills/mcp-access/SKILL.md
index e5d03430b4..955e3447da 100644
--- a/plugin/skills/mcp-access/SKILL.md
+++ b/plugin/skills/mcp-access/SKILL.md
@@ -62,6 +62,8 @@ process, delete its lock, or start another server to obtain administration.
- **Create:** machine access uses `mcp grant NAME --harness ID` with a private
handoff. Native OAuth uses `mcp admin register NAME --redirect-uri URI`; choose
the actual callback and authentication method, not a guessed vendor default.
+ A `unscoped_multi_user_token` warning means people sharing that agent can see
+ each other's chat: relay it and its fix before several people use the agent.
- **Setup:** `setup ID --harness ID` reads the actual client method. For a mixed
registration, explicitly select `--flow authorization-code` or
`--flow client-credentials`. Ordinary output contains no secret; confidential
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index 02d0686f4e..edca55f93e 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -96,9 +96,11 @@ const DELEGATED_MODULES: Record<string, string[]> = {
* direct-pool-profile.ts reads other commands'
* argv to pick the process's pool profile (`sync --watch`, `serve --access`):
* serve imports it for the read-only check, and its `--watch` made
- * `gbrain serve --watch` pass validation.
+ * `gbrain serve --watch` pass validation. grants/shared-exposure.ts (GST-363)
+ * names other commands' flags (auth rescope, mcp grant, doctor) in warning
+ * text that setup, mcp, connect, skillpack and auth print.
*/
-const EXCLUDED_MODULES = ['thin-client-routing.ts', 'persistence-delegate.ts', 'job-isolation.ts', 'strict-args.ts', 'direct-pool-profile.ts', 'flag-equals.ts'];
+const EXCLUDED_MODULES = ['thin-client-routing.ts', 'persistence-delegate.ts', 'job-isolation.ts', 'strict-args.ts', 'direct-pool-profile.ts', 'flag-equals.ts', 'shared-exposure.ts'];
function isExcludedModule(p: string): boolean {
// Basename comparison is path-separator agnostic: on Windows p ends in
diff --git a/skills/mcp-access/SKILL.md b/skills/mcp-access/SKILL.md
index fcfc22da93..07e73b58cd 100644
--- a/skills/mcp-access/SKILL.md
+++ b/skills/mcp-access/SKILL.md
@@ -61,6 +61,8 @@ process, delete its lock, or start another server to obtain administration.
- **Create:** machine access uses `mcp grant NAME --harness ID` with a private
handoff. Native OAuth uses `mcp admin register NAME --redirect-uri URI`; choose
the actual callback and authentication method, not a guessed vendor default.
+ A `unscoped_multi_user_token` warning means people sharing that agent can see
+ each other's chat: relay it and its fix before several people use the agent.
- **Setup:** `setup ID --harness ID` reads the actual client method. For a mixed
registration, explicitly select `--flow authorization-code` or
`--flow client-credentials`. Ordinary output contains no secret; confidential
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 76abef9092..3a037257b1 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -96,7 +96,7 @@
"ingest/SKILL.md": "1acc220ce6e9e65876fa2ccede6ce11f9c75457feb6695ef904955f8debecaae",
"maintain/SKILL.md": "6faf40cb944a0deb7d032e41f44b66f05fe0ebe8178bd84d3cf05e2f766f6127",
"manifest.json": "357aa185d380f0a357cb15cd513317e290cbc5fcf5ca4e3860b0e829fdcbf1e4",
- "mcp-access/SKILL.md": "1bc16338b89f476aa8c24ffec79c989fa60716793998af264d357f7886d2bc96",
+ "mcp-access/SKILL.md": "4373e0164981eb7f8cd3794a2eae895d77426cef478c8d9d959de585256d4b50",
"measure-before-you-fix/SKILL.md": "11906da29a1a31976b13d4796b686d9a9981825737846a85f32d88bf431b9b36",
"measure-before-you-fix/routing-eval.jsonl": "0661df9974a9cfe31216d574b1db0ef341945c2eb844ebf4ab6920fcbbc90d6c",
"media-ingest/SKILL.md": "d70374d3df21397380203f541ebdcc90c0bc6bc7207234349594a081e98f2719",
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index 5d9604589e..fb9a16368e 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -36,6 +36,7 @@ import { parseClientRescopeArgs, parseRescopeGrantArgs, splitRescopeTarget, type
import { GRANT_PROFILES, GrantError, TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, grantFromClient, privatePagesFromColumn, type ClientGrant, type PrivatePagesGrant } from '../core/grants/model.ts';
import { cliRenderContext, renderAction, type RenderedAction } from '../core/agent-output.ts';
import type { INSTALL_SURFACE_SET_BY } from '../mcp/surface.ts';
+import { credentialCensus, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';
import { migrateLegacyTokens, parseRescopeTokenArgs, renderLegacyGrantAxis, rescopeLegacyToken, resolveRescopeTarget, type MigrateLegacyResult, type RescopeTokenResult } from '../core/grants/legacy-token.ts';
import { bindCredential, type BindingPatch, type BindingResult } from '../core/access/members.ts';
import { bindingLine, checkBindingTarget, takeBindingFlags } from './auth-binding.ts';
@@ -124,6 +125,8 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: st
console.log('Save this token — it will not be shown again.');
console.log(`Revoke with: gbrain auth revoke "${name}" (or gbrain auth revoke --id <id> from auth list)`);
console.log(`Change its grants: gbrain auth rescope --token "${name}" --takes-holders world,garry (or --sources, --operations)`);
+ const grant = { principal: { kind: 'legacy_token' as const, id: row!.id }, scopes: opts.scopes ?? ['read', 'write', 'admin'], sources: { kind: 'default' as const } };
+ writeExposureNotice(sharedTokenNotice({ kind: 'legacy_token', name }, { census: await credentialCensus(engine, grant) }));
});
} catch (e: any) {
if (e instanceof OperationError) exitCliError(e, 'auth');
@@ -805,6 +808,8 @@ async function registerClient(name: string, args: string[]) {
console.log(line);
}
if (bound) console.log(bindingLine(bound));
+ const grant = await readClientGrant(engine, registered.clientId).then(grantFromClient).catch(() => null);
+ if (grant) writeExposureNotice(sharedTokenNotice({ kind: 'oauth_client', id: registered.clientId, name }, { census: await credentialCensus(engine, grant) }));
});
} catch (e: any) {
if (e instanceof OperationError) exitCliError(e, 'auth');
diff --git a/src/commands/doctor/checks/unscoped-multi-user-token.ts b/src/commands/doctor/checks/unscoped-multi-user-token.ts
new file mode 100644
index 0000000000..0e1319455d
--- /dev/null
+++ b/src/commands/doctor/checks/unscoped-multi-user-token.ts
@@ -0,0 +1,94 @@
+/**
+ * GST-363 `unscoped_multi_user_token` (read-only, warn): credentials and local
+ * agents that can read chat from several channels with no per-person scope.
+ * An agent several people talk to through one such grant may answer one
+ * person with another person's messages (HARN-13 host-harness pilot). The
+ * detection is src/core/grants/shared-exposure.ts, the same module the install
+ * routes warn from.
+ *
+ * Warns only when chat from MULTI_CHANNEL_MIN+ channels is in reach of an
+ * active legacy token, a live OAuth client, or the stdio server of a wired bot
+ * harness (or of Claude Code with a chat-channel plugin). A bot harness with
+ * no such chat in reach is reported as information, so a brain that cannot
+ * act on it before per-member keys (gbrain#7812) is not marked unhealthy.
+ * A remote caller (run_doctor only) gets counts, never credential names.
+ */
+import { grantFromClient, grantFromRow, grantFromTokenRow, type PrincipalGrant } from '../../../core/grants/model.ts';
+import { BOT_HARNESSES, NOTICE_CODE, chatChannelCensus, claudeCodeChannelPlugins, credentialReadSources, exposureFix, exposureReasons,
+ stdioReadSources, subjectLabel, type ChatCensus, type ExposureSubject } from '../../../core/grants/shared-exposure.ts';
+import { readBrainFirstLedger } from '../../../core/setup/brain-first.ts';
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+interface Finding { subject: ExposureSubject; label: string; reasons: string[]; census: ChatCensus }
+
+async function runUnscopedMultiUserToken(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ const engine = connectedEngine(ctx);
+ const memo = new Map<string, Promise<ChatCensus>>();
+ const census = (sources: string[]) => {
+ const key = [...sources].sort().join(',');
+ if (!memo.has(key)) memo.set(key, chatChannelCensus(engine, sources));
+ return memo.get(key)!;
+ };
+ const credentials: Array<{ subject: ExposureSubject; grant: PrincipalGrant }> = [];
+ for (const row of await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE revoked_at IS NULL ORDER BY created_at, id')) {
+ credentials.push({ subject: { kind: 'legacy_token', name: String(row.name) }, grant: grantFromTokenRow(row) });
+ }
+ for (const row of await engine.executeRaw<Record<string, unknown>>('SELECT * FROM oauth_clients WHERE deleted_at IS NULL ORDER BY client_id')) {
+ const grant = grantFromRow(row);
+ credentials.push({ subject: { kind: 'oauth_client', id: grant.clientId, name: grant.clientName || undefined }, grant: grantFromClient(grant) });
+ }
+ const findings: Finding[] = [];
+ for (const { subject, grant } of credentials) {
+ const c = await census(await credentialReadSources(engine, grant));
+ const reasons = exposureReasons({ census: c });
+ if (reasons.length) findings.push({ subject, label: subjectLabel(subject), reasons, census: c });
+ }
+ const local: Finding[] = [];
+ if (!ctx.remote) {
+ const plugins = claudeCodeChannelPlugins();
+ const harnesses = [...new Set([
+ ...readBrainFirstLedger().filter(e => e.status === 'installed' && BOT_HARNESSES.includes(e.harness)).map(e => e.harness),
+ ...(plugins.length ? ['claude-code'] : []),
+ ])];
+ const stdio = harnesses.length ? await census(await stdioReadSources(engine)) : null;
+ for (const harness of harnesses) {
+ const subject: ExposureSubject = { kind: 'stdio', harness };
+ local.push({ subject, label: subjectLabel(subject), census: stdio!,
+ reasons: exposureReasons({ harness, channelPlugins: harness === 'claude-code' ? plugins : undefined, census: stdio }) });
+ }
+ }
+ const flagged = [...findings, ...local.filter(f => f.reasons.includes('multi_channel_chat'))];
+ const details = (list: Finding[]) => list.map(f => ({ subject: f.subject, reasons: f.reasons, read_sources: f.census.sources, chat_sources: f.census.chat_sources,
+ chat_pages: f.census.chat_pages, channels: f.census.channels, fix: exposureFix(f.subject, f.census) }));
+ if (flagged.length === 0) {
+ const bots = local.map(f => f.subject.kind === 'stdio' ? f.subject.harness : '').filter(Boolean);
+ if (bots.length) {
+ checks.push({ name: 'unscoped_multi_user_token', status: 'ok', severity: 'info', readiness_state: 'ok',
+ message: `${bots.join(', ')} serve${bots.length === 1 ? 's' : ''} a chat agent from this brain with no per-person scope; no chat from several channels is in its reach now. `
+ + 'Scope the agent before you add channel or DM pages (this check reports it then).',
+ details: { local: details(local) } });
+ } else {
+ checks.push({ name: 'unscoped_multi_user_token', status: 'ok', message: 'No credential or local agent can read chat from several channels without a per-person scope.' });
+ }
+ return checks;
+ }
+ const first = flagged[0]!;
+ checks.push({
+ name: 'unscoped_multi_user_token', status: 'warn',
+ message: ctx.remote
+ ? `${flagged.length} credential(s) can read chat from several channels with no per-person scope, so an agent several people use may answer one person with another person's messages. Ask the brain host's operator to run gbrain doctor --only ${NOTICE_CODE}.`
+ : `${flagged.length} credential(s) or local agent(s) can read chat from several channels with no per-person scope: ${first.label} reaches ${first.census.channels} channels in ${first.census.chat_sources.join(', ')}`
+ + `${flagged.length > 1 ? `, and ${flagged.length - 1} more in details.flagged` : ''}. An agent several people use may answer one person with another person's messages.`,
+ details: ctx.remote ? { flagged_count: flagged.length } : { flagged: details(flagged) },
+ ...(ctx.remote ? {} : { fix: exposureFix(first.subject, first.census) }),
+ });
+ return checks;
+}
+
+export const unscopedMultiUserTokenEntry: DoctorEntry = {
+ name: 'unscoped_multi_user_token',
+ emits: ['unscoped_multi_user_token'],
+ run: runUnscopedMultiUserToken,
+};
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 88f1a8a799..f2f6f146bd 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -93,6 +93,7 @@ import { contentDriftSweepEntry } from './checks/content-drift-sweep.ts';
import { connectorAccountMismatchEntry } from './checks/connector-account-mismatch.ts';
import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';
import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';
+import { unscopedMultiUserTokenEntry } from './checks/unscoped-multi-user-token.ts';
import { grantNewOpsEntry } from './checks/grant-new-ops.ts';
import { linksExtractionLagEntry, syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';
import { persistenceConsumersEntry, serveBuildDriftEntry } from './checks/persistence-consumers.ts';
@@ -266,6 +267,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
legacyJobAuthorityEntry,
legacyTokenGrantsEntry,
grantNewOpsEntry,
+ unscopedMultiUserTokenEntry,
indexAuditEntry,
imageAssetsEntry,
imageEmbeddingCoverageEntry,
diff --git a/src/commands/harness-connect.ts b/src/commands/harness-connect.ts
index 404827523f..fe8ff0e00b 100644
--- a/src/commands/harness-connect.ts
+++ b/src/commands/harness-connect.ts
@@ -6,6 +6,7 @@ import { normalizeMcpUrl } from '../core/mcp-registration.ts';
import { validateHarnessArguments } from '../core/harness/arguments.ts';
import { readHarnessConnectionStatus } from '../core/harness/status.ts';
import { isSkillLoading, skillsOutcomeFailed, type SkillsBlockOutcome } from '../core/setup/skills-block.ts';
+import { renderedExposure, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';
export async function runHarnessConnect(args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) {
@@ -32,7 +33,9 @@ export async function runHarnessConnect(args: string[]): Promise<void> {
const result = args.includes('--install') || args.includes('--remove')
? await installHarnessConnection(c, { harness: harness.id, name: value('--name'), root: value('--root'), remove: args.includes('--remove'), credentialsFile: path, freshToken: args.includes('--fresh-token'), ...(args.includes('--no-instructions') ? { instructions: false } : {}), ...(skillLoading ? { skillLoading } : {}), ...(value('--gbrain-bin') ? { gbrainBin: value('--gbrain-bin') } : {}) })
: { ...credentialReceipt(c), status: 'prepared', harness: harness.id, documentation: harness.guide, next_action: 'Run this command with --install inside the intended harness environment. Keep the credential file private.' };
- console.log(JSON.stringify(result, null, args.includes('--json') ? undefined : 2));
+ const exposure = args.includes('--remove') ? null : sharedTokenNotice({ kind: 'oauth_client', id: c.client_id }, { harness: harness.id });
+ writeExposureNotice(exposure);
+ console.log(JSON.stringify(exposure ? { ...result, warnings: renderedExposure(exposure) } : result, null, args.includes('--json') ? undefined : 2));
const token = result as Partial<ReturnType<typeof inlineTokenReceipt>>;
if (!args.includes('--json') && token.token_storage === 'inline' && token.if_exposed) {
console.error(`The bearer token is stored inline in ${token.config_path}; this output never prints it. Renew it with: ${token.renew_command}`);
diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts
index 1a84e6b512..464746eae6 100644
--- a/src/commands/mcp.ts
+++ b/src/commands/mcp.ts
@@ -10,6 +10,8 @@ import { provisionHarnessGrant, type ProvisionGrantInput } from './mcp-provision
import { validateHarnessArguments, MCP_GRANT_ARGUMENTS } from '../core/harness/arguments.ts';
import { createMcpAdminHttp, hasAdminCredential, McpAdminError, redactAdminValue } from './mcp-admin-http.ts';
import { runMcpAdmin } from './mcp-admin.ts';
+import { grantFromClient } from '../core/grants/model.ts';
+import { credentialCensus, renderedExposure, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';
const HELP = `gbrain mcp — provision access on the host; install it inside the harness
@@ -143,7 +145,13 @@ export async function runMcp(args: string[], engine?: BrainEngine): Promise<void
try { writeCredentials(value('--credentials-out')!, result.credentials); }
catch { throw new Error(`credential_delivery_incomplete: client ${result.grant.clientId} exists; repeat with --resume --client ${result.grant.clientId} --credentials-out <private-file>. Do not create a duplicate or rotate its secret automatically.`); }
}
+ const exposure = sharedTokenNotice({ kind: 'oauth_client', id: result.grant.clientId || input.name, name: input.name }, {
+ harness: harnessAdapter(input.harness).id,
+ census: engine && !hasAdminCredential(args) ? await credentialCensus(engine, grantFromClient(result.grant)) : null,
+ });
+ writeExposureNotice(exposure);
console.log(JSON.stringify({ status: result.dry_run ? 'preview' : 'granted', grant: result.grant, before: result.before,
+ ...(exposure ? { warnings: renderedExposure(exposure) } : {}),
spending: result.grant.budgetUsdPerDay === null ? { mode: 'unlimited' } : { mode: 'daily_cap', usd: result.grant.budgetUsdPerDay },
credentials: result.credentials ? credentialReceipt(result.credentials) : result.credential_action,
credential_file: result.credentials ? value('--credentials-out') : null,
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index acbed945e0..c10900be47 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -31,6 +31,7 @@ import { inspectTurnHook, TURN_HOOK_NATIVE_INSPECT, turnHookFix, verifyTurnHook,
import { opError, OperationError } from '../core/ops/contract.ts';
import { cliRenderContext, renderCliError, renderNotice, type Action, type Notice } from '../core/agent-output.ts';
import { writeCliNotices } from '../core/interop-notices.ts';
+import { claudeCodeChannelPlugins, renderedExposure, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';
import { setupFirstRunNotices } from './init-first-run.ts';
import { hostedOptionMuted, hostedOptionNotice, writeHostedOption } from '../core/onboard/hosted-option.ts';
import { writeJsonDocument } from '../core/cli-force-exit.ts';
@@ -805,14 +806,17 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
const surface = flags.surface ?? (isRegistrationSurface(envSurface) ? envSurface : undefined);
const access: BrainFirstAccess = { kind: 'mcp', server: flags.name, ...(surface ? { surface } : {}) };
const mcp = { setup: flags.instructionsOnly ? 'unchanged' as const : 'manual' as const, docs: adapter.guide };
+ const exposure = flags.remove ? null : sharedTokenNotice({ kind: 'stdio', harness }, { harness });
+ const notices = renderedExposure(exposure);
if (!isBrainFirstHarness(harness)) {
const pasted: BrainFirstAccess = adapter.connection === 'thin-cli' ? { kind: 'cli', launcher: flags.gbrainBin ?? 'gbrain' } : access;
const snippet = renderBrainFirstSnippet(harness, pasted, 'delete this block');
if (out.json) {
await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true,
- instructions: { action: 'print', snippet, where: `${adapter.label}'s custom or system instructions` }, mcp }, null, 2)}\n`, (t) => process.stdout.write(t));
+ instructions: { action: 'print', snippet, where: `${adapter.label}'s custom or system instructions` }, mcp, notices }, null, 2)}\n`, (t) => process.stdout.write(t));
return 0;
}
+ writeExposureNotice(exposure);
console.log(`${adapter.label} has no instruction file gbrain can write. Paste this block into its custom or system instructions (keep the markers so a later paste replaces it):\n`);
console.log(snippet);
console.log(adapter.connection === 'thin-cli'
@@ -851,9 +855,10 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
const check = !off && !flags.dryRun && instructions?.decision.value === 'accepted' && !flags.noHooks && process.env.GBRAIN_HOOKS !== '0' && turnHook && turnHook.action !== 'print' && turnHook.action !== 'remove' ? verifyTurnHook(harness, { projectDir }) : null;
const code = instructions?.action === 'preserve' || skillsFailed(skills) || (check && !check.ok) ? 1 : 0;
if (out.json) {
- await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), ...(check ? { turn_hook_check: check } : {}), skills, mcp }, null, 2)}\n`, (t) => process.stdout.write(t));
+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), ...(check ? { turn_hook_check: check } : {}), skills, mcp, notices }, null, 2)}\n`, (t) => process.stdout.write(t));
return code;
}
+ writeExposureNotice(exposure);
if (instructions) say(out, flags.remove ? describeBrainFirstOutcome(instructions, flags.dryRun) : describeInstructions(instructions, flags.dryRun));
if (turnHook) say(out, ` ${(flags.dryRun && (turnHook.action === 'write' || turnHook.action === 'remove') ? `would ${turnHook.action}` : turnHook.action).padEnd(8)} ${'turn hook'.padEnd(7)} ${turnHook.detail}${'snippet' in turnHook && turnHook.snippet ? `:\n${turnHook.snippet.replace(/^/gm, ' ')}` : ''}${'commands' in turnHook && turnHook.commands ? `:\n${turnHook.commands.map((c) => ` ${c}`).join('\n')}` : ''}${'next' in turnHook && turnHook.next ? `; wire it with: ${turnHook.next}` : ''}`);
else if (!off && placed) say(out, ` note ${'turn hook'.padEnd(7)} ${adapter.label} has no per-turn hook gbrain can install; the rule reaches it through ${target.path} only.`);
@@ -912,13 +917,15 @@ async function finish(out: Out, doc: {
const harness = doc.harness ?? 'claude-code';
const state = doc.states.at(-1) ?? null;
const code = skillsFailed(doc.skills ?? null) ? 1 : 0;
+ const exposure = harness === 'claude-code' && !doc.remove ? sharedTokenNotice({ kind: 'stdio', harness }, { channelPlugins: claudeCodeChannelPlugins() }) : null;
+ const notices = exposure ? [...doc.notices, exposure] : doc.notices;
if (out.json) {
await writeJsonDocument(`${JSON.stringify({
harness, dry_run: doc.dryRun, remove: doc.remove ?? false,
...(doc.target ? { target: doc.target } : {}), ...(doc.consent ? { consent: doc.consent } : {}),
steps: doc.steps, preserved: doc.preserved ?? [], instructions: doc.instructions ?? null, skills: doc.skills ?? null, ...(doc.turnHook ? { turn_hook_check: doc.turnHook } : {}), states: doc.states, state, verify: doc.verify,
capability: capabilityRows(harness)[0], capability_table_version: SETUP_CAPABILITY_TABLE_VERSION,
- notes: doc.notes, notices: doc.notices.map((n) => renderNotice(n, cliRenderContext())),
+ notes: doc.notes, notices: notices.map((n) => renderNotice(n, cliRenderContext())),
}, null, 2)}\n`, (t) => process.stdout.write(t));
return code;
}
@@ -932,7 +939,7 @@ async function finish(out: Out, doc: {
: 'Next: open a new Claude Code session (config is read at session start) and check that /mcp lists gbrain.');
if (state && !doc.remove) say(out, 'Memory: save what the user asks you to remember as a fact with gbrain remember "<fact>", naming its entity and provenance (MCP tool: remember). '
+ 'World-visible facts (the default) are pushed into new sessions; a private fact is not (local CLI recall only). capture writes a page, not a fact.');
- writeCliNotices(doc.notices.filter((n) => n.code !== 'hosted_option'));
+ writeCliNotices(notices.filter((n) => n.code !== 'hosted_option'));
if (doc.notices.some((n) => n.code === 'hosted_option')) writeHostedOption('setup', new Set());
return code;
}
diff --git a/src/commands/skillpack/scaffold.ts b/src/commands/skillpack/scaffold.ts
index 4fdba5409d..3a5fb1e6e7 100644
--- a/src/commands/skillpack/scaffold.ts
+++ b/src/commands/skillpack/scaffold.ts
@@ -29,11 +29,15 @@ import { SkillpackManifestError } from '../../core/skillpack/manifest-v1.ts';
import { VERSION } from '../../version.ts';
import { findGbrainOrDie, resolveWorkspace } from './shared.ts';
import { consentGate } from '../../core/consent-cli.ts';
+import { botHarnessForWorkspace, sharedTokenNotice, writeExposureNotice } from '../../core/grants/shared-exposure.ts';
export async function cmdScaffold(args: string[]): Promise<void> {
// Harness lane (cathedral-7): `--harness <h>` installs a persona-curated
// set into a harness's native skills dir instead of a workspace.
if (args.some(a => a === '--harness' || a.startsWith('--harness='))) {
+ const i = args.indexOf('--harness');
+ const harness = i >= 0 ? args[i + 1] : args.find(a => a.startsWith('--harness='))!.slice('--harness='.length);
+ if (!args.includes('--help') && !args.includes('-h')) writeExposureNotice(sharedTokenNotice({ kind: 'stdio', harness: harness ?? '' }, { harness }));
const { cmdScaffoldHarness } = await import('./harness.ts');
await cmdScaffoldHarness(args);
return;
@@ -89,6 +93,8 @@ export async function cmdScaffold(args: string[]): Promise<void> {
// 3. Bare kebab AND matches a bundled-skill slug → bundled (v0.36 path)
// 4. Bare kebab AND NOT a bundled-skill slug → third-party via registry
const targetWorkspace = resolveWorkspace({ workspace });
+ const botHarness = botHarnessForWorkspace(targetWorkspace);
+ if (botHarness) writeExposureNotice(sharedTokenNotice({ kind: 'stdio', harness: botHarness }, { harness: botHarness }));
const isThirdPartyShape = !all && name !== null && /[\/:]|\.(tgz|tar\.gz)$/.test(name);
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 7f676f4c6a..c328b1bb3f 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -432,6 +432,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'legacy_token_null_scope',
// D4: grants whose operation snapshot or stored surface keeps operations their scopes allow out of reach.
'grant_new_ops_available',
+ // GST-363: credentials or local bot agents reading chat from several channels with no per-person scope.
+ 'unscoped_multi_user_token',
'reranker_health',
'rls',
// #7632: every gbrain function that pins a search_path ends it with pg_temp.
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index af6d21fed8..29fd53d9e9 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -953,6 +953,7 @@ export const NOTICE_CODES = {
first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run decisions (search mode, writeback, harness wiring, skills) carry defaults the user may change. The one muteable ask.' },
first_run_decisions_muted: { kind: 'info', summary: 'First-run decisions are still open, but the user muted them; the fix shows them again (`gbrain notices unmute first_run_decisions`).' },
migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },
+ unscoped_multi_user_token: { kind: 'safety', summary: 'An install route (gbrain setup openclaw|hermes|grok-bot|muse, setup claude-code with a chat-channel plugin, mcp grant, connect, skillpack scaffold for a bot harness, auth create, auth register-client) set up access with no per-person scope for a likely multi-user agent: a bot harness, or a grant that reads chat from 2+ channels. Several people talking to that agent may get each other\'s messages. The notice names today\'s fixes (a one-source grant, gbrain sources unfederate, visibility: private, source_ids or --source); doctor `unscoped_multi_user_token` reports the same detection. docs/mcp/ADMIN.md#one-token-several-people' },
socket_identity_mismatch: { kind: 'degraded', summary: 'The running serve\'s warm CLI socket refused this CLI call because an identity part (named, never its value) differs from the serve\'s, so the call ran on the slower cold path; doctor `cli_socket_refusals` counts these.' },
sync_retry_failed_deprecated: { kind: 'coaching', summary: '`gbrain sync --retry-failed` is a deprecated alias for a plain sync, accepted for two releases: a plain sync retries a failure the previous run recorded by itself. Drop the flag.' },
reason_not_committed: { kind: 'degraded', summary: 'A write\'s reason is in gbrain\'s page history but in no Git commit: on a non-strict source a newer write to the same file committed first, carrying only its own reason. Nothing needs fixing and retrying the write is wrong (docs/guides/page-history.md#reasons).' },
diff --git a/src/core/grants/shared-exposure.ts b/src/core/grants/shared-exposure.ts
new file mode 100644
index 0000000000..e875c689c3
--- /dev/null
+++ b/src/core/grants/shared-exposure.ts
@@ -0,0 +1,222 @@
+/**
+ * GST-363 (HARN-13 host-harness pilot, harness-evals#145): one credential with
+ * no per-person scope, serving an agent that several people talk to, lets the
+ * agent answer one person with pages only another person may read. Until
+ * per-member keys ship (gbrain#7812) gbrain cannot tell people apart, so the
+ * install routes and doctor warn instead. Nothing here changes a grant.
+ *
+ * A serve is likely multi-user when any signal holds:
+ * - `bot_harness`: the harness is a channel or bot agent (BOT_HARNESSES);
+ * - `channel_plugin`: Claude Code has a chat-channel plugin enabled;
+ * - `multi_channel_chat`: the read set holds remote-visible chat pages from
+ * MULTI_CHANNEL_MIN or more distinct channels (every DM page counts alone).
+ *
+ * Every input is a database row or a harness config file, never git, so a
+ * repo-less brain is covered the same way as a repo brain.
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join, relative, resolve, sep } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { cliRenderContext, renderNotice, type Action, type Notice } from '../agent-output.ts';
+import { renderCliNotices } from '../agent-markers.ts';
+import { isInteractive } from '../interaction.ts';
+import { hasScope } from '../scope.ts';
+import { localFederatedSourceIds, resolveSourceWithTier } from '../source-resolver.ts';
+import { privatePagesFilterFragmentFast, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import { pageTypesForAllowed } from '../facts/conversation-types.ts';
+import { claudeConfigDir } from '../bootstrap/host-specs.ts';
+import type { PrincipalGrant } from './model.ts';
+
+export const NOTICE_CODE = 'unscoped_multi_user_token';
+export const BOT_HARNESSES: readonly string[] = ['openclaw', 'hermes', 'grok-bot', 'muse'];
+export const CHANNEL_PLUGINS: readonly string[] = ['telegram', 'discord', 'slack', 'imessage', 'whatsapp', 'signal'];
+const DM_PAGE_TYPES: readonly string[] = ['slack-dm-day', 'dm', 'sms'];
+export const CHAT_PAGE_TYPES: readonly string[] = [...new Set([...pageTypesForAllowed(['slack', 'imessage', 'imessage-daily']), ...DM_PAGE_TYPES,
+ 'discord', 'telegram', 'whatsapp', 'signal', 'chat', 'channel'])];
+export const MULTI_CHANNEL_MIN = 2;
+const DOCS = 'docs/mcp/ADMIN.md#one-token-several-people';
+
+export type ExposureReason = 'bot_harness' | 'channel_plugin' | 'multi_channel_chat';
+/** `chat_sources`: the read sources that hold chat; channels across 2+ of them can be split by source grants, within one they cannot. */
+export interface ChatCensus { sources: string[]; chat_pages: number; channels: number; chat_sources: string[] }
+
+/** The chat-channel plugins Claude Code has enabled (settings.json `enabledPlugins`, `<name>@<marketplace>: true`). */
+export function claudeCodeChannelPlugins(configDir = claudeConfigDir()): string[] {
+ const path = join(configDir, 'settings.json');
+ if (!existsSync(path)) return [];
+ try {
+ const enabled = (JSON.parse(readFileSync(path, 'utf8')) as { enabledPlugins?: Record<string, unknown> }).enabledPlugins ?? {};
+ return Object.entries(enabled).filter(([key, on]) => on === true && CHANNEL_PLUGINS.includes(key.split('@')[0]!.toLowerCase())).map(([key]) => key);
+ } catch {
+ return [];
+ }
+}
+
+/** The bot harness whose home holds this workspace (OpenClaw's ~/.openclaw*, Hermes's $HERMES_HOME or ~/.hermes), or null. */
+export function botHarnessForWorkspace(workspace: string | null | undefined, home = homedir()): string | null {
+ if (!workspace) return null;
+ const path = resolve(workspace);
+ const under = (dir: string) => path === dir || path.startsWith(dir + sep);
+ const hermesHome = process.env.HERMES_HOME?.trim() ? resolve(process.env.HERMES_HOME.trim().replace(/^~(?=$|\/)/, home)) : join(home, '.hermes');
+ if (under(hermesHome)) return 'hermes';
+ const first = relative(home, path).split(sep)[0] ?? '';
+ return first === '.openclaw' || first.startsWith('.openclaw-') ? 'openclaw' : null;
+}
+
+/**
+ * The sources a credential reads with no per-call source_ids, as dispatch
+ * resolves them: an unscoped legacy token reads the default source plus every
+ * federated source (serve-http's noGrantFederatedScope); an unscoped OAuth
+ * client reads `default`; a scalar grant its source; a federated grant its
+ * read set. A credential without read scope reads nothing.
+ */
+export async function credentialReadSources(engine: BrainEngine, grant: Pick<PrincipalGrant, 'principal' | 'scopes' | 'sources'>): Promise<string[]> {
+ if (!hasScope(grant.scopes, 'read')) return [];
+ switch (grant.sources.kind) {
+ case 'default': return grant.principal.kind === 'legacy_token'
+ ? await localFederatedSourceIds(engine, 'default', 'seed_default').catch(() => undefined) ?? ['default']
+ : ['default'];
+ case 'scalar': return [grant.sources.writeSource];
+ case 'federated': return [...grant.sources.readSources];
+ case 'none': return [];
+ }
+}
+
+/** What a local stdio server reads with no per-call source_ids (src/mcp/server.ts resolveMcpStdioSourceScope). */
+export async function stdioReadSources(engine: BrainEngine, cwd = process.cwd()): Promise<string[]> {
+ const resolved = await resolveSourceWithTier(engine, null, cwd).catch(() => ({ source_id: 'default', tier: 'seed_default' as const }));
+ return await localFederatedSourceIds(engine, resolved.source_id, resolved.tier).catch(() => undefined) ?? [resolved.source_id];
+}
+
+/**
+ * Chat pages a remote caller of these sources can see, and how many distinct
+ * channels they come from. A channel is the page's frontmatter channel, chat
+ * or conversation, else a leading `#name` in its title, else its source, so
+ * unlabelled chat in one source counts as one channel. A DM page is its own
+ * channel: it is the content another person must never see.
+ */
+export async function chatChannelCensus(engine: BrainEngine, sourceIds: readonly string[]): Promise<ChatCensus> {
+ const empty: ChatCensus = { sources: [...sourceIds], chat_pages: 0, channels: 0, chat_sources: [] };
+ if (sourceIds.length === 0) return empty;
+ const hidePrivate = await resolveExcludePrivatePages(engine, true);
+ const rows = await engine.executeRaw<{ source_id: string; chat_pages: number | string; channels: number | string }>(
+ `SELECT p.source_id, count(*) AS chat_pages,
+ count(DISTINCT CASE WHEN p.type = ANY($3::text[]) THEN 'dm:' || p.slug
+ ELSE COALESCE(NULLIF(p.frontmatter->>'channel', ''), NULLIF(p.frontmatter->>'chat', ''), NULLIF(p.frontmatter->>'conversation', ''),
+ lower(substring(p.title from '^#([A-Za-z0-9._-]+)')), '') END) AS channels
+ FROM pages p
+ WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND p.source_id = ANY($2::text[])
+ ${hidePrivate ? `AND ${privatePagesFilterFragmentFast('p')}` : ''}
+ GROUP BY p.source_id ORDER BY p.source_id`,
+ [[...CHAT_PAGE_TYPES], [...sourceIds], [...DM_PAGE_TYPES]],
+ );
+ return rows.reduce((c, r) => ({ ...c, chat_pages: c.chat_pages + Number(r.chat_pages), channels: c.channels + Number(r.channels), chat_sources: [...c.chat_sources, r.source_id] }), empty);
+}
+
+/** The census of what a credential reads, or null when it cannot be read (an install route never fails on its warning). */
+export async function credentialCensus(engine: BrainEngine, grant: Pick<PrincipalGrant, 'principal' | 'scopes' | 'sources'>): Promise<ChatCensus | null> {
+ try {
+ return await chatChannelCensus(engine, await credentialReadSources(engine, grant));
+ } catch {
+ return null;
+ }
+}
+
+export function exposureReasons(input: { harness?: string; channelPlugins?: readonly string[]; census?: ChatCensus | null }): ExposureReason[] {
+ const reasons: ExposureReason[] = [];
+ if (input.harness && BOT_HARNESSES.includes(input.harness)) reasons.push('bot_harness');
+ if (input.channelPlugins?.length) reasons.push('channel_plugin');
+ if (input.census && input.census.channels >= MULTI_CHANNEL_MIN) reasons.push('multi_channel_chat');
+ return reasons;
+}
+
+/** Who the warning is about: a minted credential, or the local stdio server a harness spawns. */
+export type ExposureSubject =
+ | { kind: 'legacy_token'; name: string }
+ | { kind: 'oauth_client'; id: string; name?: string }
+ | { kind: 'stdio'; harness: string };
+
+export function subjectLabel(s: ExposureSubject): string {
+ if (s.kind === 'legacy_token') return `The token "${s.name}"`;
+ if (s.kind === 'oauth_client') return `The OAuth client ${s.name ? `"${s.name}" (${s.id})` : s.id}`;
+ return `The gbrain access ${s.harness} uses`;
+}
+
+/** Source grants can separate channels only when they sit in different sources. */
+const splitBySource = (census: ChatCensus | null | undefined): boolean => !census || census.chat_sources.length >= 2;
+
+/** The narrowing command: a credential's rescope, or a stdio server pinned to one source. Null when no source split exists. */
+export function narrowArgv(s: ExposureSubject, census?: ChatCensus | null): string[] | null {
+ if (!splitBySource(census)) return null;
+ if (s.kind === 'legacy_token') return ['gbrain', 'auth', 'rescope', '--token', s.name, '--sources', '<source>'];
+ if (s.kind === 'oauth_client') return ['gbrain', 'auth', 'rescope', '--client', s.id, '--sources', '<source>'];
+ return null;
+}
+
+function reach(reasons: readonly ExposureReason[], census: ChatCensus | null | undefined, plugins: readonly string[] | undefined): string {
+ const parts: string[] = [];
+ if (reasons.includes('multi_channel_chat') && census) parts.push(`it reads chat from ${census.channels} channels in ${census.chat_sources.join(', ')}`);
+ if (reasons.includes('channel_plugin') && plugins?.length) parts.push(`Claude Code takes messages from ${plugins.join(', ')}`);
+ if (reasons.includes('bot_harness')) parts.push('it serves a chat agent several people can talk to');
+ return parts.join('; ');
+}
+
+/**
+ * Today's fixes, chosen by where the chat lives, then the per-member keys
+ * gbrain#7812 adds. One string so every route prints the same commands.
+ */
+export function remedyText(s: ExposureSubject, census?: ChatCensus | null): string {
+ const steps: string[] = [];
+ if (splitBySource(census)) {
+ steps.push(s.kind === 'stdio'
+ ? 'pin the agent to one audience\'s source by setting GBRAIN_SOURCE=<source> in its MCP server environment'
+ : `grant one audience's source only (${narrowArgv(s, census)!.join(' ')}; a new harness grant: gbrain mcp grant <name> --source <source> --federated-read <source>)`);
+ steps.push('keep a channel\'s source out of unscoped reads (gbrain sources unfederate <id>)');
+ } else {
+ steps.push(`the chat sits in one source (${census!.chat_sources[0]}), so a source grant cannot separate it`);
+ }
+ steps.push('mark pages nobody else may see visibility: private (hidden from every remote caller while search.remote_private_pages stays off)');
+ steps.push('narrow single calls with source_ids on search and query (MCP) or --source (CLI)');
+ return `Fix: ${steps.join('; ')}. Per-member keys (gbrain access member add <id>, then gbrain auth create <name> --member <id>) arrive with gbrain#7812 and are not in this version.`;
+}
+
+export function exposureFix(s: ExposureSubject, census?: ChatCensus | null): Action {
+ const argv = narrowArgv(s, census);
+ const verify = { argv: ['gbrain', 'doctor', '--only', NOTICE_CODE, '--json'] };
+ const message = `${subjectLabel(s)} lets the agent read every channel it reaches, so when several people use the agent it may show one person another person's messages. ${remedyText(s, census).replace(/^Fix: (.)/, (_m, c: string) => c.toUpperCase())}`;
+ if (argv) {
+ return { ask_user: true, argv, consent: ['credentials'], actor: 'agent', requires_exclusive: false, docs: DOCS, verify,
+ inputs: [{ name: 'source', how: 'Ask the user which one source this agent\'s audience may read (gbrain sources list).' }],
+ why: 'Narrowing the grant limits what the agent can show anyone to one audience\'s source; the secret is unchanged.', user_message: message };
+ }
+ return { ask_user: true, consent: [], actor: 'user', requires_exclusive: false, docs: DOCS, verify,
+ why: 'gbrain cannot tell the people in a chat apart yet; scoping this agent is the user\'s choice of source, private pages or a narrower deployment.', user_message: message };
+}
+
+/** The install-time warning. Null when no signal holds. */
+export function sharedTokenNotice(s: ExposureSubject, input: { harness?: string; channelPlugins?: readonly string[]; census?: ChatCensus | null }): Notice | null {
+ const reasons = exposureReasons(input);
+ if (reasons.length === 0) return null;
+ const fix = exposureFix(s, input.census);
+ return {
+ code: NOTICE_CODE, kind: 'safety', fix, user_message: fix.user_message,
+ why: `WARNING: ${subjectLabel(s)} is not scoped to a person (${reach(reasons, input.census, input.channelPlugins)}). `
+ + 'An agent using it can read every page that grant reaches, so when several people talk to the agent it may answer one person with another person\'s messages. '
+ + remedyText(s, input.census),
+ };
+}
+
+/** The notice as the JSON receipts carry it (`warnings`/`notices`). */
+export function renderedExposure(notice: Notice | null): ReturnType<typeof renderNotice>[] {
+ return notice ? [renderNotice(notice, cliRenderContext())] : [];
+}
+
+/** Install routes print on stderr: their stdout carries a token or a JSON document. A terminal gets readable lines, an agent an [AGENT] block. */
+export function writeExposureNotice(notice: Notice | null): void {
+ if (!notice) return;
+ try {
+ const out = renderCliNotices([renderNotice(notice, cliRenderContext())], { json: false, tty: isInteractive(), stdoutIsData: true });
+ if (out.stderr) process.stderr.write(out.stderr);
+ } catch { /* a warning never breaks the install */ }
+}
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 4e25de0931..144121ee5b 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -191,6 +191,7 @@
" [OK] legacy_token_grant_shape: Every active legacy token uses the unified grant columns. The permissions mirror for older gbrain binaries is kept until 2026-11-04.",
" [OK] legacy_token_grant_drift: No legacy token grant has drifted from its permissions mirror.",
" [OK] legacy_token_null_scope: Every active legacy token has explicit scopes.",
+ " [OK] unscoped_multi_user_token: No credential or local agent can read chat from several channels without a per-person scope.",
" [OK] grant_new_ops_available: Every active client and token can call the operations its scopes allow.",
" [OK] image_assets: No image assets indexed yet",
" [OK] ocr_health: OCR not in use (or no images ingested with OCR opt-in)",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 63bb1b5937..8e0e14dba7 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -2462,6 +2462,13 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No credential or local agent can read chat from several channels without a per-person scope.",
+ "name": "unscoped_multi_user_token",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index 0bf4f033b0..f80e322b13 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -2634,6 +2634,13 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No credential or local agent can read chat from several channels without a per-person scope.",
+ "name": "unscoped_multi_user_token",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
@@ -7731,6 +7738,13 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No credential or local agent can read chat from several channels without a per-person scope.",
+ "name": "unscoped_multi_user_token",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 8efd132b9c..2974d0a846 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -2638,6 +2638,13 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No credential or local agent can read chat from several channels without a per-person scope.",
+ "name": "unscoped_multi_user_token",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
@@ -7736,6 +7743,13 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No credential or local agent can read chat from several channels without a per-person scope.",
+ "name": "unscoped_multi_user_token",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 5dc7b9d4bb..c14d492616 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -2261,6 +2261,13 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No credential or local agent can read chat from several channels without a per-person scope.",
+ "name": "unscoped_multi_user_token",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index fe956f3135..76dd79f75e 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -2317,6 +2317,13 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No credential or local agent can read chat from several channels without a per-person scope.",
+ "name": "unscoped_multi_user_token",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 4c4b47af54..27e9245aa9 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -2321,6 +2321,13 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "elapsed_ms": "<volatile>",
+ "message": "No credential or local agent can read chat from several channels without a per-person scope.",
+ "name": "unscoped_multi_user_token",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 51e19e3824..723a376e82 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -801,6 +801,10 @@
"category": "ops",
"name": "legacy_token_null_scope"
},
+ {
+ "category": "ops",
+ "name": "unscoped_multi_user_token"
+ },
{
"category": "ops",
"name": "grant_new_ops_available"
diff --git a/test/shared-exposure-routes.test.ts b/test/shared-exposure-routes.test.ts
new file mode 100644
index 0000000000..c4cd3c8dba
--- /dev/null
+++ b/test/shared-exposure-routes.test.ts
@@ -0,0 +1,140 @@
+/**
+ * GST-363: every install route prints the unscoped_multi_user_token warning
+ * when the serve is likely multi-user, and stays quiet otherwise. Spawns the
+ * CLI against a temp HOME / GBRAIN_HOME; the brain routes run on a keyless
+ * PGLite brain with no repository (gbrain init --pglite --no-embedding).
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const CODE = 'unscoped_multi_user_token';
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+function box() {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-shared-routes-'));
+ roots.push(root);
+ const home = join(root, 'home');
+ mkdirSync(home, { recursive: true });
+ const env = { HOME: home, GBRAIN_HOME: home, CLAUDE_CONFIG_DIR: join(home, '.claude'), HERMES_HOME: undefined, OPENCLAW_STATE_DIR: undefined,
+ OPENCLAW_WORKSPACE_DIR: undefined, OPENCLAW_PROFILE: undefined, GBRAIN_SOURCE: undefined, GBRAIN_AGENT_INSTRUCTIONS: undefined };
+ return { root, home, env };
+}
+const json = (s: string) => { try { return JSON.parse(s); } catch { return null; } };
+const codes = (list: any[] | undefined) => (list ?? []).map((n) => n.code);
+
+describe('setup routes', () => {
+ test('setup openclaw and setup hermes carry the warning; --remove does not', async () => {
+ const b = box();
+ const ws = join(b.home, '.openclaw', 'workspace');
+ mkdirSync(ws, { recursive: true });
+ const openclaw = await runCli(['setup', 'openclaw', '--workspace', ws, '--dry-run', '--json'], { env: b.env, cwd: b.root });
+ const doc = json(openclaw.stdout);
+ expect(codes(doc?.notices)).toEqual([CODE]);
+ expect(doc.notices[0].why).toContain('another person\'s messages');
+ expect(doc.notices[0].why).toContain('GBRAIN_SOURCE=<source>');
+ expect(doc.notices[0].fix.next).toBe('ask_user');
+ const hermes = json((await runCli(['setup', 'hermes', '--dry-run', '--json'], { env: b.env, cwd: b.root })).stdout);
+ expect(codes(hermes?.notices)).toEqual([CODE]);
+ const removed = json((await runCli(['setup', 'openclaw', '--workspace', ws, '--remove', '--dry-run', '--json'], { env: b.env, cwd: b.root })).stdout);
+ expect(codes(removed?.notices)).toEqual([]);
+ }, 60_000);
+
+ test('setup hermes in human mode prints an [AGENT] block on stderr when not a terminal', async () => {
+ const b = box();
+ const r = await runCli(['setup', 'hermes', '--dry-run'], { env: b.env, cwd: b.root });
+ expect(r.stderr).toContain('[AGENT]');
+ expect(r.stderr).toContain(`[${CODE}] WARNING`);
+ expect(r.stdout).not.toContain(CODE);
+ }, 60_000);
+
+ test('setup grok-bot --instructions-only (the paste branch) carries the warning', async () => {
+ const b = box();
+ const doc = json((await runCli(['setup', 'grok-bot', '--instructions-only', '--json'], { env: b.env, cwd: b.root })).stdout);
+ expect(codes(doc?.notices)).toEqual([CODE]);
+ }, 60_000);
+
+ test('setup claude-code warns only when a chat-channel plugin is enabled', async () => {
+ const b = box();
+ const bin = join(b.root, 'gbrain');
+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' '${join(import.meta.dir, '..', 'src', 'cli.ts')}' "$@"\n`);
+ chmodSync(bin, 0o755);
+ const setup = async () => json((await runCli(['setup', 'claude-code', '--gbrain-bin', bin, '--dry-run', '--json'], { env: b.env, cwd: b.root })).stdout);
+ const quiet = await setup();
+ expect(quiet?.harness).toBe('claude-code');
+ expect(codes(quiet.notices)).not.toContain(CODE);
+ mkdirSync(join(b.home, '.claude'), { recursive: true });
+ writeFileSync(join(b.home, '.claude', 'settings.json'), JSON.stringify({ enabledPlugins: { 'telegram@claude-plugins-official': true } }));
+ const loud = await setup();
+ expect(codes(loud?.notices)).toContain(CODE);
+ expect(loud.notices.find((n: any) => n.code === CODE).why).toContain('telegram@claude-plugins-official');
+ }, 60_000);
+});
+
+describe('harness-side routes', () => {
+ test('skillpack scaffold --harness openclaw warns on stderr and keeps stdout for its JSON', async () => {
+ const b = box();
+ const r = await runCli(['skillpack', 'scaffold', '--harness', 'openclaw', '--workspace', join(b.home, '.openclaw', 'workspace'), '--dry-run', '--json'], { env: b.env, cwd: b.root });
+ expect(r.stderr).toContain(CODE);
+ expect(r.stdout).not.toContain(`[${CODE}]`);
+ }, 60_000);
+
+ test('connect --harness hermes adds warnings to its receipt; --harness claude-code does not', async () => {
+ const b = box();
+ const file = join(b.root, 'creds.json');
+ writeFileSync(file, JSON.stringify({ version: 1, mcp_url: 'https://brain.example.ts.net/mcp', client_id: 'client-a', client_secret: 'secretvalue0123456789abcdef' }));
+ chmodSync(file, 0o600);
+ const hermes = await runCli(['connect', 'https://brain.example.ts.net/mcp', '--harness', 'hermes', '--credentials-file', file, '--json'], { env: b.env, cwd: b.root });
+ const doc = json(hermes.stdout);
+ expect(doc?.status).toBe('prepared');
+ expect(codes(doc.warnings)).toEqual([CODE]);
+ expect(hermes.stderr).toContain(CODE);
+ const cc = json((await runCli(['connect', 'https://brain.example.ts.net/mcp', '--harness', 'claude-code', '--credentials-file', file, '--json'], { env: b.env, cwd: b.root })).stdout);
+ expect(cc?.warnings).toBeUndefined();
+ }, 60_000);
+});
+
+describe('brain routes on a repo-less keyless brain', () => {
+ const page = (title: string) => `---\ntitle: "${title}"\ntype: slack\n---\nhello\n`;
+ async function brain(titles: string[]) {
+ const b = box();
+ expect((await runCli(['init', '--pglite', '--no-embedding', '--non-interactive'], { env: b.env, cwd: b.root, timeoutMs: 120_000 })).exitCode).toBe(0);
+ for (const [i, title] of titles.entries()) {
+ const file = join(b.root, `p${i}.md`);
+ writeFileSync(file, page(title));
+ const put = Bun.spawnSync(['sh', '-c', `'${process.execPath}' '${join(import.meta.dir, '..', 'src', 'cli.ts')}' put chats/p${i} < '${file}'`], { env: Object.fromEntries(Object.entries({ ...process.env, ...b.env }).filter(([, v]) => v !== undefined)) as Record<string, string> });
+ expect(put.exitCode).toBe(0);
+ }
+ return b;
+ }
+
+ test('auth create, register-client, mcp grant and doctor all flag chat from two channels in default', async () => {
+ const b = await brain(['#alpha-team, Jul 2', '#beta-team, Jul 3']);
+ const token = await runCli(['auth', 'create', 'team-bot'], { env: b.env, cwd: b.root });
+ expect(token.stdout).toMatch(/gbrain_[0-9a-f]+/);
+ expect(token.stdout).not.toContain(CODE);
+ expect(token.stderr).toContain('The token "team-bot" is not scoped to a person (it reads chat from 2 channels in default)');
+ expect(token.stderr).toContain('the chat sits in one source (default)');
+ const client = await runCli(['auth', 'register-client', 'team-client'], { env: b.env, cwd: b.root });
+ expect(client.stdout).toContain('Client ID:');
+ expect(client.stderr).toContain(CODE);
+ const grant = await runCli(['mcp', 'grant', 'laptop', '--harness', 'claude-code', '--source', 'default', '--url', 'https://brain.example.ts.net/mcp', '--dry-run', '--json'], { env: b.env, cwd: b.root });
+ const receipt = json(grant.stdout);
+ expect(receipt?.status).toBe('preview');
+ expect(codes(receipt.warnings)).toEqual([CODE]);
+ const doctor = json((await runCli(['doctor', '--only', CODE, '--json'], { env: b.env, cwd: b.root, timeoutMs: 120_000 })).stdout);
+ const check = doctor?.checks?.find((c: any) => c.name === CODE);
+ expect(check?.status).toBe('warn');
+ expect(check.fix.next).toBe('ask_user');
+ }, 240_000);
+
+ test('a brain whose chat comes from one channel mints a token silently', async () => {
+ const b = await brain(['#alpha-team, Jul 2', '#alpha-team, Jul 3']);
+ const token = await runCli(['auth', 'create', 'solo-bot'], { env: b.env, cwd: b.root });
+ expect(token.stdout).toMatch(/gbrain_[0-9a-f]+/);
+ expect(token.stderr).not.toContain(CODE);
+ }, 240_000);
+});
diff --git a/test/shared-exposure.test.ts b/test/shared-exposure.test.ts
new file mode 100644
index 0000000000..3ee49fb0d2
--- /dev/null
+++ b/test/shared-exposure.test.ts
@@ -0,0 +1,225 @@
+/**
+ * GST-363: the shared-token exposure detection (src/core/grants/shared-exposure.ts)
+ * and the doctor check built on it (unscoped_multi_user_token). Every brain
+ * here is an in-memory PGLite brain with no repository: sources are added
+ * without a path, so the repo-less default install is the case under test.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { insertUnifiedToken } from '../src/core/token-mint.ts';
+import { grantFromTokenRow } from '../src/core/grants/model.ts';
+import {
+ BOT_HARNESSES, CHAT_PAGE_TYPES, botHarnessForWorkspace, chatChannelCensus, claudeCodeChannelPlugins, credentialReadSources,
+ exposureFix, exposureReasons, sharedTokenNotice, stdioReadSources,
+} from '../src/core/grants/shared-exposure.ts';
+import { unscopedMultiUserTokenEntry } from '../src/commands/doctor/checks/unscoped-multi-user-token.ts';
+import { categorizeCheck } from '../src/core/doctor-categories.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { withEnv } from './helpers/with-env.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+
+let engine: PGLiteEngine;
+const roots: string[] = [];
+const tmp = () => { const d = mkdtempSync(join(tmpdir(), 'gbrain-shared-exposure-')); roots.push(d); return d; };
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { if (engine) await engine.disconnect(); for (const r of roots) rmSync(r, { recursive: true, force: true }); }, 60_000);
+
+async function reset() {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw('DELETE FROM access_tokens');
+ await engine.executeRaw('DELETE FROM oauth_clients');
+ await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");
+ await engine.setConfig('search.remote_private_pages', 'hidden');
+ __resetPrivateVisibilityCacheForTests();
+}
+const chat = (slug: string, title: string, frontmatter: Record<string, unknown> = {}, type = 'slack', sourceId = 'default') =>
+ engine.putPage(slug, { type: type as any, title, compiled_truth: 'hello', frontmatter }, { sourceId } as any);
+async function token(name: string, sources?: string[]) {
+ const [row] = await insertUnifiedToken(engine, { name, tokenHash: `hash-${name}`, grant: {
+ sources: sources ? (sources.length === 1 ? { kind: 'scalar', writeSource: sources[0]! } : { kind: 'federated', writeSource: sources[0]!, readSources: sources }) : { kind: 'default' },
+ takesHolders: ['world'], allowedOperations: null } });
+ const [full] = await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE id = $1', [row!.id]);
+ return grantFromTokenRow(full!);
+}
+const doctor = async (extra: Partial<DoctorContext> = {}, home = tmp()) =>
+ withEnv({ GBRAIN_HOME: home, HOME: home, CLAUDE_CONFIG_DIR: join(home, '.claude') }, async () =>
+ (await unscopedMultiUserTokenEntry.run({ engine, args: [], ...extra } as DoctorContext) as any[])[0]);
+
+describe('chat census', () => {
+ test('channels come from frontmatter, a #title, or the source; deleted and private pages do not count', async () => {
+ await reset();
+ await chat('chats/a1', '#alpha-team, Jul 2');
+ await chat('chats/a2', '#Alpha-Team, Jul 3');
+ await chat('chats/b1', 'Standup notes', { channel: 'beta' });
+ await chat('chats/x', '#gamma, Jul 4', { visibility: 'private' });
+ await chat('chats/gone', '#delta, Jul 5');
+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug = 'chats/gone'");
+ await engine.putPage('notes/n', { type: 'note' as any, title: '#not-chat', compiled_truth: 'x' });
+ const c = await chatChannelCensus(engine, ['default']);
+ expect(c).toEqual({ sources: ['default'], chat_pages: 3, channels: 2, chat_sources: ['default'] });
+ await engine.setConfig('search.remote_private_pages', 'visible');
+ __resetPrivateVisibilityCacheForTests();
+ expect((await chatChannelCensus(engine, ['default'])).channels).toBe(3);
+ });
+
+ test('unlabelled chat in one source is one channel; each DM page is its own channel', async () => {
+ await reset();
+ await chat('chats/u1', 'Jul 2 log');
+ await chat('chats/u2', 'Jul 3 log');
+ expect((await chatChannelCensus(engine, ['default'])).channels).toBe(1);
+ await chat('dms/d1', 'DMs Jul 2', {}, 'slack-dm-day');
+ await chat('dms/d2', 'DMs Jul 3', {}, 'slack-dm-day');
+ expect((await chatChannelCensus(engine, ['default'])).channels).toBe(3);
+ expect(CHAT_PAGE_TYPES).toContain('slack-thread');
+ });
+
+ test('the census counts only the sources it is given', async () => {
+ await reset();
+ await runSources(engine, ['add', 'chan-a', '--no-federated']);
+ await runSources(engine, ['add', 'chan-b', '--no-federated']);
+ await chat('chats/a', 'A log', {}, 'slack', 'chan-a');
+ await chat('chats/b', 'B log', {}, 'slack', 'chan-b');
+ expect((await chatChannelCensus(engine, ['chan-a'])).channels).toBe(1);
+ expect(await chatChannelCensus(engine, ['chan-a', 'chan-b'])).toMatchObject({ channels: 2, chat_sources: ['chan-a', 'chan-b'] });
+ expect((await chatChannelCensus(engine, [])).channels).toBe(0);
+ });
+});
+
+describe('read sets', () => {
+ test('an unscoped legacy token reads default plus every federated source; scalar and federated grants read what they name', async () => {
+ await reset();
+ await runSources(engine, ['add', 'fed-a', '--federated']);
+ await runSources(engine, ['add', 'solo', '--no-federated']);
+ expect((await credentialReadSources(engine, await token('open'))).sort()).toEqual(['default', 'fed-a']);
+ expect(await credentialReadSources(engine, await token('one', ['solo']))).toEqual(['solo']);
+ expect(await credentialReadSources(engine, await token('two', ['solo', 'fed-a']))).toEqual(['solo', 'fed-a']);
+ });
+
+ test('an unscoped OAuth client reads default only, a client without read scope nothing', async () => {
+ await reset();
+ await runSources(engine, ['add', 'fed-a', '--federated']);
+ const client = { principal: { kind: 'oauth_client' as const, id: 'c1' }, scopes: ['read'], sources: { kind: 'default' as const } };
+ expect(await credentialReadSources(engine, client)).toEqual(['default']);
+ expect(await credentialReadSources(engine, { ...client, scopes: ['write_only_scope_x'] })).toEqual([]);
+ });
+
+ test('a stdio server pinned with GBRAIN_SOURCE reads that source alone', async () => {
+ await reset();
+ await runSources(engine, ['add', 'fed-a', '--federated']);
+ expect((await withEnv({ GBRAIN_SOURCE: undefined }, () => stdioReadSources(engine, tmp()))).sort()).toEqual(['default', 'fed-a']);
+ expect(await withEnv({ GBRAIN_SOURCE: 'fed-a' }, () => stdioReadSources(engine, tmp()))).toEqual(['fed-a']);
+ });
+});
+
+describe('signals and the warning', () => {
+ test('reasons: bot harness, channel plugin, multi-channel chat', () => {
+ const two = { sources: ['default'], chat_pages: 2, channels: 2, chat_sources: ['default'] };
+ expect(exposureReasons({ harness: 'claude-code' })).toEqual([]);
+ for (const h of BOT_HARNESSES) expect(exposureReasons({ harness: h })).toEqual(['bot_harness']);
+ expect(exposureReasons({ channelPlugins: ['telegram@claude-plugins-official'], census: two })).toEqual(['channel_plugin', 'multi_channel_chat']);
+ expect(exposureReasons({ census: { ...two, channels: 1 } })).toEqual([]);
+ });
+
+ test('chat split across sources gets the rescope fix; chat inside one source gets no rescope command', () => {
+ const across = { sources: ['a', 'b'], chat_pages: 2, channels: 2, chat_sources: ['a', 'b'] };
+ const within = { sources: ['default'], chat_pages: 2, channels: 2, chat_sources: ['default'] };
+ const split = sharedTokenNotice({ kind: 'legacy_token', name: 'bot' }, { census: across })!;
+ expect(split.code).toBe('unscoped_multi_user_token');
+ expect(split.kind).toBe('safety');
+ expect(split.why).toContain('another person\'s messages');
+ expect(split.why).toContain('gbrain auth rescope --token bot --sources <source>');
+ expect(split.why).toContain('gbrain sources unfederate <id>');
+ expect(split.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'auth', 'rescope', '--token', 'bot', '--sources', '<source>'], consent: ['credentials'] });
+ const one = sharedTokenNotice({ kind: 'oauth_client', id: 'c1' }, { census: within })!;
+ expect(one.why).toContain('the chat sits in one source (default), so a source grant cannot separate it');
+ expect(one.why).not.toContain('auth rescope');
+ expect(one.fix!.argv).toBeUndefined();
+ for (const n of [split, one]) {
+ expect(n.why).toContain('visibility: private');
+ expect(n.why).toContain('source_ids on search and query (MCP) or --source (CLI)');
+ expect(n.why).toContain('gbrain auth create <name> --member <id>) arrive with gbrain#7812');
+ expect(n.user_message).toBe(n.fix!.user_message);
+ }
+ const bot = sharedTokenNotice({ kind: 'stdio', harness: 'hermes' }, { harness: 'hermes' })!;
+ expect(bot.why).toContain('GBRAIN_SOURCE=<source>');
+ expect(sharedTokenNotice({ kind: 'stdio', harness: 'claude-code' }, { harness: 'claude-code' })).toBeNull();
+ expect(exposureFix({ kind: 'stdio', harness: 'hermes' }).argv).toBeUndefined();
+ });
+
+ test('Claude Code channel plugins and bot workspaces are read from config paths', () => {
+ const dir = tmp();
+ expect(claudeCodeChannelPlugins(dir)).toEqual([]);
+ writeFileSync(join(dir, 'settings.json'), JSON.stringify({ enabledPlugins: { 'telegram@claude-plugins-official': true, 'discord@x': false, 'github@x': true } }));
+ expect(claudeCodeChannelPlugins(dir)).toEqual(['telegram@claude-plugins-official']);
+ writeFileSync(join(dir, 'settings.json'), '{not json');
+ expect(claudeCodeChannelPlugins(dir)).toEqual([]);
+ const home = tmp();
+ withEnv({ HERMES_HOME: undefined }, () => {
+ expect(botHarnessForWorkspace(join(home, '.openclaw', 'workspace'), home)).toBe('openclaw');
+ expect(botHarnessForWorkspace(join(home, '.openclaw-work', 'ws'), home)).toBe('openclaw');
+ expect(botHarnessForWorkspace(join(home, '.hermes'), home)).toBe('hermes');
+ expect(botHarnessForWorkspace(join(home, 'projects', 'repo'), home)).toBeNull();
+ });
+ });
+});
+
+describe('doctor unscoped_multi_user_token', () => {
+ test('an unscoped token over chat from two channels warns with an ask-user fix; scoping it to one channel source clears it', async () => {
+ await reset();
+ await runSources(engine, ['add', 'chan-a', '--federated']);
+ await runSources(engine, ['add', 'chan-b', '--federated']);
+ await chat('chats/a', '#alpha, Jul 2', {}, 'slack', 'chan-a');
+ await chat('chats/b', '#beta, Jul 2', {}, 'slack', 'chan-b');
+ await token('team-bot');
+ const warn = await doctor();
+ expect(warn.status).toBe('warn');
+ expect(warn.message).toContain('The token "team-bot" reaches 2 channels in chan-a, chan-b');
+ expect(warn.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'auth', 'rescope', '--token', 'team-bot', '--sources', '<source>'] });
+ expect(categorizeCheck('unscoped_multi_user_token')).toBeDefined();
+ await engine.executeRaw('DELETE FROM access_tokens');
+ await token('team-bot', ['chan-a']);
+ expect((await doctor()).status).toBe('ok');
+ });
+
+ test('a remote caller gets a count, never credential names', async () => {
+ await reset();
+ await chat('chats/a', '#alpha, Jul 2');
+ await chat('chats/b', '#beta, Jul 2');
+ await token('team-bot');
+ const remote = await doctor({ remote: true });
+ expect(remote.status).toBe('warn');
+ expect(remote.message).not.toContain('team-bot');
+ expect(remote.details).toEqual({ flagged_count: 1 });
+ expect(remote.fix).toBeUndefined();
+ });
+
+ test('a wired bot harness with no multi-channel chat is information; with it, a warning', async () => {
+ await reset();
+ const home = tmp();
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'agent-instructions.json'), JSON.stringify({ entries: [{ harness: 'hermes', path: join(home, '.hermes', 'SOUL.md'), status: 'installed', block_version: 1, access: { kind: 'mcp', server: 'gbrain' }, writer: 'gbrain setup hermes' }] }));
+ const info = await doctor({}, home);
+ expect(info).toMatchObject({ status: 'ok', severity: 'info' });
+ expect(info.message).toContain('hermes serves a chat agent');
+ await chat('chats/a', '#alpha, Jul 2');
+ await chat('chats/b', '#beta, Jul 2');
+ const warn = await doctor({}, home);
+ expect(warn.status).toBe('warn');
+ expect(warn.message).toContain('The gbrain access hermes uses reaches 2 channels');
+ });
+
+ test('a brain with no chat and no credentials is ok', async () => {
+ await reset();
+ await token('laptop');
+ expect(await doctor()).toMatchObject({ status: 'ok' });
+ });
+});