Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(auth): private_pages grant axis on access tokens and OAuth clients (GBRA-156)

garrytan1f9cf3c86c55
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index a44bbe6141..edb1d743bb 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -32,7 +32,7 @@ import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';
import { sqlQueryForEngine, type SqlQuery } from '../core/sql-query.ts';
import { readClientGrant, rescopeClientGrant, resolveGrantProfile, type GrantPatch } from '../core/grants/service.ts';
import { parseClientRescopeArgs, parseRescopeGrantArgs, splitRescopeTarget, type RescopeGrantArgs } from '../core/grants/cli.ts';
-import { GRANT_PROFILES, GrantError, TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, grantFromClient, type ClientGrant } from '../core/grants/model.ts';
+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 { migrateLegacyTokens, parseRescopeTokenArgs, renderLegacyGrantAxis, rescopeLegacyToken, resolveRescopeTarget, type MigrateLegacyResult, type RescopeTokenResult } from '../core/grants/legacy-token.ts';
@@ -158,6 +158,11 @@ async function permissions(name: string, action: string, value: string | undefin
/** Render a token row's scope grant honestly (#4043: NULL = grandfathered).
* Routes through the SAME normalizer the verify path uses — the ops surface
* must never claim admin on a row the serve actually scopes or denies. */
+/** GBRA-156: the private-pages axis as `auth list`, `auth clients` and `auth rescope` print it. */
+export function renderPrivatePages(mode: PrivatePagesGrant | undefined): string {
+ return mode === 'granted_sources' ? 'granted-sources (private pages in the sources this grant names)' : 'none';
+}
+
export function renderTokenScopes(scopes: unknown): string {
const normalized = normalizeTokenScopes(scopes);
if (normalized === undefined) return 'admin (grandfathered)';
@@ -165,27 +170,34 @@ export function renderTokenScopes(scopes: unknown): string {
return normalized.join(',');
}
-async function list() {
+async function list(json: boolean) {
await withConfiguredSql(async (sql) => {
+ // SELECT * reads every schema generation (private_pages arrives with GBRA-156's migration; absent reads as none).
const rows = await sql`
- SELECT id, name, scopes, created_at, last_used_at, revoked_at
- FROM access_tokens
+ SELECT * FROM access_tokens
ORDER BY created_at DESC
`;
+ if (json) {
+ console.log(JSON.stringify(rows.map(r => ({
+ id: String(r.id), name: r.name, scopes: renderTokenScopes(r.scopes), created_at: r.created_at, last_used_at: r.last_used_at ?? null,
+ status: r.revoked_at ? 'revoked' : 'active', private_pages: privatePagesFromColumn(r.private_pages),
+ })), null, 2));
+ return;
+ }
if (rows.length === 0) {
console.log('No tokens found. Create one: gbrain auth create "my-client"');
return;
}
- console.log('ID Name Scopes Created Last Used Status');
- console.log('─'.repeat(126));
+ console.log('ID Name Scopes Created Last Used Status Private pages');
+ console.log('─'.repeat(141));
for (const r of rows) {
const id = String(r.id).padEnd(36);
const name = (r.name as string).padEnd(20);
const scopes = renderTokenScopes(r.scopes).padEnd(21);
const created = new Date(r.created_at as string).toISOString().slice(0, 19);
const lastUsed = r.last_used_at ? new Date(r.last_used_at as string).toISOString().slice(0, 19) : 'never'.padEnd(19);
- const status = r.revoked_at ? 'REVOKED' : 'active';
- console.log(`${id} ${name} ${scopes} ${created} ${lastUsed} ${status}`);
+ const status = (r.revoked_at ? 'REVOKED' : 'active').padEnd(7);
+ console.log(`${id} ${name} ${scopes} ${created} ${lastUsed} ${status} ${renderPrivatePages(privatePagesFromColumn(r.private_pages))}`);
}
});
}
@@ -887,6 +899,7 @@ function printClientGrantAxes(grant: ClientGrant) {
console.log(` Write source: ${grant.sourcesNone ? 'none (every read and write refused)' : grant.sourceId}`);
console.log(` Federated reads: ${grant.federatedRead.join(', ') || '<none>'}`);
console.log(` Takes holders: ${grant.takesHolders === null ? 'world (default)' : grant.takesHolders.join(', ') || 'none (every take hidden)'}`);
+ console.log(` Private pages: ${renderPrivatePages(grant.privatePages)}`);
console.log(` Tool surface: ${grant.surface ?? '<server default>'}`);
console.log(` Delegated spending: ${grant.budgetUsdPerDay === null ? 'unlimited' : '$' + grant.budgetUsdPerDay + '/day'}`);
}
@@ -895,12 +908,16 @@ function printTokenRescope(result: RescopeTokenResult, json: boolean) {
if (json) { console.log(JSON.stringify(result, null, 2)); return; }
const verb = !result.changed ? 'grants' : result.dryRun ? 'grant preview' : 'rescoped';
console.log(`Legacy token ${verb}: ${result.name} (${result.id})`);
- const rows: Array<[string, keyof typeof result.before]> = [['Sources', 'sources'], ['Takes holders', 'takesHolders'], ['Operations', 'operations']];
+ const rows: Array<[string, 'sources' | 'takesHolders' | 'operations']> = [['Sources', 'sources'], ['Takes holders', 'takesHolders'], ['Operations', 'operations']];
for (const [label, key] of rows) {
const before = renderLegacyGrantAxis(result.before[key]);
const after = renderLegacyGrantAxis(result.after[key]);
console.log(` ${label}: ${before === after ? after : `${before} -> ${after}`}`);
}
+ if (result.before.privatePages || result.after.privatePages) {
+ const [ppBefore, ppAfter] = [renderPrivatePages(result.before.privatePages), renderPrivatePages(result.after.privatePages)];
+ console.log(` Private pages: ${ppBefore === ppAfter ? ppAfter : `${ppBefore} -> ${ppAfter}`}`);
+ }
console.log(` Grant revision: ${result.revision.before === result.revision.after ? result.revision.after : `${result.revision.before} -> ${result.revision.after}`}`);
if (result.drift.length && !result.written) {
console.log(` Drift: ${result.drift.join(', ')} deny every request (the permissions JSON disagrees with the grant columns). `
@@ -982,6 +999,8 @@ export interface ClientRow {
allowed_operations?: string[] | null;
/** Soft-revoke stamp (`auth` lifecycle revoke); absent on schemas without it. */
deleted_at?: string | Date | null;
+ /** GBRA-156 private-pages axis; absent on schemas without it (reads as none). */
+ private_pages?: string | null;
}
/** The operation-snapshot axis of one client, as `auth clients` reports it. */
@@ -1052,7 +1071,16 @@ export async function listClientRows(engine: BrainEngine): Promise<ClientRow[]>
// The columns each degrade tier drops; any other missing object rethrows.
const isSchemaShapeError = (e: unknown): boolean =>
isMissingSchemaObject(e, 'table', 'oauth_clients') ||
- isMissingSchemaObject(e, 'column', ['allowed_operations', 'deleted_at', 'surface', 'surface_set_by', 'source_id', 'federated_read']);
+ isMissingSchemaObject(e, 'column', ['private_pages', 'allowed_operations', 'deleted_at', 'surface', 'surface_set_by', 'source_id', 'federated_read']);
+ try {
+ return await engine.executeRaw<ClientRow>(
+ `SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read, allowed_operations, deleted_at, private_pages
+ FROM oauth_clients ORDER BY client_name, client_id`,
+ );
+ } catch (e) {
+ // Brain predates the private-pages column: it reads as none.
+ if (!isSchemaShapeError(e)) throw e;
+ }
try {
return await engine.executeRaw<ClientRow>(
`SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read, allowed_operations, deleted_at
@@ -1135,6 +1163,7 @@ async function clientsCmd(args: string[]) {
surface_set_by: c.surface_set_by,
source_id: c.source_id,
federated_read: c.federated_read,
+ private_pages: privatePagesFromColumn(c.private_pages),
...clientOperationsView(c),
revoked_at: c.deleted_at ?? null,
token_lifetime_clamped: lifetimeClamped.has(c.client_id),
@@ -1160,6 +1189,7 @@ async function clientsCmd(args: string[]) {
: '<server/config resolution>';
console.log(` scopes: ${c.scope ?? '<none>'} surface: ${surfaceStr}`);
console.log(` write source: ${c.source_id ?? '<none>'} federated reads: ${(c.federated_read ?? []).join(', ') || '<none>'}`);
+ console.log(` private pages: ${renderPrivatePages(privatePagesFromColumn(c.private_pages))}`);
for (const line of clientOperationsLines(c)) console.log(line);
if (lifetimeClamped.has(c.client_id)) console.log(' access-token lifetime: clamped to the 90-day maximum by an upgrade (docs/mcp/ADMIN.md#access-token-lifetime)');
if (parsed.usage) {
@@ -1259,7 +1289,7 @@ Usage:
memory as you (local CLI only; never via admin API)
gbrain auth set-min-trust <client|token> <tier|none> Set or clear the read floor of an OAuth client (id)
or legacy token (id or name). Local CLI only.
- gbrain auth list List all tokens (id, scopes, usage)
+ gbrain auth list [--json] List all tokens (id, scopes, usage, private pages)
gbrain auth revoke <name> Revoke a legacy token (ALL active rows with that name)
gbrain auth revoke --id <uuid> Revoke exactly one token by id (names are not unique)
gbrain auth rescope --token <name>|--id <uuid>|--client <client_id>|<name> [options]
@@ -1277,6 +1307,10 @@ Usage:
surface allow, including ones later upgrades add; clears
the profile (tokens: --reset-default operations)
--scopes <read,write,...> Replace the scopes
+ --private-pages <granted-sources|none> Remote reads see visibility: private pages in the
+ sources this grant names explicitly (never the
+ no-grant floor, federation, a client's bound source
+ or a request's source_ids); 'none' (default) hides them
--reset-default <sources,takes-holders,operations> Token only: restore the auth create default for those axes
--refresh-operations [--add <op,...>|--all-new] Token only: preview operations added since the snapshot;
widen only by the ones --add names (or all with --all-new)
@@ -1370,7 +1404,7 @@ export async function runAuth(args: string[]): Promise<void> {
return;
}
case 'set-min-trust': await setMinTrustCmd(rest); return;
- case 'list': await list(); return;
+ case 'list': await list(rest.includes('--json')); return;
case 'revoke': {
if (rest[0] === '--id') { await revokeById(rest[1] || ''); return; }
await revoke(rest[0]);
diff --git a/src/commands/serve-http-api-keys.ts b/src/commands/serve-http-api-keys.ts
index 4906af7c16..2892224a18 100644
--- a/src/commands/serve-http-api-keys.ts
+++ b/src/commands/serve-http-api-keys.ts
@@ -118,6 +118,7 @@ function grantView(row: Record<string, unknown>) {
scopes_grandfathered: row.scopes == null,
sources: s.kind === 'default' ? 'default' : s.kind === 'none' ? [] : s.kind === 'scalar' ? [s.writeSource] : [...s.readSources],
takes_holders: grant.takesHolders ?? ['world'],
+ private_pages: grant.privatePages,
};
}
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index 4dbaf8dee3..86377568f6 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -35,7 +35,7 @@ export interface InventoryEntry {
type Row = [table: string, cls: InventoryClass, reason: string, columns: string, probe?: string];
const ROWS: readonly Row[] = [
- ['access_tokens', 'out_of_scope', 'secret_material', 'name token_hash scopes permissions source_grant source_id federated_read allowed_operations takes_holders min_trust'],
+ ['access_tokens', 'out_of_scope', 'secret_material', 'name token_hash scopes permissions source_grant source_id federated_read allowed_operations takes_holders min_trust private_pages'],
['belief_events', 'swept', 'belief_ledger', 'event_key source_id slug subject_kind subject_key event_type origin trust_tier writer_tier tier_basis visibility value value_hash prior_hash state_hash cause claim_fp redacted_fields'],
['belief_page_lifetimes', 'out_of_scope', 'text_free_ledger', 'source_id slug'],
['belief_redactions', 'out_of_scope', 'text_free_ledger', 'source_id subject_key field field_hash released_hash'],
@@ -105,7 +105,7 @@ const ROWS: readonly Row[] = [
['minion_lease_pressure_log', 'out_of_scope', 'no_memory_text', 'lease_key queue_name job_name model provider'],
['minion_self_fix_log', 'out_of_scope', 'no_memory_text', 'classifier_bucket policy_applied outcome'],
['needs_rederive', 'out_of_scope', 'text_free_ledger', 'derived_table derived_id source_id reason'],
- ['oauth_clients', 'out_of_scope', 'secret_material', 'client_id client_secret_hash client_name redirect_uris grant_types scope token_endpoint_auth_method source_id federated_read bound_tools bound_source_id bound_brain_id bound_slug_prefixes surface surface_set_by allowed_operations delegated_slug_prefixes delegated_namespace grant_profile grant_repair_reasons source_grant takes_holders min_trust registered_via'],
+ ['oauth_clients', 'out_of_scope', 'secret_material', 'client_id client_secret_hash client_name redirect_uris grant_types scope token_endpoint_auth_method source_id federated_read bound_tools bound_source_id bound_brain_id bound_slug_prefixes surface surface_set_by allowed_operations delegated_slug_prefixes delegated_namespace grant_profile grant_repair_reasons source_grant takes_holders min_trust registered_via private_pages'],
['oauth_codes', 'out_of_scope', 'secret_material', 'code_hash client_id scopes code_challenge code_challenge_method redirect_uri state resource'],
['oauth_grant_audit', 'out_of_scope', 'no_memory_text', 'client_id actor action before_grant after_grant'],
['oauth_tokens', 'out_of_scope', 'secret_material', 'token_hash token_type client_id scopes resource'],
diff --git a/src/core/grants/cli.ts b/src/core/grants/cli.ts
index d0c614cd8e..c4eb374320 100644
--- a/src/core/grants/cli.ts
+++ b/src/core/grants/cli.ts
@@ -1,4 +1,4 @@
-import { GRANT_PROFILES, GrantError, validatePrincipalGrant, type GrantPatch, type GrantProfileId } from './model.ts';
+import { GRANT_PROFILES, GrantError, validatePrincipalGrant, type GrantPatch, type GrantProfileId, type PrivatePagesGrant } from './model.ts';
import { parseScopeString, assertAllowedScopes } from '../scope.ts';
import { isValidHolder } from '../takes-fence.ts';
@@ -66,6 +66,7 @@ function parseRescopeGrantFlags(args: string[]): RescopeGrantArgs {
if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value))) throw new GrantError('invalid_grant', '--if-version must be a non-negative integer');
result.expectedRevision = Number(value);
break;
+ case '--private-pages': result.patch.privatePages = parsePrivatePagesFlag(value); break;
default: throw new GrantError('invalid_grant', `Unknown flag: ${flag}`);
}
}
@@ -73,6 +74,13 @@ function parseRescopeGrantFlags(args: string[]): RescopeGrantArgs {
return result;
}
+/** `--private-pages granted-sources|none` (GBRA-156). */
+export function parsePrivatePagesFlag(value: string): PrivatePagesGrant {
+ if (value === 'granted-sources') return 'granted_sources';
+ if (value === 'none') return 'none';
+ throw new GrantError('invalid_grant', '--private-pages must be granted-sources or none', ['private_pages_invalid']);
+}
+
/**
* `all`: store no operation snapshot, so the scopes and the surface alone
* decide, including operations later releases add. A null list is valid only
@@ -182,7 +190,7 @@ export function parseClientRescopeArgs(clientId: string, args: string[]): Rescop
const result = parseRescopeGrantFlags(legacy);
if (sources !== undefined) {
validatePrincipalGrant({
- principal: { kind: 'oauth_client', id: clientId }, scopes: [], allowedOperations: null, takesHolders: null, revision: 0,
+ principal: { kind: 'oauth_client', id: clientId }, scopes: [], allowedOperations: null, takesHolders: null, privatePages: 'none', revision: 0,
shape: 'unified', drift: [], permissionsMalformed: false,
sources: sources.length === 0 ? { kind: 'none' } : { kind: 'federated', writeSource: sources[0], readSources: sources },
}, { operationNames: new Set() });
diff --git a/src/core/grants/legacy-token.ts b/src/core/grants/legacy-token.ts
index 766ba52502..5fd25ef067 100644
--- a/src/core/grants/legacy-token.ts
+++ b/src/core/grants/legacy-token.ts
@@ -5,6 +5,8 @@
* - sources (`--sources a,b|none`): element 0 = write source
* - takes holders (`--takes-holders a,b|none`)
* - operations (`--operations a,b|none`, `--refresh-operations`)
+ * - private pages (`--private-pages granted-sources|none`): stored in
+ * `private_pages` only, never in the `permissions` mirror
*
* `none` stores the explicit empty list (deny-all). An omitted flag preserves
* the stored value. `--reset-default <axes>` restores the `auth create`
@@ -32,8 +34,9 @@ import { isUndefinedColumnError } from '../utils.ts';
import { requiresExplicitApproval } from '../ops/execution-prerequisites.ts';
import {
GrantError, LEGACY_GRANT_AXES, grantFromTokenRow, permissionsMirror, tokenGrantColumnValues, tokenGrantFromColumns,
- tokenGrantFromPermissions, validatePrincipalGrant, TOKEN_GRANT_COLUMNS, type LegacyGrantAxis, type PrincipalGrant,
+ tokenGrantFromPermissions, validatePrincipalGrant, TOKEN_GRANT_COLUMNS, type LegacyGrantAxis, type PrincipalGrant, type PrivatePagesGrant,
} from './model.ts';
+import { parsePrivatePagesFlag } from './cli.ts';
export type { LegacyGrantAxis } from './model.ts';
@@ -45,6 +48,7 @@ export interface RescopeTokenArgs {
takesHolders?: string[];
operations?: string[];
scopes?: string[];
+ privatePages?: PrivatePagesGrant;
reset: LegacyGrantAxis[];
refreshOperations: boolean;
add?: string[];
@@ -59,6 +63,8 @@ export interface LegacyTokenGrantView {
sources: string[] | 'default';
takesHolders: string[];
operations: string[] | 'unrestricted';
+ /** Present only when granted, so a 'none' token's view is unchanged. */
+ privatePages?: 'granted_sources';
}
export interface RescopeTokenResult {
@@ -120,6 +126,7 @@ export function parseRescopeTokenArgs(args: string[]): RescopeTokenArgs {
out.operations = csvOrNone(value);
break;
case '--add': out.add = csvOrNone(value); break;
+ case '--private-pages': out.privatePages = parsePrivatePagesFlag(value); break;
case '--scopes':
out.scopes = csvOrNone(value.replaceAll(' ', ','));
if (out.scopes.length === 0) throw new GrantError('invalid_grant', '--scopes needs at least one scope (to cut a token off, use --sources none or gbrain auth revoke)');
@@ -151,12 +158,13 @@ export function parseRescopeTokenArgs(args: string[]): RescopeTokenArgs {
return { target, ...out };
}
-function grantView(g: TokenGrantAxes): LegacyTokenGrantView {
+function grantView(g: TokenGrantAxes & Pick<PrincipalGrant, 'privatePages'>): LegacyTokenGrantView {
const s = g.sources;
return {
sources: s.kind === 'default' ? 'default' : s.kind === 'none' ? [] : s.kind === 'scalar' ? [s.writeSource] : [...s.readSources],
takesHolders: g.takesHolders ?? ['world'],
operations: g.allowedOperations ?? 'unrestricted',
+ ...(g.privatePages === 'granted_sources' ? { privatePages: g.privatePages } : {}),
};
}
@@ -185,7 +193,7 @@ async function assertActiveSources(engine: BrainEngine, ids: string[]): Promise<
const SCHEMA_HINT = 'this brain predates the unified token grant columns (access_tokens.source_grant); run `gbrain apply-migrations --yes` (no user decision needed), then retry';
function schemaError(error: unknown): unknown {
- return ['source_grant', 'grant_revision', ...TOKEN_GRANT_COLUMNS].some(c => isUndefinedColumnError(error, c)) ? new GrantError('grant_schema_required', SCHEMA_HINT) : error;
+ return ['source_grant', 'grant_revision', 'private_pages', ...TOKEN_GRANT_COLUMNS].some(c => isUndefinedColumnError(error, c)) ? new GrantError('grant_schema_required', SCHEMA_HINT) : error;
}
/** Write the unified columns and the `permissions` mirror in one UPDATE; returns the new revision. */
@@ -285,14 +293,19 @@ async function rescopeInTransaction(tx: BrainEngine, args: RescopeTokenArgs): Pr
allowedOperations: opsEdited ? next.allowedOperations : null,
}, { operationNames: all });
- const edits = args.sources !== undefined || args.takesHolders !== undefined || opsEdited || args.reset.length > 0 || args.scopes !== undefined;
+ const privatePages = args.privatePages ?? current.privatePages;
+ const edits = args.sources !== undefined || args.takesHolders !== undefined || opsEdited || args.reset.length > 0 || args.scopes !== undefined
+ || args.privatePages !== undefined;
if (edits && !args.adopt && current.drift.length) throw driftRefusal(name, id, current.drift);
const before = grantView(current);
- const after = grantView(next);
+ const after = grantView({ ...next, privatePages });
const changed = JSON.stringify(before) !== JSON.stringify(after)
|| (args.scopes !== undefined && JSON.stringify(args.scopes) !== JSON.stringify(current.scopes));
const write = !args.dryRun && (edits || Boolean(args.adopt));
const revision = write ? await writeTokenGrant(tx, row, next, args.scopes) : current.revision;
+ if (write && privatePages !== current.privatePages) {
+ await tx.executeRaw('UPDATE access_tokens SET private_pages = $2 WHERE id = $1::uuid', [id, privatePages]);
+ }
return {
id, name, dryRun: args.dryRun, changed, before, after,
shape: current.shape, migrated: write && current.shape === 'legacy_permissions', written: write,
diff --git a/src/core/grants/model.ts b/src/core/grants/model.ts
index 3c34a2fb73..512af3ed02 100644
--- a/src/core/grants/model.ts
+++ b/src/core/grants/model.ts
@@ -6,6 +6,14 @@ import { pgArray } from './encoding.ts';
export const GRANT_PROFILES = ['memory-reader', 'memory-writer', 'coding-agent', 'operator', 'delegating-agent', 'full'] as const;
export type GrantProfileId = typeof GRANT_PROFILES[number];
export type GrantSurface = 'verbs' | 'starter' | 'full';
+/**
+ * GBRA-156: whether a remote caller reads `visibility: private` pages in the
+ * sources its grant names explicitly (`granted_sources`) or in none (`none`,
+ * the default). Stored in `private_pages` on access_tokens and oauth_clients,
+ * not in the legacy `permissions` mirror, so older binaries keep hiding them.
+ */
+export type PrivatePagesGrant = 'none' | 'granted_sources';
+export const PRIVATE_PAGES_GRANTS: readonly PrivatePagesGrant[] = ['none', 'granted_sources'];
/** Access-token lifetime bounds for every per-client override and the server default: 1 minute to 90 days. */
export const TOKEN_TTL_MIN_SECONDS = 60;
@@ -22,6 +30,7 @@ export interface ClientGrant {
sourcesNone: boolean;
/** Takes-holder allow-list; null = the default ['world'], [] = deny-all. */
takesHolders: string[] | null;
+ privatePages: PrivatePagesGrant;
boundSlugPrefixes: string[] | null;
allowedOperations: string[] | null;
boundTools: string[] | null;
@@ -79,6 +88,7 @@ export function grantFromRow(row: Record<string, unknown>): ClientGrant {
scopes: parseScopeString(nullable(row.scope) ?? ''),
sourceId: nullable(row.source_id), federatedRead: stringArray(row.federated_read) ?? [],
sourcesNone: row.source_grant === 'none', takesHolders: stringArray(row.takes_holders),
+ privatePages: privatePagesFromColumn(row.private_pages),
boundSlugPrefixes: legacyPrefixes, allowedOperations: stringArray(row.allowed_operations),
boundTools: stringArray(row.bound_tools), boundSourceId: nullable(row.bound_source_id),
boundBrainId: normalizeGrantBrain(nullable(row.bound_brain_id)),
@@ -96,6 +106,11 @@ export function grantFromRow(row: Record<string, unknown>): ClientGrant {
};
}
+/** A `private_pages` column value; anything but `granted_sources` reads as `none` (fail closed). */
+export function privatePagesFromColumn(value: unknown): PrivatePagesGrant {
+ return value === 'granted_sources' ? 'granted_sources' : 'none';
+}
+
export function validGrantPrefixes(prefixes: readonly string[] | null): boolean {
return prefixes !== null && prefixes.length > 0 && prefixes.every(p =>
typeof p === 'string' && p.trim() === p && !/\s/.test(p) && p === p.toLowerCase()
@@ -138,6 +153,7 @@ export function validateClientGrant(grant: ClientGrant, ctx: GrantValidationCont
if (grant.tokenTtlSeconds !== null && (!Number.isSafeInteger(grant.tokenTtlSeconds) || grant.tokenTtlSeconds < TOKEN_TTL_MIN_SECONDS || grant.tokenTtlSeconds > TOKEN_TTL_MAX_SECONDS)) reasons.push('token_ttl_invalid');
if (grant.surface !== null && !['verbs', 'starter', 'full'].includes(grant.surface)) reasons.push('surface_invalid');
if (grant.profile !== null && !(GRANT_PROFILES as readonly string[]).includes(grant.profile)) reasons.push('profile_invalid');
+ if (grant.privatePages !== undefined && !PRIVATE_PAGES_GRANTS.includes(grant.privatePages)) reasons.push('private_pages_invalid');
if (!Number.isSafeInteger(grant.boundMaxConcurrent) || grant.boundMaxConcurrent < 1) reasons.push('concurrency_invalid');
if (hasScope(grant.scopes, 'agent')) reasons.push(...delegationReasons(grant, ctx));
if (reasons.length) throw new GrantError('invalid_grant', `Invalid client grant: ${[...new Set(reasons)].join(', ')}`, [...new Set(reasons)]);
@@ -166,6 +182,7 @@ export interface PrincipalGrant {
allowedOperations: string[] | null;
/** null = the default ['world']; [] = deny-all. */
takesHolders: string[] | null;
+ privatePages: PrivatePagesGrant;
revision: number;
shape: 'unified' | 'legacy_permissions';
/**
@@ -262,6 +279,7 @@ export function grantFromTokenRow(row: Record<string, unknown>): PrincipalGrant
const base = {
principal: { kind: 'legacy_token' as const, id: String(row.id) },
scopes: normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin'],
+ privatePages: privatePagesFromColumn(row.private_pages),
revision: Number(row.grant_revision ?? 0),
};
const { malformed, ...legacy } = tokenGrantFromPermissions(row.permissions);
@@ -286,7 +304,8 @@ export function grantFromClient(grant: ClientGrant): PrincipalGrant {
: { kind: 'federated', writeSource: grant.sourceId, readSources: [...grant.federatedRead] };
return {
principal: { kind: 'oauth_client', id: grant.clientId }, scopes: [...grant.scopes], sources,
- allowedOperations: grant.allowedOperations, takesHolders: grant.takesHolders ?? null, revision: grant.revision,
+ allowedOperations: grant.allowedOperations, takesHolders: grant.takesHolders ?? null,
+ privatePages: privatePagesFromColumn(grant.privatePages), revision: grant.revision,
shape: 'unified', drift: [], permissionsMalformed: false,
};
}
@@ -301,6 +320,26 @@ export function authSourcesFromGrant(g: PrincipalGrant): { sourceId: string; all
}
}
+/**
+ * GBRA-156: the sources whose private pages this grant's principal may read
+ * remotely. Only sources the grant names explicitly count: a scalar grant's
+ * write source, a federated grant's write and read sources. The no-grant
+ * floor (`default`), `none` and the `none` axis yield nothing.
+ */
+export function privatePagesSources(g: Pick<PrincipalGrant, 'sources' | 'privatePages'>): string[] {
+ if (g.privatePages !== 'granted_sources') return [];
+ const s = g.sources;
+ if (s.kind === 'scalar') return [s.writeSource];
+ if (s.kind === 'federated') return [...new Set([s.writeSource, ...s.readSources])];
+ return [];
+}
+
+/** The AuthInfo `privatePages` field for this grant; empty when nothing is private-readable. */
+export function privatePagesAuth(g: Pick<PrincipalGrant, 'sources' | 'privatePages'>): { privatePages?: { mode: 'granted_sources'; sources: string[] } } {
+ const sources = privatePagesSources(g);
+ return sources.length ? { privatePages: { mode: 'granted_sources', sources } } : {};
+}
+
/**
* Shape rules for a grant about to be written. Whether named sources are
* active is the caller's database check. Tokens and OAuth clients may both
diff --git a/src/core/grants/service.ts b/src/core/grants/service.ts
index 91dc4b80d3..c9a5fd06a2 100644
--- a/src/core/grants/service.ts
+++ b/src/core/grants/service.ts
@@ -27,7 +27,7 @@ export interface GrantMutationOptions {
servingBrainId?: string;
}
export interface GrantMutationResult { before: ClientGrant; after: ClientGrant; revision: number; dryRun: boolean }
-const PATCH_FIELDS = new Set<keyof GrantPatch>(['scopes', 'sourceId', 'federatedRead', 'sourcesNone', 'takesHolders', 'boundSlugPrefixes', 'allowedOperations', 'boundTools', 'boundSourceId', 'boundBrainId', 'delegatedSlugPrefixes', 'delegatedNamespace', 'boundMaxConcurrent', 'budgetUsdPerDay', 'surface', 'surfaceSetBy', 'tokenTtlSeconds', 'profile', 'repairReasons']);
+const PATCH_FIELDS = new Set<keyof GrantPatch>(['scopes', 'sourceId', 'federatedRead', 'sourcesNone', 'takesHolders', 'boundSlugPrefixes', 'allowedOperations', 'boundTools', 'boundSourceId', 'boundBrainId', 'delegatedSlugPrefixes', 'delegatedNamespace', 'boundMaxConcurrent', 'budgetUsdPerDay', 'surface', 'surfaceSetBy', 'tokenTtlSeconds', 'profile', 'repairReasons', 'privatePages']);
export function assertGrantPatch(patch: GrantPatch): void {
for (const key of Object.keys(patch)) {
if (!PATCH_FIELDS.has(key as keyof GrantPatch)) throw new GrantError('invalid_grant', `Unknown grant field: ${key}`);
@@ -114,6 +114,7 @@ export async function rescopeClientGrantInTransaction(db: GrantDatabase, clientI
const rows = await sql`SELECT * FROM oauth_clients WHERE client_id = ${clientId} FOR UPDATE`;
if (!rows.length) throw new GrantError('client_not_found', `No OAuth client found with id "${clientId}"`);
if (!('grant_revision' in rows[0]) || !('takes_holders' in rows[0])) throw new GrantError('grant_schema_required', 'Run gbrain apply-migrations --yes before changing client grants');
+ if (patch.privatePages !== undefined && !('private_pages' in rows[0])) throw new GrantError('grant_schema_required', 'Run gbrain apply-migrations --yes before changing the private-pages grant');
const before = grantFromRow(rows[0]);
if (opts.expectedRevision !== undefined && before.revision !== opts.expectedRevision) {
throw new GrantError('grant_conflict', `Grant changed (expected revision ${opts.expectedRevision}, current ${before.revision}); review a fresh preview`);
@@ -231,6 +232,9 @@ export async function persistGrant(sql: SqlQuery, before: ClientGrant, after: Cl
) SELECT client_id FROM audited
`;
if (!result.length) throw new GrantError('grant_conflict', 'Client grant changed; review a fresh preview');
+ if ((after.privatePages ?? 'none') !== (before.privatePages ?? 'none')) {
+ await sql`UPDATE oauth_clients SET private_pages = ${after.privatePages} WHERE client_id = ${before.clientId}`;
+ }
}
export { GrantError, grantFromRow, validateClientGrant, delegationReasons, intersectGrantedScopes } from './model.ts';
diff --git a/src/core/harness/capabilities.ts b/src/core/harness/capabilities.ts
index b4829265f0..2db5692e63 100644
--- a/src/core/harness/capabilities.ts
+++ b/src/core/harness/capabilities.ts
@@ -379,6 +379,7 @@ export function describeAuthCapabilities(auth: AuthInfo, options: { surface?: st
surface: options.surface ?? auth.surface ?? 'full',
source_id: auth.sourceId ?? null,
federated_read: auth.allowedSources ?? [],
+ private_pages: auth.privatePages ?? { mode: 'none', sources: [] },
allowed_operations: auth.allowedOperations ?? null,
...(options.visibleOperations ? { available_operations: options.visibleOperations } : {}),
shared_skills: {
diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.ts
index 4a8d0fe122..f9b19d0dd6 100644
--- a/src/core/oauth-provider.ts
+++ b/src/core/oauth-provider.ts
@@ -37,7 +37,7 @@ import {
dcrScopeViolation,
} from './scope.ts';
import type { AuthInfo as CoreAuthInfo } from './operations.ts';
-import { TOKEN_TTL_MAX_SECONDS, authSourcesFromGrant, grantFromRow, normalizeGrantBrain, intersectGrantedScopes, type GrantPatch } from './grants/model.ts';
+import { TOKEN_TTL_MAX_SECONDS, authSourcesFromGrant, grantFromClient, grantFromRow, normalizeGrantBrain, intersectGrantedScopes, privatePagesAuth, type GrantPatch } from './grants/model.ts';
import { assertValidSlugPrefixes, pgArray } from './grants/encoding.ts';
import { rescopeOAuthClient, type RescopeClientOptions, type RescopeClientResult } from './grants/rescope.ts';
import { grantValidationContext, validateClientGrant, insertClientGrant, assertGrantPatch } from './grants/service.ts';
@@ -921,6 +921,8 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
...(rowSurfaceSetBy !== undefined ? { surfaceSetBy: rowSurfaceSetBy } : {}),
// #5575 (CEO-18): the client's read floor; current_grant is the whole row, so no projection rung needs it.
...(storedMinTrust(currentGrant.min_trust) ? { minTrust: storedMinTrust(currentGrant.min_trust) } : {}),
+ // GBRA-156: private pages in the sources the client's grant names (source_id + federated_read), never its bound source.
+ ...(sourcesNone || rowSourceId === undefined ? {} : privatePagesAuth(grantFromClient(grantFromRow({ ...currentGrant, source_id: rowSourceId, federated_read: allowedSources ?? [] })))),
} as CoreAuthInfo as SdkAuthInfo;
}
@@ -961,6 +963,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
...authSourcesFromGrant(grant),
takesHoldersAllowList: grant.takesHolders ?? undefined,
...(storedMinTrust(legacyRows[0].min_trust) ? { minTrust: storedMinTrust(legacyRows[0].min_trust) } : {}),
+ ...privatePagesAuth(grant),
} as CoreAuthInfo as SdkAuthInfo;
}
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 124bec4f4a..c87dd6e654 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -409,6 +409,13 @@ export interface AuthInfo {
* but never lower it. Undefined = no floor (or a brain before the column).
*/
minTrust?: TrustTier;
+ /**
+ * GBRA-156: the grant's `private_pages: granted_sources` axis, set at token
+ * verification from the live row. `sources` are the sources the grant names
+ * explicitly (`privatePagesSources`); MCP dispatch makes them the
+ * private-readable set of each non-mutating call. Undefined = `none`.
+ */
+ privatePages?: { mode: 'granted_sources'; sources: string[] };
/** Current transport ceiling applied to this authenticated request. */
effectiveSurface?: 'verbs' | 'starter' | 'full';
/**
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 0ce9625d70..1a209b9221 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 272;
+export const LATEST_SCHEMA_VERSION = 273;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index f9798571c9..97a2b0ea61 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -273,6 +273,7 @@ import { v269 } from './v269-links-supersedes-index.ts';
import { v270 } from './v270-pages-source-created-index.ts';
import { v271 } from './v271-facts-superseded-by-index.ts';
import { v272 } from './v272-git-canonical-declared.ts';
+import { v273 } from './v273-principal-private-pages.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -544,4 +545,5 @@ export const MIGRATIONS: Migration[] = [
v270,
v271,
v272,
+ v273,
];
diff --git a/src/core/schema-migrations/v273-principal-private-pages.ts b/src/core/schema-migrations/v273-principal-private-pages.ts
new file mode 100644
index 0000000000..4d0a10826d
--- /dev/null
+++ b/src/core/schema-migrations/v273-principal-private-pages.ts
@@ -0,0 +1,25 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// GBRA-156: the per-principal private-pages grant axis (grants/model.ts
+// PrivatePagesGrant). `granted_sources` lets a remote token or OAuth client
+// read `visibility: private` pages in the sources its grant names explicitly;
+// `none` (the default every existing row reads) keeps them hidden. A constant
+// default, so no row is rewritten. Not mirrored into access_tokens.permissions:
+// older binaries read only the mirror and keep hiding private pages. No
+// schema.sql mirror: like min_trust, both columns exist only through
+// migrations, so fresh installs and upgrades end with the same column order.
+// Provisional number: renumbered at the merge slot.
+export const v273: Migration = {
+ version: 273,
+ name: 'principal_private_pages',
+ idempotent: true,
+ sql: `
+ALTER TABLE access_tokens ADD COLUMN IF NOT EXISTS private_pages TEXT NOT NULL DEFAULT 'none'
+ CHECK (private_pages IN ('none', 'granted_sources'));
+ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS private_pages TEXT NOT NULL DEFAULT 'none'
+ CHECK (private_pages IN ('none', 'granted_sources'));
+`,
+};
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index 22aa9004cb..61eb704a7a 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -52,7 +52,7 @@ import { degradedLastError, isEngineDegraded } from '../core/degraded-marker.ts'
import { classifyPgAccessError } from '../core/pg-access-classify.ts';
import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';
import { redactUrlsInText } from '../core/url-redact.ts';
-import { authSourcesFromGrant } from '../core/grants/model.ts';
+import { authSourcesFromGrant, privatePagesAuth } from '../core/grants/model.ts';
import { resolveTokenGrant, touchTokenLastUsed } from '../core/grants/legacy-token.ts';
import { storedMinTrust } from '../core/trust/tier.ts';
export { parseLegacyTokenScope } from '../core/legacy-token-scope.ts';
@@ -288,7 +288,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
scopes: grant.scopes,
sourceId,
...(grant.allowedOperations === null ? {} : { allowedOperations: grant.allowedOperations }),
- ...(allowedSources ? { allowedSources } : {}),
+ ...(allowedSources ? { allowedSources } : {}), ...privatePagesAuth(grant),
...(storedMinTrust(row.min_trust) ? { minTrust: storedMinTrust(row.min_trust) } : {}),
};
return {