Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: register-client keeps the pre-migration fallback (transaction only around the grant insert)

garrytan6940db5aba9e
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index 4fca72c412..5d9604589e 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -30,6 +30,7 @@ import { generateToken, isMissingSchemaObject } from '../core/utils.ts';
import { TOKEN_ID_RE, insertUnifiedToken } from '../core/token-mint.ts';
import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';
import { sqlQueryForEngine, type SqlQuery } from '../core/sql-query.ts';
+import type { OAuthTransaction } from '../core/oauth-grants.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, privatePagesFromColumn, type ClientGrant, type PrivatePagesGrant } from '../core/grants/model.ts';
@@ -601,6 +602,8 @@ export async function preflightOauthClientColumns(sql: SqlQuery): Promise<Set<st
export interface RegisterScopedClientOpts {
/** Explicit normalized profile snapshot; old callers keep legacy operation grants. */
grant?: GrantPatch;
+ /** GST-1113: runs the grant insert in one transaction (callers not already inside one). */
+ transaction?: OAuthTransaction;
/** Per-client access-token TTL to persist (oauth_clients.token_ttl). */
tokenTtlSeconds?: number;
/** Per-client tool-surface tier, written via provider.rescopeClient — the
@@ -669,7 +672,7 @@ export async function registerScopedClient(
}
: undefined;
const { GBrainOAuthProvider } = await import('../core/oauth-provider.ts');
- const provider = new GBrainOAuthProvider({ sql });
+ const provider = new GBrainOAuthProvider({ sql, transaction: opts.transaction });
const { clientId, clientSecret } = await provider.registerClientManual(
name, grantTypes, scopes, redirectUris, sourceId, federatedRead, tokenEndpointAuthMethod, agentBindings, opts.grant,
);
@@ -793,7 +796,7 @@ async function registerClient(name: string, args: string[]) {
const columns = parsed.tokenTtlSeconds !== undefined
? await preflightOauthClientColumns(sql)
: undefined;
- const registered = await engine.transaction(tx => registerScopedClient(sqlQueryForEngine(tx), name, parsed, { columns }));
+ const registered = await registerScopedClient(sql, name, parsed, { columns, transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
const bound = binding.patch ? await bindCredential(engine, { kind: 'client', id: registered.clientId }, binding.patch) : null;
if (registered.skipped?.tokenTtl) {
console.error('Note: this brain predates the token_ttl column; run `gbrain apply-migrations --yes`, then rescope. The server default TTL applies.');
diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.ts
index b2433bbb56..8e4735b213 100644
--- a/src/core/oauth-provider.ts
+++ b/src/core/oauth-provider.ts
@@ -574,6 +574,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
// for both the SDK's public-client route and our confidential-client route.
readonly skipLocalPkceValidation = true;
private sql: SqlQuery;
+ private transaction?: OAuthTransaction;
private _clientsStore: GBrainClientsStore;
private readonly dcrDisabled: boolean;
private tokenTtl: number;
@@ -582,6 +583,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
constructor(options: GBrainOAuthProviderOptions) {
this.sql = options.sql;
+ this.transaction = options.transaction;
this.dcrDisabled = options.dcrDisabled === true;
this.tokenTtl = options.tokenTtl || 3600;
this.refreshTtl = options.refreshTtl || 30 * 24 * 3600;
@@ -1127,7 +1129,9 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
const grant = { ...initial, ...changes, revision: 1 };
grant.boundBrainId = normalizeGrantBrain(grant.boundBrainId);
validateClientGrant(grant, await grantValidationContext(this.sql));
- await insertClientGrant(this.sql, grant, { secretHash, redirectUris, grantTypes, authMethod, issuedAt: now });
+ // GST-1113: with a transaction, the scope-source check and the insert commit together under the source row locks.
+ const metadata = { secretHash, redirectUris, grantTypes, authMethod, issuedAt: now };
+ await (this.transaction ? this.transaction(sql => insertClientGrant(sql, grant, metadata)) : insertClientGrant(this.sql, grant, metadata));
return { clientId, clientSecret };
}
if (grantPatch || hasScope(parseScopeString(scopes), 'agent')) {
diff --git a/test/qm-scope-writes.test.ts b/test/qm-scope-writes.test.ts
index 2ec25f94f5..a49683650a 100644
--- a/test/qm-scope-writes.test.ts
+++ b/test/qm-scope-writes.test.ts
@@ -38,6 +38,7 @@ import { isSourceFederated, loadAllSources, parseSourceConfig } from '../src/cor
import { restoreSource, softDeleteSource } from '../src/core/destructive-guard.ts';
import { proposeRevision } from '../src/core/access/policy.ts';
import { quarantineRestoredExecution } from '../src/core/backup/quarantine.ts';
+import { registerScopedClient } from '../src/commands/auth.ts';
import type { AuthInfo } from '../src/core/ops/contract.ts';
import { attestRightFrom } from '../src/core/access/actor-model.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -432,3 +433,21 @@ describe('backup restore quarantine keeps the scope mark', () => {
}
}, 120_000);
});
+
+describe('CLI client registration keeps the pre-migration fallback', () => {
+ test('register-client on an oauth_clients table without source_id still registers when given a transaction', async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' } as never);
+ try {
+ await engine.executeRaw(`CREATE TABLE oauth_clients (client_id TEXT PRIMARY KEY, client_secret_hash TEXT, client_name TEXT NOT NULL,
+ redirect_uris TEXT[], grant_types TEXT[], scope TEXT, token_endpoint_auth_method TEXT, client_id_issued_at BIGINT, deleted_at TIMESTAMPTZ)`);
+ const sql = sqlQueryForEngine(engine);
+ const registered = await registerScopedClient(sql, 'old-schema-client', { grantTypes: ['client_credentials'], scopes: 'read', sourceId: 'default', federatedRead: [], redirectUris: [], tokenEndpointAuthMethod: 'client_secret_post' } as never,
+ { transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const rows = await engine.executeRaw<{ client_name: string }>('SELECT client_name FROM oauth_clients WHERE client_id = $1', [registered.clientId]);
+ expect(rows.map(r => r.client_name)).toEqual(['old-schema-client']);
+ } finally {
+ await engine.disconnect();
+ }
+ }, 60_000);
+});