Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(grants): one PrincipalGrant shape for every legacy-token reader (F3)
garrytanfa2601d3b24d
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 4329af93bc..3f91695faa 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -52,7 +52,6 @@ src/core/minions/queue.ts MinionQueue.add 498 seed: W5 baseline, refactor wave 1src/core/minions/queue.ts MinionQueue.add>result=this.engine.transaction(#0) 359 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/minions/worker.ts MinionWorker.executeJob 303 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/minions/worker.ts MinionWorker.start 470 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/oauth-provider.ts GBrainOAuthProvider.verifyAccessToken 327 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/ops/facts.ts recall.handler 348 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/ops/search.ts query.handler 330 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/progressive-batch/orchestrator.ts runProgressiveBatch 348 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/src/core/grants/model.ts b/src/core/grants/model.tsindex f4a92022f4..21e17c5340 100644--- a/src/core/grants/model.ts+++ b/src/core/grants/model.ts@@ -1,4 +1,7 @@import { assertAllowedScopes, hasScope, parseScopeString } from '../scope.ts';+import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyOperationGrant, parseLegacyTokenScope, parseTakesHoldersAllowList } from '../legacy-token-scope.ts';+import { NO_SOURCES, isValidSourceId } from '../source-id.ts';+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];@@ -125,3 +128,199 @@ export function validateClientGrant(grant: ClientGrant, ctx: GrantValidationContif (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)]);}++// ---------------------------------------------------------------------------+// F3: one grant shape for legacy bearer tokens and OAuth clients.+// ---------------------------------------------------------------------------++export type LegacyGrantAxis = 'sources' | 'takes-holders' | 'operations';+export const LEGACY_GRANT_AXES: readonly LegacyGrantAxis[] = ['sources', 'takes-holders', 'operations'];++/** For tokens `readSources[0] === writeSource`; a client's read set may differ from its write source. */+export type GrantSources =+ | { kind: 'default' }+ | { kind: 'scalar'; writeSource: string }+ | { kind: 'federated'; writeSource: string; readSources: string[] }+ | { kind: 'none' };++export interface PrincipalGrant {+ principal: { kind: 'oauth_client' | 'legacy_token'; id: string };+ /** Tokens: `normalizeTokenScopes`, NULL grandfathered to read/write/admin. */+ scopes: string[];+ sources: GrantSources;+ /** null = every operation the scopes allow; [] = none. */+ allowedOperations: string[] | null;+ /** null = the default ['world']; [] = deny-all. */+ takesHolders: string[] | null;+ revision: number;+ shape: 'unified' | 'legacy_permissions';+ /**+ * Unified rows only: axes whose `permissions` mirror disagrees with the+ * columns (an older gbrain edited the JSONB). Each listed axis is already+ * deny-all in this grant until `auth rescope --adopt-permissions` or+ * `--adopt-columns` resolves it.+ */+ drift: LegacyGrantAxis[];+ /**+ * Legacy rows only: `permissions` is present but not a JSON object. The HTTP+ * auth paths read it as no grant; publication and job admission deny it.+ */+ permissionsMalformed: boolean;+}++type TokenGrantAxes = Pick<PrincipalGrant, 'sources' | 'allowedOperations' | 'takesHolders'>;++/** The grant a `permissions` JSONB value carries, read with lane F's parsers. */+export function tokenGrantFromPermissions(raw: unknown): TokenGrantAxes & { malformed: boolean } {+ const permissions = coerceLegacyPermissions(raw);+ let sources: GrantSources = { kind: 'default' };+ if (permissions?.source_id != null) {+ // Non-null garbage keeps lane F's `default` floor WITH a source grant+ // (hasSourceGrant=true), which is exactly a scalar 'default' grant.+ const parsed = parseLegacyTokenScope(permissions.source_id);+ sources = parsed.allowedSources?.length === 0 ? { kind: 'none' }+ : parsed.allowedSources ? { kind: 'federated', writeSource: parsed.sourceId, readSources: parsed.allowedSources }+ : { kind: 'scalar', writeSource: parsed.sourceId };+ }+ return {+ sources,+ allowedOperations: parseLegacyOperationGrant(permissions?.allowed_operations) ?? null,+ takesHolders: parseTakesHoldersAllowList(permissions?.takes_holders) ?? null,+ malformed: raw != null && permissions === undefined,+ };+}++/** A TEXT[] column value; anything but NULL or a string array denies (fail-closed). */+function columnList(value: unknown): string[] | null {+ if (value == null) return null;+ if (Array.isArray(value)) return value.every(v => typeof v === 'string') ? [...value] : [];+ if (typeof value === 'string' && /^\{.*\}$/.test(value.trim())) {+ const inner = value.trim().slice(1, -1);+ return inner === '' ? [] : inner.split(',').map(s => s.trim().replace(/^"|"$/g, ''));+ }+ return [];+}++/** The grant the unified columns carry; an inconsistent source state reads as `none`. */+export function tokenGrantFromColumns(row: Record<string, unknown>): TokenGrantAxes {+ const write = typeof row.source_id === 'string' && row.source_id.length > 0 ? row.source_id : null;+ const reads = columnList(row.federated_read);+ let sources: GrantSources = { kind: 'none' };+ if (row.source_grant === 'default') sources = { kind: 'default' };+ else if (row.source_grant === 'scalar' && write) sources = { kind: 'scalar', writeSource: write };+ else if (row.source_grant === 'federated' && write && reads?.length && reads[0] === write) {+ sources = { kind: 'federated', writeSource: write, readSources: reads };+ }+ return { sources, allowedOperations: columnList(row.allowed_operations), takesHolders: columnList(row.takes_holders) };+}++const sortedSet = (list: readonly string[]): string => JSON.stringify([...new Set(list)].sort());++function sameAxis(axis: LegacyGrantAxis, a: TokenGrantAxes, b: TokenGrantAxes): boolean {+ if (axis === 'sources') return JSON.stringify(a.sources) === JSON.stringify(b.sources);+ if (axis === 'takes-holders') return sortedSet(a.takesHolders ?? ['world']) === sortedSet(b.takesHolders ?? ['world']);+ return a.allowedOperations === null || b.allowedOperations === null+ ? a.allowedOperations === b.allowedOperations+ : sortedSet(a.allowedOperations) === sortedSet(b.allowedOperations);+}++/**+ * The effective grant of an `access_tokens` row (SELECT * keeps this working+ * on brains that predate the columns). `source_grant IS NULL` rows are read+ * through lane F's JSONB parsers unchanged; unified rows read the columns,+ * and any axis whose JSONB mirror disagrees evaluates deny-all.+ */+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'],+ revision: Number(row.grant_revision ?? 0),+ };+ const { malformed, ...legacy } = tokenGrantFromPermissions(row.permissions);+ if (row.source_grant == null) return { ...base, ...legacy, shape: 'legacy_permissions', drift: [], permissionsMalformed: malformed };+ const columns = tokenGrantFromColumns(row);+ const drift = LEGACY_GRANT_AXES.filter(axis => malformed || !sameAxis(axis, columns, legacy));+ return {+ ...base, shape: 'unified', drift, permissionsMalformed: false,+ sources: drift.includes('sources') ? { kind: 'none' } : columns.sources,+ allowedOperations: drift.includes('operations') ? [] : columns.allowedOperations,+ takesHolders: drift.includes('takes-holders') ? [] : columns.takesHolders,+ };+}++export function grantFromClient(grant: ClientGrant): PrincipalGrant {+ const sources: GrantSources = grant.sourceId === null ? { kind: 'default' }+ : grant.federatedRead.length === 0 ? { kind: 'scalar', writeSource: grant.sourceId }+ : { kind: 'federated', writeSource: grant.sourceId, readSources: [...grant.federatedRead] };+ return {+ principal: { kind: 'oauth_client', id: grant.clientId }, scopes: [...grant.scopes], sources,+ allowedOperations: grant.allowedOperations, takesHolders: null, revision: grant.revision,+ shape: 'unified', drift: [], permissionsMalformed: false,+ };+}++/** The AuthInfo source fields, exactly as lane F derived them from `permissions.source_id`. */+export function authSourcesFromGrant(g: PrincipalGrant): { sourceId: string; allowedSources?: string[]; hasSourceGrant: boolean } {+ switch (g.sources.kind) {+ case 'default': return { sourceId: 'default', hasSourceGrant: false };+ case 'scalar': return { sourceId: g.sources.writeSource, hasSourceGrant: true };+ case 'federated': return { sourceId: g.sources.writeSource, allowedSources: [...g.sources.readSources], hasSourceGrant: true };+ case 'none': return { sourceId: NO_SOURCES, allowedSources: [], hasSourceGrant: true };+ }+}++/**+ * Shape rules for a grant about to be written. Whether named sources are+ * active is the caller's database check. Tokens may hold the explicit+ * deny-all `none`; OAuth clients may not in F3 (client deny-all is+ * `auth revoke-client`).+ */+export function validatePrincipalGrant(g: PrincipalGrant, ctx: { operationNames: ReadonlySet<string> }): void {+ const reasons: string[] = [];+ const client = g.principal.kind === 'oauth_client';+ if (g.sources.kind === 'none' && client) reasons.push('client_sources_none_unsupported');+ if (g.sources.kind === 'scalar' || g.sources.kind === 'federated') {+ const ids = g.sources.kind === 'scalar' ? [g.sources.writeSource] : [g.sources.writeSource, ...g.sources.readSources];+ if (ids.some(id => !isValidSourceId(id))) reasons.push('source_invalid');+ if (g.sources.kind === 'federated' && (g.sources.readSources.length === 0 || (!client && g.sources.readSources[0] !== g.sources.writeSource))) reasons.push('read_sources_invalid');+ }+ if (g.allowedOperations?.some(name => !ctx.operationNames.has(name))) reasons.push('operations_unavailable');+ if (!reasons.length) return;+ const fix = reasons.includes('client_sources_none_unsupported')+ ? ` OAuth clients cannot hold an explicit no-source grant yet; to cut client ${g.principal.id} off run gbrain auth revoke-client ${g.principal.id}, or narrow it with gbrain auth rescope --client ${g.principal.id} --sources <id>.`+ : '';+ throw new GrantError('invalid_grant', `Invalid ${client ? 'client' : 'token'} grant: ${reasons.join(', ')}.${fix}`, reasons);+}++/**+ * The `permissions` JSONB written beside the columns so older binaries, which+ * read only JSONB, enforce the same grant. Unrelated keys are preserved; a+ * malformed value is replaced by an object.+ */+export function permissionsMirror(g: Pick<PrincipalGrant, 'sources' | 'allowedOperations' | 'takesHolders'>, existing: unknown): Record<string, unknown> {+ const out: Record<string, unknown> = { ...(coerceLegacyPermissions(existing) ?? {}) };+ if (g.sources.kind === 'default') delete out.source_id;+ else out.source_id = g.sources.kind === 'none' ? [] : g.sources.kind === 'scalar' ? g.sources.writeSource : [...g.sources.readSources];+ if (g.takesHolders === null) delete out.takes_holders;+ else out.takes_holders = [...g.takesHolders];+ if (g.allowedOperations === null) delete out.allowed_operations;+ else out.allowed_operations = [...g.allowedOperations];+ return out;+}++/**+ * Bind values for the unified columns, in order: source_grant, source_id,+ * federated_read, allowed_operations, takes_holders (arrays as text[]+ * literals, NULL as null). Pair with `TOKEN_GRANT_COLUMNS`.+ */+export function tokenGrantColumnValues(g: Pick<PrincipalGrant, 'sources' | 'allowedOperations' | 'takesHolders'>): [string, string | null, string | null, string | null, string | null] {+ const s = g.sources;+ return [+ s.kind,+ s.kind === 'scalar' || s.kind === 'federated' ? s.writeSource : null,+ s.kind === 'federated' ? pgArray(s.readSources) : s.kind === 'none' ? '{}' : null,+ g.allowedOperations === null ? null : pgArray(g.allowedOperations),+ g.takesHolders === null ? null : pgArray(g.takesHolders),+ ];+}+export const TOKEN_GRANT_COLUMNS = ['source_grant', 'source_id', 'federated_read', 'allowed_operations', 'takes_holders'] as const;diff --git a/src/core/minions/submission-authority.ts b/src/core/minions/submission-authority.tsindex f7c0b51b56..1d2e961107 100644--- a/src/core/minions/submission-authority.ts+++ b/src/core/minions/submission-authority.ts@@ -9,7 +9,7 @@ import { catalogueError } from '../error-catalogue.ts';import { STOP_PRODUCERS, legacyRecoveryHint, selectCommand } from './legacy-selection.ts';import { normalizeSlugPrefix } from '../ops/context.ts';import { hasScope } from '../scope.ts';-import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyTokenScope } from '../legacy-token-scope.ts';+import { authSourcesFromGrant, grantFromTokenRow } from '../grants/model.ts';import { isValidSourceId } from '../source-id.ts';import { discoverGitRoot } from '../sync-git.ts';import type { MinionJob } from './types.ts';@@ -137,11 +137,12 @@ export async function assertCurrentRemoteJobPrincipal(engine: BrainEngine, autho}} else {const [row] = await engine.executeRaw<Record<string, unknown>>(- 'SELECT id, revoked_at, scopes, permissions FROM access_tokens WHERE id = $1', [principal.id]);+ 'SELECT * FROM access_tokens WHERE id = $1', [principal.id]);if (!row || row.revoked_at != null) deny('legacy token is missing or revoked');- scopes = normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin'];- if (row.permissions != null && !coerceLegacyPermissions(row.permissions)) deny('malformed token permissions');- sourceId = parseLegacyTokenScope(coerceLegacyPermissions(row.permissions)?.source_id).sourceId;+ const tokenGrant = grantFromTokenRow(row);+ if (tokenGrant.permissionsMalformed) deny('malformed token permissions');+ scopes = tokenGrant.scopes;+ sourceId = authSourcesFromGrant(tokenGrant).sourceId;}if (!hasScope(grant.scopes, 'admin') || !hasScope(scopes, 'admin') || sourceId !== grant.sourceId) {deny('the original grant and current principal must both authorize this source and admin operation');diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex 565d39a4af..673fb3c004 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -37,8 +37,7 @@ import {dcrScopeViolation,} from './scope.ts';import type { AuthInfo as CoreAuthInfo } from './operations.ts';-import { parseLegacyTokenScope, parseTakesHoldersAllowList, coerceLegacyPermissions, normalizeTokenScopes, parseLegacyOperationGrant } from './legacy-token-scope.ts';-import { grantFromRow, normalizeGrantBrain, intersectGrantedScopes, type GrantPatch } from './grants/model.ts';+import { authSourcesFromGrant, grantFromRow, grantFromTokenRow, normalizeGrantBrain, intersectGrantedScopes, 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';@@ -890,41 +889,15 @@ export class GBrainOAuthProvider implements OAuthServerProvider {} as CoreAuthInfo as SdkAuthInfo;}- // Fallback: legacy access_tokens table (backward compat). Modern legacy- // rows may carry permissions.source_id from the pre-OAuth bearer-token- // path; OAuth transport must preserve that same source grant instead of- // pinning every legacy token to `default`.- let legacyRows: Record<string, unknown>[];- try {- legacyRows = await this.sql`- SELECT id, name, permissions, scopes FROM access_tokens- WHERE token_hash = ${tokenHash} AND revoked_at IS NULL- `;- } catch (err) {- if (isUndefinedColumnError(err, 'permissions')) {- // Pre-v38 brain: no permissions column. scopes is ORIGINAL schema, so- // it must stay in the degraded SELECT — dropping it here would route- // normalizeTokenScopes(undefined) into the grandfather branch and- // silently promote a scoped token to full admin on any brain whose- // permissions projection fails (ship-review P1). Only if scopes- // ITSELF is missing (out-of-tree schema) does the ladder fall to- // name-only — and that brain predates scoped minting entirely.- try {- legacyRows = await this.sql`- SELECT id, name, scopes FROM access_tokens- WHERE token_hash = ${tokenHash} AND revoked_at IS NULL- `;- } catch (err2) {- if (!isUndefinedColumnError(err2, 'scopes')) throw err2;- legacyRows = await this.sql`- SELECT id, name FROM access_tokens- WHERE token_hash = ${tokenHash} AND revoked_at IS NULL- `;- }- } else {- throw err;- }- }+ // Fallback: legacy access_tokens table (backward compat). SELECT * keeps+ // every schema generation readable: pre-v38 rows have no permissions,+ // pre-F3 rows no grant columns, and `scopes` (original schema) must never+ // drop out of the projection, or normalizeTokenScopes(undefined) would+ // grandfather a scoped token to full admin (ship-review P1).+ const legacyRows: Record<string, unknown>[] = await this.sql`+ SELECT * FROM access_tokens+ WHERE token_hash = ${tokenHash} AND revoked_at IS NULL+ `;if (legacyRows.length > 0) {// For legacy tokens, name = clientId = clientName (single identifier).@@ -940,37 +913,25 @@ export class GBrainOAuthProvider implements OAuthServerProvider {AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds') FOR UPDATE SKIP LOCKED)`.catch(() => { /* fire-and-forget */ });const name = legacyRows[0].name as string;- const permissions = coerceLegacyPermissions(legacyRows[0].permissions);- const { sourceId, allowedSources } = parseLegacyTokenScope(permissions?.source_id);- // #2529: thread the stored takes-holders grant, mirroring the legacy- // HTTP transport's validateToken (both decode via coerceLegacyPermissions- // + parseTakesHoldersAllowList so they cannot drift). Undefined (no array- // grant, or the pre-v29 no-permissions-column fallback above) → the /mcp- // dispatch site defaults to the fail-closed ['world']. An explicit []- // grant is preserved as deny-all.- const takesHoldersAllowList = parseTakesHoldersAllowList(permissions?.takes_holders);- // #4043 least-privilege: the original-schema `scopes TEXT[]` column is- // the scope store. NULL/absent (every token minted before this feature)- // → grandfathered full access, byte-identical behavior. An array is- // filtered to known scopes and honored as-is — including [] as deny.- const grantedScopes = normalizeTokenScopes(legacyRows[0].scopes);+ // F3: one grant shape (grants/model.ts), shared with the legacy HTTP+ // transport so the two cannot drift. Unmigrated rows read through lane+ // F's JSONB parsers; unified rows read the columns, fail-closed on drift.+ // Scopes: NULL (every token minted before #4043) is grandfathered full+ // access; an array is honored as-is, including [] as deny. Takes holders+ // null → the /mcp dispatch site defaults to the fail-closed ['world'].+ const grant = grantFromTokenRow(legacyRows[0]);return {token,clientId: name,principal: { kind: 'legacy_token', id: String(legacyRows[0].id) },clientName: name,- scopes: grantedScopes ?? ['read', 'write', 'admin'],- ...(permissions?.allowed_operations === undefined ? {} : { allowedOperations: parseLegacyOperationGrant(permissions.allowed_operations) }),+ scopes: grant.scopes,+ ...(grant.allowedOperations === null ? {} : { allowedOperations: grant.allowedOperations }),expiresAt: Math.floor(Date.now() / 1000) + 365 * 24 * 3600, // Legacy tokens never expire — set 1yr future- // Legacy tokens without an explicit permissions.source_id grant keep- // the historical 'default' source floor. Array grants become- // allowedSources for federated reads, matching legacy HTTP transport.- sourceId,- allowedSources,- // #3242 parity with src/mcp/http-transport.ts: only the historical- // no-grant floor may widen unqualified reads to the federated set.- hasSourceGrant: permissions?.source_id != null,- takesHoldersAllowList,+ // #3242 parity: hasSourceGrant=false only on the historical no-grant+ // floor, the one case that may widen unqualified reads.+ ...authSourcesFromGrant(grant),+ takesHoldersAllowList: grant.takesHolders ?? undefined,} as CoreAuthInfo as SdkAuthInfo;}diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 69d8b0244a..7d246a3a2f 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -4,7 +4,8 @@ import { OperationError } from '../ops/contract.ts';import { slugUnderBoundPrefixes, matchesSlugAllowList, noSourceGrantError } from '../ops/context.ts';import { NO_SOURCES } from '../source-id.ts';import { hasScope } from '../scope.ts';-import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyTokenScope, parseTakesHoldersAllowList, parseLegacyOperationGrant } from '../legacy-token-scope.ts';+import { normalizeTokenScopes } from '../legacy-token-scope.ts';+import { authSourcesFromGrant, grantFromTokenRow } from '../grants/model.ts';import { readLocalWriter, currentVerifiedLocalWriter, verifyLocalWriter, type LocalGrant } from './identity.ts';import type { Principal, SqlEngine, WriteAuthority, WriteRequest } from './model.ts';import { authorizePageVisibility, excludesPrivateWrites } from './page-visibility.ts';@@ -79,15 +80,14 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operareturn;}if (a.principal.kind === 'legacy_token') {- const [row] = await engine.executeRaw<Record<string, unknown>>(`SELECT revoked_at,scopes,permissions FROM access_tokens WHERE id=$1${suffix}`, [a.principal.id]);+ const [row] = await engine.executeRaw<Record<string, unknown>>(`SELECT * FROM access_tokens WHERE id=$1${suffix}`, [a.principal.id]);if (!row || row.revoked_at != null) deny('The owning token is revoked.');- const permissions = coerceLegacyPermissions(row.permissions);- if (row.permissions != null && !permissions) deny('The current legacy grant is malformed.');+ const grant = grantFromTokenRow(row);+ if (grant.permissionsMalformed) deny('The current legacy grant is malformed.');assertSkillWriteScopes(normalizeTokenScopes(row.scopes) ?? [], operation, a.remote);- const liveOperations = parseLegacyOperationGrant(permissions?.allowed_operations);+ const liveOperations = grant.allowedOperations;if (!operationAllowed(liveOperations, operation) || skillWrite(operation) && !liveOperations?.includes(operation)) deny('The current legacy operation grant excludes this write.');- if (!hasScope(normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin'], 'write') ||- parseLegacyTokenScope(permissions?.source_id).sourceId !== a.sourceId) deny('The current token no longer permits this source write.');+ if (!hasScope(grant.scopes, 'write') || authSourcesFromGrant(grant).sourceId !== a.sourceId) deny('The current token no longer permits this source write.');return;}if (a.principal.kind === 'local_cli' || a.principal.kind === 'local_stdio') {@@ -169,9 +169,9 @@ export async function authorizeTakeHolder(engine: SqlEngine, authority: WriteAutif (!(authority.takesHolders ?? ['world']).includes(holder)) deny('The take holder exceeds the original grant.');let current = ['world'];if (authority.principal.kind === 'legacy_token') {- const [row] = await engine.executeRaw<{ permissions: unknown }>('SELECT permissions FROM access_tokens WHERE id=$1 AND revoked_at IS NULL', [authority.principal.id]);+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE id=$1 AND revoked_at IS NULL', [authority.principal.id]);if (!row) deny('The owning token is revoked.');- current = parseTakesHoldersAllowList(coerceLegacyPermissions(row.permissions)?.takes_holders) ?? ['world'];+ current = grantFromTokenRow(row).takesHolders ?? ['world'];}if (!current.includes(holder)) deny('The current holder grant excludes this write.');}diff --git a/src/core/shared-skills/membership-authority.ts b/src/core/shared-skills/membership-authority.tsindex dfd2340dc7..04850eabfb 100644--- a/src/core/shared-skills/membership-authority.ts+++ b/src/core/shared-skills/membership-authority.ts@@ -3,7 +3,8 @@ import { OperationError, type OperationContext } from '../ops/contract.ts';import { sourceScopeOpts } from '../ops/context.ts';import { currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter, type LocalGrant } from '../persistence/identity.ts';import type { Principal } from '../persistence/model.ts';-import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyTokenScope } from '../legacy-token-scope.ts';+import { normalizeTokenScopes } from '../legacy-token-scope.ts';+import { authSourcesFromGrant, grantFromTokenRow } from '../grants/model.ts';import { hasScope } from '../scope.ts';const deny = (): never => { throw new OperationError('permission_denied', 'An intact, current skills_member_self grant and explicit operation approval are required. Membership grants no other authority.'); };@@ -26,14 +27,14 @@ export async function memberAuthority(ctx: OperationContext, operation: string):sources = [...new Set([row.source_id, ...(row.federated_read ?? [])])].filter(Boolean);grant = row;} else {- const [row] = await ctx.engine.executeRaw<{ scopes: unknown; permissions: unknown }>('SELECT scopes,permissions FROM access_tokens WHERE id=$1 AND revoked_at IS NULL FOR SHARE', [principal.id]);- const scopes = normalizeTokenScopes(row?.scopes) ?? [];- const permissions = coerceLegacyPermissions(row?.permissions);- const operations = permissions?.allowed_operations;- if (!row || !hasScope(scopes, 'read') || !hasScope(scopes, 'skills_member_self') || !Array.isArray(operations) || !operations.includes(operation)) deny();- const parsed = parseLegacyTokenScope(permissions?.source_id);+ const [row] = await ctx.engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE id=$1 AND revoked_at IS NULL FOR SHARE', [principal.id]);+ if (!row) deny();+ const scopes = normalizeTokenScopes(row.scopes) ?? [];+ const tokenGrant = grantFromTokenRow(row);+ if (!hasScope(scopes, 'read') || !hasScope(scopes, 'skills_member_self') || !tokenGrant.allowedOperations?.includes(operation)) deny();+ const parsed = authSourcesFromGrant(tokenGrant);sources = parsed.allowedSources ?? [parsed.sourceId];- grant = row;+ grant = { scopes: row.scopes, permissions: row.permissions };}const scope = sourceScopeOpts(ctx);const original = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : []);diff --git a/src/core/shared-skills/policy.ts b/src/core/shared-skills/policy.tsindex 738b5da8a4..0eb8a59b6a 100644--- a/src/core/shared-skills/policy.ts+++ b/src/core/shared-skills/policy.ts@@ -3,7 +3,8 @@ import { OperationError, type OperationContext } from '../ops/contract.ts';import { sourceScopeOpts } from '../ops/context.ts';import { hasScope } from '../scope.ts';import { currentVerifiedLocalWriter, type LocalGrant } from '../persistence/identity.ts';-import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyOperationGrant, parseLegacyTokenScope } from '../legacy-token-scope.ts';+import { normalizeTokenScopes } from '../legacy-token-scope.ts';+import { authSourcesFromGrant, grantFromTokenRow } from '../grants/model.ts';import type { SqlEngine, WriteAuthority } from '../persistence/model.ts';import { stringList } from './manifest.ts';import type { SharedSkillPolicy, SkillFileClass, StoredSkillFile } from './model.ts';@@ -63,15 +64,15 @@ export async function authorizeSkillRead(ctx: OperationContext, operation: strinliveOperations = auth.allowedOperations == null ? row.allowed_operations : row.allowed_operations == null ? auth.allowedOperations : intersect(auth.allowedOperations, row.allowed_operations);grantRevision = row.grant_revision;} else {- const [row] = await ctx.engine.executeRaw<{ scopes: unknown; permissions: unknown }>(- 'SELECT scopes,permissions FROM access_tokens WHERE id=$1 AND revoked_at IS NULL', [auth.principal.id]);- if (!row || !hasScope(normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin'], 'read')) throw new OperationError('permission_denied', 'The shared skill reader token was revoked.');- const permissions = coerceLegacyPermissions(row.permissions);- if (row.permissions != null && !permissions) throw new OperationError('permission_denied', 'Invalid reader projection.');- const parsed = parseLegacyTokenScope(permissions?.source_id);- const currentOperations = parseLegacyOperationGrant(permissions?.allowed_operations);+ const [row] = await ctx.engine.executeRaw<Record<string, unknown>>(+ 'SELECT * FROM access_tokens WHERE id=$1 AND revoked_at IS NULL', [auth.principal.id]);+ const tokenGrant = row ? grantFromTokenRow(row) : undefined;+ if (!tokenGrant || !hasScope(tokenGrant.scopes, 'read')) throw new OperationError('permission_denied', 'The shared skill reader token was revoked.');+ if (tokenGrant.permissionsMalformed) throw new OperationError('permission_denied', 'Invalid reader projection.');+ const parsed = authSourcesFromGrant(tokenGrant);+ const currentOperations = tokenGrant.allowedOperations;if (currentOperations != null && !currentOperations.includes(operation)) throw new OperationError('permission_denied', 'The current legacy operation grant excludes this read.');- liveScopes = auth.scopes.filter(scope => hasScope(normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin'], scope));+ liveScopes = auth.scopes.filter(scope => hasScope(tokenGrant.scopes, scope));liveOperations = auth.allowedOperations == null ? currentOperations : currentOperations == null ? auth.allowedOperations : intersect(auth.allowedOperations, currentOperations);liveSources = parsed.allowedSources ?? [parsed.sourceId];}diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex b1c63b8bce..986fa13158 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -48,8 +48,8 @@ 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 { normalizeTokenScopes, parseLegacyTokenScope, parseTakesHoldersAllowList, coerceLegacyPermissions, parseLegacyOperationGrant } from '../core/legacy-token-scope.ts';-export { parseLegacyTokenScope };+import { authSourcesFromGrant, grantFromTokenRow } from '../core/grants/model.ts';+export { parseLegacyTokenScope } from '../core/legacy-token-scope.ts';const DEFAULT_BODY_CAP = 1024 * 1024; // 1 MiB@@ -252,8 +252,9 @@ export async function startHttpTransport(opts: HttpTransportOptions) {const token = authHeader.slice(7);const hash = hashToken(token);try {+ // SELECT * reads every schema generation (pre-F3 rows lack the grant columns).const [row] = await sql`- SELECT id, name, permissions, scopes FROM access_tokens+ SELECT * FROM access_tokensWHERE token_hash = ${hash} AND revoked_at IS NULL`;if (!row) return { ok: false };@@ -266,25 +267,20 @@ export async function startHttpTransport(opts: HttpTransportOptions) {WHERE id IN (SELECT id FROM access_tokens WHERE id = ${rowId}AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds') FOR UPDATE SKIP LOCKED)`.catch(() => { /* fire-and-forget */ });- // v0.28: extract per-token takes-holder allow-list. Fail-safe default- // is ['world'] — a token with no permissions row sees public claims only.- // #2529: decode + parse via the shared core helpers so this transport and- // the OAuth provider behind `serve --http` cannot drift — including a- // double-encoded jsonb string scalar (#2339 class), which both now decode- // identically instead of one honoring the grant while the other fails- // open to ['world'].- const perms = coerceLegacyPermissions((row as { permissions?: unknown }).permissions);- const allowList = parseTakesHoldersAllowList(perms?.takes_holders) ?? ['world'];- // #1336: honor the operator-set source grant stored on the token.- const { sourceId, allowedSources } = parseLegacyTokenScope(perms?.source_id);+ // F3: one grant shape (grants/model.ts) shared with the OAuth provider+ // behind `serve --http`, so the two transports cannot drift. Takes+ // holders fail safe to ['world']; #1336 honors the stored source grant.+ const grant = grantFromTokenRow(row);+ const allowList = grant.takesHolders ?? ['world'];+ const { sourceId, allowedSources, hasSourceGrant } = authSourcesFromGrant(grant);const auth: AuthInfo = {token,clientId: rowId,principal: { kind: 'legacy_token', id: rowId },clientName: rowName,- scopes: normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin'],+ scopes: grant.scopes,sourceId,- ...(perms?.allowed_operations === undefined ? {} : { allowedOperations: parseLegacyOperationGrant(perms.allowed_operations) }),+ ...(grant.allowedOperations === null ? {} : { allowedOperations: grant.allowedOperations }),...(allowedSources ? { allowedSources } : {}),};return {@@ -298,7 +294,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {auth,// #3242: distinguish "operator granted a scope" from "historical// no-grant floor" — only the latter widens to federated sources.- hasSourceGrant: perms?.source_id != null,+ hasSourceGrant,};} catch {return { ok: false };diff --git a/test/http-transport.test.ts b/test/http-transport.test.tsindex 4bbd2bd565..7f5588060d 100644--- a/test/http-transport.test.ts+++ b/test/http-transport.test.ts@@ -92,7 +92,9 @@ function makeFakeEngine(cfg: FakeEngineConfig = {}): FakeEngine {const norm = normalizeSql(query);// SELECT id, name, permissions FROM access_tokens WHERE token_hash = $1 AND revoked_at IS NULL- if (norm.startsWith('select id, name from access_tokens') ||+ // F3: validateToken reads `SELECT * FROM access_tokens` (every schema generation).+ if (norm.startsWith('select * from access_tokens') ||+ norm.startsWith('select id, name from access_tokens') ||norm.startsWith('select id, name, permissions from access_tokens') ||norm.startsWith('select id, name, permissions, scopes from access_tokens')) {const tokenHash = values[0] as string;