Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(grants): point the unscoped-token warning at master's per-member access
garrytan902e65f7141e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 30d04724f8..d1e6a4784f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,9 +12,9 @@ identifiers and attribution are available in the pre-removal Git revision## [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.+**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. A credential reads the same pages whoever talks to its agent (an unbound one everything its grant reaches, one bound to a member what that member may read), so gbrain 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.+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 (a one-source grant, `sources unfederate`, `GBRAIN_SOURCE` for a stdio agent, `visibility: private`, a credential bound to each person with `gbrain auth create <name> --member <id>`, or one shared agent with `--may-act-for` and a per-request audience), says plainly when the chat sits in one source and no source grant can separate it, and says that `source_ids` narrows only the call that sends it. A credential holding `--may-act-for` is not flagged. 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 changesdiff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex e3004abfbe..03146d87d1 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -9,7 +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/shared-exposure.ts` + `src/commands/doctor/checks/unscoped-multi-user-token.ts` — GST-363 warning when one credential that reads the same pages whoever asks (unbound, or bound to one member) serves an agent several people use; a credential holding `may_act_for` is skipped (auth create, register-client and the doctor check). 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, then the per-person setups: a credential bound to each member, or `--may-act-for` with a per-request audience); `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.mdindex 130f0efed0..ead0cdf3d8 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -377,11 +377,12 @@ 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+A credential reads the same pages whoever talks to its agent: an unbound one+everything its grant reaches, one bound to a member what that member may read.+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) through+such a credential can answer one person with pages only another person may+read. In a measured multi-user pilot withone unscoped bot token, telling the agent that gbrain was live lowered passrates by 9 to 21 points, and every added cross-scope failure cited a channelpage the bot grant returned.@@ -403,7 +404,9 @@ the page's `channel`, `chat` or `conversation` frontmatter, a leading`#name` in its title, or else its source; every DM page counts as its ownchannel. The warning goes to stderr (an `[AGENT]` block when stdout is not aterminal) and into the `notices` or `warnings` list of a `--json` result.-It never changes a grant or an exit code.+It never changes a grant or an exit code. A credential holding+`--may-act-for` is not flagged: its reads follow the audience its harness+names.`gbrain doctor --only unscoped_multi_user_token` runs the same detection overevery active token and OAuth client, and over the local agents setup wired: it@@ -421,13 +424,19 @@ Fix it with today's commands:- For a local stdio agent, set `GBRAIN_SOURCE=<source>` in its MCP serverenvironment.- 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).+ the pages nobody else may see `visibility: private`. That hides them from+ the agent only while its access may not read private pages.- Don't rely on `source_ids`: it narrows only the call that sends it, sorecall, list_pages or any read without it reads the token's full grant.- The fix is a member-bound or rescoped token (`gbrain auth rescope …`).--Per-member keys arrive with gbrain#7812.+ The fix is a narrower grant (`gbrain auth rescope …`) or per-person access.+- Per-person access: give each person's agent its own credential bound to+ them (`gbrain access member add <id>`, then+ `gbrain auth create <name> --member <id>`) and put `readable_by` on pages+ only some people may read. One agent in a shared channel instead uses a+ credential made with `gbrain auth create <name> --may-act-for <members>`,+ and its harness names each request's audience (see+ [above](#inspect-clients-and-edit-access)). Never bind a shared agent's credential to one+ person: it then reads as that person for everyone who talks to it.## Dashboard API keysdiff --git a/src/commands/auth.ts b/src/commands/auth.tsindex fb9a16368e..61336aa3a4 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -126,7 +126,7 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: stconsole.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) }));+ if (!opts.binding?.mayActFor?.length) writeExposureNotice(sharedTokenNotice({ kind: 'legacy_token', name }, { census: await credentialCensus(engine, grant) }));});} catch (e: any) {if (e instanceof OperationError) exitCliError(e, 'auth');@@ -809,7 +809,7 @@ async function registerClient(name: string, args: string[]) {}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) }));+ if (grant && !binding.patch?.mayActFor?.length) 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.tsindex 0e1319455d..273e326b9e 100644--- a/src/commands/doctor/checks/unscoped-multi-user-token.ts+++ b/src/commands/doctor/checks/unscoped-multi-user-token.ts@@ -1,6 +1,7 @@/*** 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.+ * agents that can read chat from several channels and read the same pages+ * whoever talks to their agent (unbound, or bound to one member).* 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@@ -9,8 +10,9 @@* 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.+ * no such chat in reach is reported as information, so a brain with nothing+ * to separate yet is not marked unhealthy. A credential holding --may-act-for+ * is skipped: its reads follow the audience its harness names.* A remote caller (run_doctor only) gets counts, never credential names.*/import { grantFromClient, grantFromRow, grantFromTokenRow, type PrincipalGrant } from '../../../core/grants/model.ts';@@ -32,10 +34,13 @@ async function runUnscopedMultiUserToken(ctx: DoctorContext): Promise<Check[]> {return memo.get(key)!;};const credentials: Array<{ subject: ExposureSubject; grant: PrincipalGrant }> = [];+ const actsForAudience = (row: Record<string, unknown>) => Array.isArray(row.may_act_for) && row.may_act_for.length > 0;for (const row of await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE revoked_at IS NULL ORDER BY created_at, id')) {+ if (actsForAudience(row)) continue;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')) {+ if (actsForAudience(row)) continue;const grant = grantFromRow(row);credentials.push({ subject: { kind: 'oauth_client', id: grant.clientId, name: grant.clientName || undefined }, grant: grantFromClient(grant) });}@@ -66,11 +71,11 @@ async function runUnscopedMultiUserToken(ctx: DoctorContext): Promise<Check[]> {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. `+ message: `${bots.join(', ')} serve${bots.length === 1 ? 's' : ''} a chat agent from this brain that reads the same pages whoever talks to it; 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.' });+ checks.push({ name: 'unscoped_multi_user_token', status: 'ok', message: 'No credential or local agent that reads the same pages for everyone can read chat from several channels.' });}return checks;}@@ -78,8 +83,8 @@ async function runUnscopedMultiUserToken(ctx: DoctorContext): Promise<Check[]> {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} credential(s) can read chat from several channels and read the same pages whoever talks to their agent, 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 and read the same pages whoever talks to their agent: ${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) }),diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex c328b1bb3f..0674ada8aa 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -432,7 +432,7 @@ 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.+ // GST-363: credentials or local bot agents reading chat from several channels the same way for everyone who talks to their agent.'unscoped_multi_user_token','reranker_health','rls',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 29fd53d9e9..3ff068d516 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -953,7 +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' },+ 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 that reads the same pages whoever talks to 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 the fixes (a one-source grant, gbrain sources unfederate, visibility: private, a credential bound to each person, or one shared agent with may_act_for and a per-request audience); a credential holding may_act_for is not flagged; 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.tsindex d97b8083dd..b6c07884b6 100644--- a/src/core/grants/shared-exposure.ts+++ b/src/core/grants/shared-exposure.ts@@ -1,9 +1,12 @@/**- * 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.+ * GST-363 (HARN-13 host-harness pilot, harness-evals#145): one credential that+ * reads the same pages whoever talks to its agent (unbound, or bound to one+ * member), serving an agent that several people talk to, lets the agent answer+ * one person with pages only another person may read. The install routes and+ * doctor warn and name the per-person setups (a credential bound to each+ * person, or --may-act-for with a per-request audience). Nothing here changes a+ * grant. A credential holding --may-act-for is not flagged: its reads follow+ * the audience its harness names.** A serve is likely multi-user when any signal holds:* - `bot_harness`: the harness is a channel or bot agent (BOT_HARNESSES);@@ -162,9 +165,14 @@ function reach(reasons: readonly ExposureReason[], census: ChatCensus | null | ureturn parts.join('; ');}+/** The per-person setup: a credential per person, or one shared agent reading as each request's audience. */+const PER_PERSON = 'Per-person access: give each person\'s agent its own credential bound to them (gbrain access member add <id>, then gbrain auth create <name> --member <id>) and put readable_by on pages only some people may read; '+ + 'one agent in a shared channel instead uses a credential made with gbrain auth create <name> --may-act-for <members>, and its harness names each request\'s audience. '+ + 'Never bind a shared agent\'s credential to one person: it then reads as that person for everyone who talks to it.';+/**- * 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.+ * Today's fixes, chosen by where the chat lives, then the per-person setup.+ * One string so every route prints the same commands.*/export function remedyText(s: ExposureSubject, census?: ChatCensus | null): string {const steps: string[] = [];@@ -176,8 +184,8 @@ export function remedyText(s: ExposureSubject, census?: ChatCensus | null): stri} 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)');- return `Fix: ${steps.join('; ')}. source_ids narrows only the call that sends it, so recall, list_pages or any read without it reads the token's full grant; the fix is ${splitBySource(census) ? 'a member-bound or rescoped token (gbrain auth rescope …)' : 'a member-bound token'}, not per-call narrowing. Per-member keys arrive with gbrain#7812 and are not in this version.`;+ steps.push('mark pages nobody else may see visibility: private (hidden from this agent unless its access may read private pages)');+ return `Fix: ${steps.join('; ')}. source_ids narrows only the call that sends it, so recall, list_pages or any read without it reads the token's full grant; the fix is ${splitBySource(census) ? 'a narrower grant (gbrain auth rescope …) or per-person access' : 'per-person access'}, not per-call narrowing. ${PER_PERSON}`;}export function exposureFix(s: ExposureSubject, census?: ChatCensus | null): Action {@@ -190,7 +198,7 @@ export function exposureFix(s: ExposureSubject, census?: ChatCensus | null): Actwhy: '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 };+ why: 'Scoping this agent is the user\'s choice: a credential per person, a shared-channel audience, one source, private pages or a narrower deployment.', user_message: message };}/** The install-time warning. Null when no signal holds. */@@ -200,8 +208,8 @@ export function sharedTokenNotice(s: ExposureSubject, input: { harness?: string;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. '+ why: `WARNING: ${subjectLabel(s)} reads the same pages whoever talks to its agent (${reach(reasons, input.census, input.channelPlugins)}). `+ + 'An agent using it shows everyone what it can read, so when several people talk to the agent it may answer one person with another person\'s messages. '+ remedyText(s, input.census),};}diff --git a/test/shared-exposure-routes.test.ts b/test/shared-exposure-routes.test.tsindex c4cd3c8dba..7c60767331 100644--- a/test/shared-exposure-routes.test.ts+++ b/test/shared-exposure-routes.test.ts@@ -116,8 +116,12 @@ describe('brain routes on a repo-less keyless brain', () => {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 token "team-bot" reads the same pages whoever talks to its agent (it reads chat from 2 channels in default)');expect(token.stderr).toContain('the chat sits in one source (default)');+ expect((await runCli(['access', 'member', 'add', 'alice-example'], { env: b.env, cwd: b.root })).exitCode).toBe(0);+ const audience = await runCli(['auth', 'create', 'channel-bot', '--may-act-for', 'alice-example'], { env: b.env, cwd: b.root });+ expect(audience.stdout).toMatch(/gbrain_[0-9a-f]+/);+ expect(audience.stderr).not.toContain(CODE);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);diff --git a/test/shared-exposure.test.ts b/test/shared-exposure.test.tsindex 0ffc85e3a4..f79e41d655 100644--- a/test/shared-exposure.test.ts+++ b/test/shared-exposure.test.ts@@ -142,19 +142,26 @@ describe('signals and the warning', () => {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.why).toContain('the fix is a member-bound token, not per-call narrowing');- expect(split.why).toContain('the fix is a member-bound or rescoped token (gbrain auth rescope …), not per-call narrowing');+ expect(one.why).toContain('the fix is per-person access, not per-call narrowing');+ expect(split.why).toContain('the fix is a narrower grant (gbrain auth rescope …) or per-person access, not per-call narrowing');+ expect(one.why).toContain('gbrain auth create <name> --may-act-for <members>');expect(one.fix!.argv).toBeUndefined();for (const n of [split, one]) {- expect(n.why).toContain('visibility: private');+ expect(n.why).toContain('visibility: private (hidden from this agent unless its access may read private pages)');+ expect(n.why).not.toContain('hidden from every remote caller');+ expect(n.why).toMatch(/reads the same pages whoever talks to its agent/);+ expect(n.why).not.toContain('not scoped to a person');expect(n.why).toContain('source_ids narrows only the call that sends it, so recall, list_pages or any read without it reads the token\'s full grant');expect(n.why).not.toContain('narrow single calls');- expect(n.why).toContain('Per-member keys arrive with gbrain#7812 and are not in this version.');- expect(n.why).not.toContain('gbrain access');+ expect(n.why).toContain('gbrain access member add <id>, then gbrain auth create <name> --member <id>');+ expect(n.why).toContain('Never bind a shared agent\'s credential to one person: it then reads as that person for everyone who talks to it.');+ expect(n.why).not.toContain('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(bot.why).toContain('gbrain auth create <name> --member <id>');+ expect(exposureFix({ kind: 'stdio', harness: 'hermes' }).why).not.toContain('cannot tell');expect(sharedTokenNotice({ kind: 'stdio', harness: 'claude-code' }, { harness: 'claude-code' })).toBeNull();expect(exposureFix({ kind: 'stdio', harness: 'hermes' }).argv).toBeUndefined();});@@ -221,6 +228,22 @@ describe('doctor unscoped_multi_user_token', () => {expect(warn.message).toContain('The gbrain access hermes uses reaches 2 channels');});+ test('a credential holding may_act_for is not flagged; a member-bound one still is', async () => {+ await reset();+ await chat('chats/a', '#alpha, Jul 2');+ await chat('chats/b', '#beta, Jul 2');+ await engine.executeRaw("INSERT INTO access_members (id) VALUES ('alice-example') ON CONFLICT DO NOTHING");+ const bound = await token('alice-bot');+ await engine.executeRaw("UPDATE access_tokens SET member_id = 'alice-example' WHERE id = $1", [bound.principal.id]);+ const shared = await token('channel-bot');+ await engine.executeRaw("UPDATE access_tokens SET may_act_for = ARRAY['member:alice-example']::text[] WHERE id = $1", [shared.principal.id]);+ const check = await doctor();+ expect(check.status).toBe('warn');+ expect(check.message).toContain('1 credential(s)');+ expect(check.message).toContain('The token "alice-bot" reaches 2 channels');+ expect(JSON.stringify(check.details)).not.toContain('channel-bot');+ });+test('a brain with no chat and no credentials is ok', async () => {await reset();await token('laptop');