Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(connectors): bind the OAuth loopback test to an OS-assigned port

garrytan19aa0cbabeb9
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index 12e4e66542..06d1d94d30 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -41,4 +41,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/chunkers/symbol-resolver.ts` — resolves and stamps each bounded chunk batch in one transaction. It takes ordered source/page guards before edge reads, revalidates current chunk/page/slug identity under those guards, and commits edge metadata with its backfill watermark. Concurrent projection replacement cannot certify new edges using an old resolver read; rollback leaves both metadata and watermark unchanged. Pinned by `test/symbol-resolver-projection-race.test.ts` with PGLite serialization and a real PostgreSQL lock-wait receipt. A `calls` edge the extractor flagged `memberCall` (an untyped receiver, `obj.m()` emitted as bare `m`; persisted as `edge_metadata.member_call`) is never resolved within the file, since a member call cannot invoke a same-file top-level function (gbrain-evals N13-8, `test/code-intel/n13-edge-resolution.test.ts`); existing code pages pick this up when they re-import (`gbrain reindex-code`).
-- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, browser UA, refresh-once-on-401, Retry-After backoff; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, Claude's `chat_conversations` paged with `limit`/`offset` across every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT's `toIso`), a ChatGPT walk that steps back when `total` shrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, content-block text assembly for Claude, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **per-(provider, source) config-scalar watermark** `connectors.<p>.source.<id>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → skip stubs whose `updatedAt` the source's `synced` ledger already holds and stubs quarantined in its `failed` ledger (after `QUARANTINE_ATTEMPTS` = 3 fetch OR ingest failures at one `updatedAt`; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record each successfully ingested conversation as synced → advance the watermark ONLY on a clean run (quarantined ids no longer block it; ledger entries older than the next list window are pruned) → `logIngest` receipt → stamp per-source `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `config-keys.ts`: the `connectors.` key builders (sync progress keyed by `(provider, source)`; `auth_error_at` stays per provider because it describes the shared credential), `readConnectorState`/`writeConnectorState` (a legacy per-provider `watermark_iso`/`last_sync_at` is honored only for the scheduled `connectors.source_id` source until that source writes its own key, which retires it), and the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir; `connectors sync` usage errors, a missing `--source` value or a missing/unknown provider, are `invalid_params` exit 2 with the envelope under `--json` and a `fix` whose `<SOURCE_ID>`/`<PROVIDER>` input it names, and `connectors sync --help` prints the usage; `test/connectors-sync-cli.test.ts`), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-checkpoints-pglite.test.ts` (per-source watermark, `--limit` progress, quarantine, retitle) + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.
+- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, browser UA, refresh-once-on-401, Retry-After backoff; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, Claude's `chat_conversations` paged with `limit`/`offset` across every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT's `toIso`), a ChatGPT walk that steps back when `total` shrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, content-block text assembly for Claude, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **per-(provider, source) config-scalar watermark** `connectors.<p>.source.<id>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → skip stubs whose `updatedAt` the source's `synced` ledger already holds and stubs quarantined in its `failed` ledger (after `QUARANTINE_ATTEMPTS` = 3 fetch OR ingest failures at one `updatedAt`; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record each successfully ingested conversation as synced → advance the watermark ONLY on a clean run (quarantined ids no longer block it; ledger entries older than the next list window are pruned) → `logIngest` receipt → stamp per-source `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `config-keys.ts`: the `connectors.` key builders (sync progress keyed by `(provider, source)`; `auth_error_at` stays per provider because it describes the shared credential), `readConnectorState`/`writeConnectorState` (a legacy per-provider `watermark_iso`/`last_sync_at` is honored only for the scheduled `connectors.source_id` source until that source writes its own key, which retires it), and the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state; `portOverride: 0` plus `onListen` binds an OS-assigned port for tests while the authorize and token URLs keep `redirectPort`) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir; `connectors sync` usage errors, a missing `--source` value or a missing/unknown provider, are `invalid_params` exit 2 with the envelope under `--json` and a `fix` whose `<SOURCE_ID>`/`<PROVIDER>` input it names, and `connectors sync --help` prints the usage; `test/connectors-sync-cli.test.ts`), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-checkpoints-pglite.test.ts` (per-source watermark, `--limit` progress, quarantine, retitle) + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.
diff --git a/src/core/connectors/oauth-pkce.ts b/src/core/connectors/oauth-pkce.ts
index cca878d49f..18af62dd07 100644
--- a/src/core/connectors/oauth-pkce.ts
+++ b/src/core/connectors/oauth-pkce.ts
@@ -61,8 +61,10 @@ function stateMatches(expected: string, got: string | null): boolean {
export interface LoopbackOpts {
/** Print the URL instead of opening a browser (SSH/headless). */
openBrowser?: boolean;
- /** Override the redirect port (tests use an ephemeral port). */
+ /** Override the listen port; 0 asks the OS for a free one (tests). */
portOverride?: number;
+ /** Called once the listener is bound, with the port it actually bound. */
+ onListen?: (port: number) => void;
timeoutMs?: number;
signal?: AbortSignal;
/** Injected opener (tests). Default: no-op (the URL is printed regardless). */
@@ -134,7 +136,9 @@ export async function runLoopbackFlow(
'another flow may be using it; close it or use the cookie lane',
),
);
+ return;
}
+ opts.onListen?.(server!.port);
});
if (opts.openBrowser && opts.openUrl) opts.openUrl(authorizeUrl);
diff --git a/test/connectors-pkce.test.ts b/test/connectors-pkce.test.ts
index 3c1d9e568e..7cfe9a29c9 100644
--- a/test/connectors-pkce.test.ts
+++ b/test/connectors-pkce.test.ts
@@ -36,32 +36,37 @@ describe('PKCE', () => {
expect(url.searchParams.get('code_challenge')).toBe('CHAL');
expect(url.searchParams.get('state')).toBe('STATE');
expect(url.searchParams.get('client_id')).toBe('app_test');
+ expect(url.searchParams.get('redirect_uri')).toBe('http://127.0.0.1:1455/callback');
});
});
+function startFlow(expectedState: string, timeoutMs: number) {
+ let reportPort!: (port: number) => void;
+ const port = new Promise<number>((resolve) => { reportPort = resolve; });
+ const flow = runLoopbackFlow(CFG, 'https://auth.example.com/authorize', expectedState, {
+ portOverride: 0,
+ onListen: reportPort,
+ timeoutMs,
+ log: () => {},
+ });
+ return { flow, port };
+}
+
describe('loopback flow (ephemeral port)', () => {
test('resolves the code when the redirect carries a matching state', async () => {
const state = generateState();
- const port = 45219; // fixed high port for the test redirect
- const cfg = { ...CFG, redirectPort: port };
- const flow = runLoopbackFlow(cfg, 'https://auth.example.com/authorize', state, {
- timeoutMs: 5000,
- log: () => {},
- });
- // Simulate the browser redirect after a short delay.
- await new Promise((r) => setTimeout(r, 150));
- await fetch(`http://127.0.0.1:${port}/callback?code=THE_CODE&state=${encodeURIComponent(state)}`).catch(() => {});
+ const { flow, port } = startFlow(state, 5000);
+ const bound = await port;
+ expect(bound).toBeGreaterThan(0);
+ expect(bound).not.toBe(CFG.redirectPort);
+ const res = await fetch(`http://127.0.0.1:${bound}/callback?code=THE_CODE&state=${encodeURIComponent(state)}`);
+ expect(res.status).toBe(200);
const { code } = await flow;
expect(code).toBe('THE_CODE');
});
test('rejects on state mismatch (CSRF guard)', async () => {
- const port = 45220;
- const cfg = { ...CFG, redirectPort: port };
- const flow = runLoopbackFlow(cfg, 'https://auth.example.com/authorize', 'EXPECTED', {
- timeoutMs: 5000,
- log: () => {},
- });
+ const { flow, port } = startFlow('EXPECTED', 5000);
// Attach the rejection handler synchronously at creation so the reject
// (which fires as soon as the mismatched callback lands) is never a
// momentarily-unhandled rejection.
@@ -69,17 +74,15 @@ describe('loopback flow (ephemeral port)', () => {
() => { throw new Error('flow should not have resolved'); },
(e: unknown) => e,
);
- await new Promise((r) => setTimeout(r, 150));
- await fetch(`http://127.0.0.1:${port}/callback?code=x&state=WRONG`).catch(() => {});
+ const res = await fetch(`http://127.0.0.1:${await port}/callback?code=x&state=WRONG`);
+ expect(res.status).toBe(400);
const err = await captured;
expect(String(err)).toMatch(/state mismatch/i);
});
test('times out when no callback arrives', async () => {
- const port = 45221;
- const cfg = { ...CFG, redirectPort: port };
- await expect(
- runLoopbackFlow(cfg, 'https://auth.example.com/authorize', 'S', { timeoutMs: 200, log: () => {} }),
- ).rejects.toThrow(/timed out/i);
+ const { flow, port } = startFlow('S', 200);
+ expect(await port).toBeGreaterThan(0);
+ await expect(flow).rejects.toThrow(/timed out/i);
});
});