Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(auth): rescope --client with no grant flag prints the stored grants (#6993)

time-attack95c7fa5644b0
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index caf0a2d99a..eaa2a4592e 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -401,6 +401,7 @@ gbrain auth rescope --token agent-example --operations get_page,search,query
gbrain auth rescope --token agent-example --sources none # deny-all
gbrain auth rescope --token agent-example --reset-default sources,takes-holders
gbrain auth rescope --id TOKEN_ID --sources default --if-version 3 --dry-run --json
+gbrain auth rescope --client CLIENT_ID # print the stored grants, no change
gbrain auth rescope --client CLIENT_ID --sources workspace,default --operations get_page,search
gbrain auth rescope --client CLIENT_ID --takes-holders world,brain
gbrain auth rescope --client CLIENT_ID --sources none # deny-all, secret unchanged
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index 06e1f6f9bb..a44bbe6141 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 } from '../core/grants/model.ts';
+import { GRANT_PROFILES, GrantError, TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, grantFromClient, type ClientGrant } 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';
@@ -833,17 +833,36 @@ async function runRescope(args: string[], clientParser?: (args: string[]) => Res
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
+ const grantError = error instanceof GrantError ? error : undefined;
+ const fix = grantError?.code === 'client_not_found' ? renderAction(CLIENT_NOT_FOUND_FIX, cliRenderContext()) : undefined;
if (json) {
- const grantError = error instanceof GrantError ? error : undefined;
- console.log(JSON.stringify({ error: { code: grantError?.code ?? 'rescope_failed', reasons: grantError?.reasons ?? [], message } }, null, 2));
+ console.log(JSON.stringify({ error: { code: grantError?.code ?? 'rescope_failed', reasons: grantError?.reasons ?? [], message, ...(fix ? { fix, docs: 'docs/guides/error-codes.md#client_not_found' } : {}) } }, null, 2));
}
console.error('Error:', message);
+ if (fix) console.error('Fix: Run gbrain auth clients --json on this brain, then retry with an existing client id. No grants or tokens changed.');
process.exit(1);
}
}
+const CLIENT_NOT_FOUND_FIX = {
+ argv: ['gbrain', 'auth', 'clients', '--json'], consent: [], actor: 'agent' as const, requires_exclusive: false,
+ why: 'Read-only: lists the OAuth clients registered on this brain so the call can be retried with an existing client id. No grants or tokens changed.',
+ verify: { argv: ['gbrain', 'auth', 'clients', '--json'] },
+};
+
async function rescopeClientWith(engine: BrainEngine, clientId: string, parsed: RescopeGrantArgs) {
const existing = await readClientGrant(engine, clientId);
+ if (parsed.printOnly) {
+ if (parsed.json) {
+ console.log(JSON.stringify({ before: existing, after: existing, revision: existing.revision, dryRun: true, changed: false, written: false, principal_grant: grantFromClient(existing) }, null, 2));
+ return;
+ }
+ console.log(`OAuth client grants: ${existing.clientName} (${clientId})`);
+ console.log(` Revision: ${existing.revision}`);
+ printClientGrantAxes(existing);
+ console.log(`No change made. To change a grant, pass a grant flag, for example: gbrain auth rescope --client ${clientId} --sources default --dry-run`);
+ return;
+ }
const profile = parsed.profile ? resolveGrantProfile({
profile: parsed.profile, existing, sourceId: parsed.patch.sourceId ?? existing.sourceId ?? 'default',
boundTools: parsed.patch.boundTools ?? undefined,
@@ -859,15 +878,19 @@ async function rescopeClientWith(engine: BrainEngine, clientId: string, parsed:
if (parsed.json) { console.log(JSON.stringify({ ...result, principal_grant: grantFromClient(result.after) }, null, 2)); return; }
console.log(`OAuth client ${parsed.dryRun ? 'grant preview' : 'rescoped'}: ${result.after.clientName} (${clientId})`);
console.log(` Revision: ${result.before.revision} -> ${result.after.revision}`);
- console.log(` Scopes: ${result.after.scopes.join(' ') || '<none>'}`);
- console.log(` Write source: ${result.after.sourcesNone ? 'none (every read and write refused)' : result.after.sourceId}`);
- console.log(` Federated reads: ${result.after.federatedRead.join(', ') || '<none>'}`);
- console.log(` Takes holders: ${result.after.takesHolders === null ? 'world (default)' : result.after.takesHolders.join(', ') || 'none (every take hidden)'}`);
- console.log(` Tool surface: ${result.after.surface ?? '<server default>'}`);
- console.log(` Delegated spending: ${result.after.budgetUsdPerDay === null ? 'unlimited' : '$' + result.after.budgetUsdPerDay + '/day'}`);
+ printClientGrantAxes(result.after);
console.log('Restrictions apply on the next request. Added scopes require a new access token; the client secret is unchanged.');
}
+function printClientGrantAxes(grant: ClientGrant) {
+ console.log(` Scopes: ${grant.scopes.join(' ') || '<none>'}`);
+ 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(` Tool surface: ${grant.surface ?? '<server default>'}`);
+ console.log(` Delegated spending: ${grant.budgetUsdPerDay === null ? 'unlimited' : '$' + grant.budgetUsdPerDay + '/day'}`);
+}
+
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';
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 261c728b69..dee7dfa136 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -908,6 +908,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.307.0', text: 'On Windows, cancelling or timing out a job now ends its whole process tree with taskkill: a per-job child and a shell job first get a polite close (`taskkill /T`), then a forced one (`/T /F`) after the grace window, instead of only the direct child being killed. A windowless console program refuses the polite close, so a cancelled Windows shell job now takes up to its 5-second grace window to end. A descendant whose parent already exited is no longer in the tree and is not ended.', id: 'windows_tree_kill' },
{ since: '0.60.307.0', text: '`get_links` and `get_backlinks` (`gbrain links`, `gbrain backlinks`) now return at most 500 link rows per call instead of every edge of the page. When more match, the last row carries `truncated: true` and `next_cursor`: pass it back as `cursor` (`--cursor`) with the same filters for the next rows, raise `limit` (`--limit`, up to 5000), or use `--all` on the CLI for every row. Remote callers also get a `listing_truncated` notice naming the next call. Rows come in link order, `link_type` and the live/history filter apply before the cap so hidden former relationships never use a row, and each row\'s `context` is cut to 2000 characters (ending in an ellipsis). A cursor from another listing is refused `link_cursor_invalid`. `get_backlinks` with `limit` no longer points at `group: "page"`; it pages the rows with `cursor`.', id: 'link_read_cap' },
{ since: '0.60.307.0', id: 'google_account_credential_refusal', text: 'A managed Google source whose account cannot be read because the Google API is disabled for the OAuth project (or the grant is missing, or Google answers 403) now fails the sync with that credential error (`api_not_enabled` with the console link to enable the API, `scope_missing`, or `upstream` naming the 403) instead of `connector_account_changed`. A credential that no service can name for another reason still refuses as before.' },
+ { since: '0.60.307.0', id: 'auth_rescope_client_print_only', text: '`gbrain auth rescope --client <id>` (and `gbrain auth rescope-client <id>`) with no grant flag and no `--profile` now prints the client\'s stored grants and writes nothing (`--json`: `changed: false`, `written: false`), as the help always said, instead of refusing with `invalid_grant`. An unknown client id refuses with `client_not_found`, whose fix is `gbrain auth clients --json`. `--repair` alone still refuses.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index f8893ef68a..f19b72a944 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -129,6 +129,7 @@ export const CODES = {
claim_already_used: { class: 'caller', summary: "Google connect credential error: claim already used.", docs: 'docs/guides/google-connect.md#troubleshooting' },
client_json_unreadable: { class: 'caller', summary: "Google connect credential error: client json unreadable.", docs: 'docs/guides/google-connect.md#troubleshooting' },
client_json_wrong_type: { class: 'caller', summary: "Google connect credential error: client json wrong type.", docs: 'docs/guides/google-connect.md#troubleshooting' },
+ client_not_found: { class: 'caller', summary: "No OAuth client with this id is registered on this brain, so nothing was read or changed.", why: 'A client id is matched exactly; a revoked, deleted or mistyped id has no grant to read or edit.', suggestion: 'List the clients with `gbrain auth clients --json` and retry with an existing client id. Do not register a replacement client or rotate credentials for a lookup miss.', fix: { argv: ['gbrain', 'auth', 'clients', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the OAuth clients registered on this brain.', verify: { argv: ['gbrain', 'auth', 'clients', '--json'] } } },
client_shape_invalid: { class: 'caller', summary: "Google connect credential error: client shape invalid.", docs: 'docs/guides/google-connect.md#troubleshooting' },
code_callees_requires_symbol: { class: 'caller', summary: "code-callees requires a symbol name." },
code_callers_requires_symbol: { class: 'caller', summary: "code-callers requires a symbol name." },
diff --git a/src/core/grants/cli.ts b/src/core/grants/cli.ts
index 2cd210714b..d0c614cd8e 100644
--- a/src/core/grants/cli.ts
+++ b/src/core/grants/cli.ts
@@ -9,16 +9,22 @@ export interface RescopeGrantArgs {
repair: boolean;
dryRun: boolean;
json: boolean;
+ /** No grant field and no --profile: print the stored grants and write nothing (#6993). */
+ printOnly: boolean;
}
export function parseRescopeGrantArgs(args: string[]): RescopeGrantArgs {
- const result = parseRescopeGrantFlags(args);
- if (!result.profile && Object.keys(result.patch).length === 0) throw new GrantError('invalid_grant', 'Pass a grant field or --profile to rescope');
- return result;
+ return markPrintOnly(parseRescopeGrantFlags(args));
+}
+
+function markPrintOnly(result: RescopeGrantArgs): RescopeGrantArgs {
+ if (result.profile || Object.keys(result.patch).length > 0) return result;
+ if (result.repair) throw new GrantError('invalid_grant', 'Pass a grant field or --profile with --repair');
+ return { ...result, printOnly: true };
}
function parseRescopeGrantFlags(args: string[]): RescopeGrantArgs {
- const result: RescopeGrantArgs = { patch: {}, repair: false, dryRun: false, json: false };
+ const result: RescopeGrantArgs = { patch: {}, repair: false, dryRun: false, json: false, printOnly: false };
const csv = (value: string): string[] => value.split(',').map(s => s.trim()).filter(Boolean);
for (let i = 0; i < args.length; i++) {
const flag = args[i];
@@ -195,6 +201,5 @@ export function parseClientRescopeArgs(clientId: string, args: string[]): Rescop
if (invalid.length) throw new GrantError('invalid_grant', `Invalid takes holder: ${invalid.join(', ')} (use world, brain, people/<slug>, companies/<slug> or a bare slug)`, ['takes_holders_invalid']);
result.patch.takesHolders = takesHolders;
}
- if (!result.profile && Object.keys(result.patch).length === 0) throw new GrantError('invalid_grant', 'Pass a grant field or --profile to rescope');
- return result;
+ return markPrintOnly(result);
}
diff --git a/test/auth-rescope-unified.test.ts b/test/auth-rescope-unified.test.ts
index 2c11da7690..b6ed9c5fce 100644
--- a/test/auth-rescope-unified.test.ts
+++ b/test/auth-rescope-unified.test.ts
@@ -192,6 +192,35 @@ describe('9. OAuth clients', () => {
expect((await tokenRow('tok-all')).allowed_operations).toBeNull();
}, 180_000);
+ test('#6993 rescope --client with no grant flag prints the stored grants and writes nothing; an unknown id is client_not_found', async () => {
+ const client = await withBrain(async engine => {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ return provider.registerClientManual('client-print-example', ['client_credentials'], 'read write');
+ });
+ const before = await clientRow(client.clientId);
+ const human = await cli('auth', 'rescope', '--client', client.clientId);
+ expect(human.exitCode).toBe(0);
+ expect(human.stdout).toContain(`OAuth client grants: client-print-example (${client.clientId})`);
+ expect(human.stdout).toContain('No change made.');
+ const alias = await cli('auth', 'rescope-client', client.clientId, '--json');
+ expect(alias.exitCode).toBe(0);
+ const body = JSON.parse(alias.stdout) as { written: boolean; changed: boolean; revision: number; principal_grant: unknown };
+ expect(body).toMatchObject({ written: false, changed: false, revision: before.grant_revision });
+ expect(body.principal_grant).toBeDefined();
+ expect(await clientRow(client.clientId)).toEqual(before);
+
+ const missing = await cli('auth', 'rescope', '--client', 'client-missing-example', '--json');
+ expect(missing.exitCode).toBe(1);
+ const error = JSON.parse(missing.stdout) as { error: { code: string; fix: { argv: string[] } } };
+ expect(error.error.code).toBe('client_not_found');
+ expect(error.error.fix.argv.slice(0, 4)).toEqual(['gbrain', 'auth', 'clients', '--json']);
+ expect(missing.stderr).toContain('Fix: Run gbrain auth clients --json');
+
+ const repairOnly = await cli('auth', 'rescope', '--client', client.clientId, '--repair');
+ expect(repairOnly.exitCode).toBe(1);
+ expect(repairOnly.stderr).toContain('with --repair');
+ }, 180_000);
+
test('a bare name that matches both a token and a client refuses as ambiguous', async () => {
const client = await withBrain(async engine => {
const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
diff --git a/test/client-grants.test.ts b/test/client-grants.test.ts
index 824e115973..975bce87e7 100644
--- a/test/client-grants.test.ts
+++ b/test/client-grants.test.ts
@@ -342,6 +342,13 @@ describe('client capability grants', () => {
expect(() => parseRescopeGrantArgs(['--if-version', '-1'])).toThrow('non-negative');
});
+ test('#6993 no grant flag parses as print-only on both client spellings; --repair alone still refuses', () => {
+ expect(parseClientRescopeArgs('client-example', ['--json'])).toMatchObject({ printOnly: true, patch: {} });
+ expect(parseRescopeGrantArgs(['--json'])).toMatchObject({ printOnly: true, patch: {} });
+ expect(parseClientRescopeArgs('client-example', ['--sources', 'default']).printOnly).toBe(false);
+ expect(() => parseRescopeGrantArgs(['--repair'])).toThrow('with --repair');
+ });
+
test('operations all drops the snapshot and the profile; a csv still sets a snapshot', () => {
expect(parseRescopeGrantArgs(['--allowed-operations', 'all']).patch).toEqual({ allowedOperations: null, profile: null });
expect(parseClientRescopeArgs('client-example', ['--operations', 'all']).patch).toEqual({ allowedOperations: null, profile: null });