Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search,oauth): page-vector rebuilds index the withdrawal overlay; first consent locks an active source

time-attackebe347ab0e16
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 920721dc4c..2e465dfb70 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -48,5 +48,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/supabase-admin.ts` — Supabase Management-API client (`listProjects`, `discoverPoolerUrl`, `extractProjectRef` — refs are lowercase ALPHANUMERIC, `[a-z0-9]+`). Consumed by the `init --prefer-postgres` ladder's rung 2 (DISCOVERY only — project creation stays dashboard guidance; discovered URLs are candidates, connect-probed before persisting) and by the classifier's Supabase hints. The access token is never persisted, logged, or written to receipts/config.
- `src/core/worker-pool.ts` — (must-abort tags: `BUDGET_EXHAUSTED` and `SPEND_GROUP_REFUSED`, a job's spend-group refusal) Canonical sliding-pool + bounded-semaphore primitive (used by the `src/commands/embed.ts` sliding-pool sites and `src/commands/eval-cross-modal.ts`'s `runWithLimit` semaphore). Two exports: `runSlidingPool<T>({items, workers, onItem, signal?, onError?, failureLabel?, onProgress?})` + `runWithLimit<TIn, TOut>({items, limit, fn, signal?})`. Atomicity invariant: `const idx = nextIdx++` is one synchronous JS statement (no `await` between read and write — guaranteed by the single-threaded event loop), documented in the module header AND enforced by `scripts/check-worker-pool-atomicity.sh` (wired into `bun run verify`), which rejects importing `worker_threads` in any consuming file and inserting `await` between the `nextIdx` read and write. `MUST_ABORT_ERROR_TAGS` set is seeded with `BUDGET_EXHAUSTED` from `src/core/budget/budget-tracker.ts`; tagged errors (matched via `err.tag === 'BUDGET_EXHAUSTED'` to avoid cross-module import) bypass `onError` and hard-abort the pool via `AbortController.abort()` to in-flight `onItem`, then the pool JOINS every worker (each finishes its current item) before rethrowing — the budget cap is a structural ceiling under concurrency and no worker is left running detached past the caller's catch. `failures[]` shape is `{idx, label, error}` records (NOT full items; callers supply `failureLabel(item) => string`) for bounded memory under huge brains. Pinned by `test/worker-pool.test.ts` + `test/scripts/check-worker-pool-atomicity.test.ts`. Drives every `--workers N` bulk command.
-- `src/core/search-vector-backfill.ts` — keyset-batched rebuilds of stored keyword vectors, shared by `reindex-search-vector` (every row) and the `fts_cjk_boundary` migration (an optional `where` limits it to rows with a CJK boundary). `backfillChunkVectors` recomputes `content_chunks.search_vector` with `chunkSearchVectorSql`; `backfillPageVectors` (#6374) reads each batch through an UPDATE-to-self of `id` (`RETURNING id, timeline, knowledge_revision`), sanitizes the timeline with `sanitizeRemoteBody` as the seal does, and writes `search_vector` through `pageSearchVectorSql` in one `UPDATE … FROM unnest(…)` guarded by the revision read (a page edited in between is skipped; its seal reindexes it). `BACKFILL_BATCH_SIZE` 5000 rows per statement, never one transaction; the cursor persists after every batch under `backfill.<checkpoint>.last_id` and the caller clears it. Pinned by `test/reindex-search-vector.serial.test.ts`, `test/reindex-search-vector-pages.serial.test.ts`, `test/fts-cjk-boundary.test.ts`. FTS write expressions (`src/core/fts-language.ts`, #6370): `FTS_INPUT_FUNCTION_SQL` (`gbrain_fts_input(text)`, IMMUTABLE STRICT PARALLEL SAFE, `search_path = pg_catalog`: two `regexp_replace` passes built from `CJK_SLUG_CHARS` that insert a space at every CJK→ASCII-alnum and ASCII-alnum→CJK boundary; a byte-for-byte no-op without CJK, idempotent; spliced into src/schema.sql by `build:schema`), `FTS_CJK_BOUNDARY_REGEX` (the rows the `fts_cjk_boundary` migration rebuilds), `pageSearchVectorSql` (the sealed page vector used by the seal, the import seal and `search-vector-backfill.ts`), `chunkSearchVectorSql`, and `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (the two trigger functions under a language, byte-identical to src/schema.sql's for `english` so the blob replay after a migration leaves the catalog unchanged; used by `reindex-search-vector` and the migration). Every indexing `to_tsvector` reads through `gbrain_fts_input`; `applyFtsLanguagePolicy`'s `to_tsvector('english',` prefix rewrite still matches. Pinned by `test/fts-cjk-boundary.test.ts`, `test/fts-cjk-boundary-search.test.ts`, `test/e2e/fts-cjk-boundary-postgres.test.ts`.
+- `src/core/search-vector-backfill.ts` — keyset-batched rebuilds of stored keyword vectors, shared by `reindex-search-vector` (every row) and the `fts_cjk_boundary` migration (an optional `where` limits it to rows with a CJK boundary). `backfillChunkVectors` recomputes `content_chunks.search_vector` with `chunkSearchVectorSql`; `backfillPageVectors` (#6374) reads each batch through an UPDATE-to-self of `id` (`RETURNING id, slug, source_id, timeline, knowledge_revision` plus whether a `fact_withdrawals`/`fact_purges` row covers the page or its whole source), takes the seal's effective timeline (the raw column, or for a withdrawn/purged page `readPageSnapshot`'s overlaid timeline, so a database withdrawal never returns to the vector), sanitizes it with `sanitizeRemoteBody` as the seal does, and writes `search_vector` through `pageSearchVectorSql` in one `UPDATE … FROM unnest(…)` guarded by the revision read (a page edited in between is skipped; its seal reindexes it). `BACKFILL_BATCH_SIZE` 5000 rows per statement, never one transaction; the cursor persists after every batch under `backfill.<checkpoint>.last_id` and the caller clears it. Pinned by `test/reindex-search-vector.serial.test.ts`, `test/reindex-search-vector-pages.serial.test.ts`, `test/fts-cjk-boundary.test.ts`, `test/search-vector-backfill-withdrawal.test.ts`. FTS write expressions (`src/core/fts-language.ts`, #6370): `FTS_INPUT_FUNCTION_SQL` (`gbrain_fts_input(text)`, IMMUTABLE STRICT PARALLEL SAFE, `search_path = pg_catalog`: two `regexp_replace` passes built from `CJK_SLUG_CHARS` that insert a space at every CJK→ASCII-alnum and ASCII-alnum→CJK boundary; a byte-for-byte no-op without CJK, idempotent; spliced into src/schema.sql by `build:schema`), `FTS_CJK_BOUNDARY_REGEX` (the rows the `fts_cjk_boundary` migration rebuilds), `pageSearchVectorSql` (the sealed page vector used by the seal, the import seal and `search-vector-backfill.ts`), `chunkSearchVectorSql`, and `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (the two trigger functions under a language, byte-identical to src/schema.sql's for `english` so the blob replay after a migration leaves the catalog unchanged; used by `reindex-search-vector` and the migration). Every indexing `to_tsvector` reads through `gbrain_fts_input`; `applyFtsLanguagePolicy`'s `to_tsvector('english',` prefix rewrite still matches. Pinned by `test/fts-cjk-boundary.test.ts`, `test/fts-cjk-boundary-search.test.ts`, `test/e2e/fts-cjk-boundary-postgres.test.ts`.
- `src/core/schema-migrations/v232-fts-cjk-boundary.ts` — #6370, handler-only and idempotent: creates `gbrain_fts_input`, recreates both search_vector trigger functions under `getFtsLanguage()` with the shared builders, then rebuilds only pages (`title`/`timeline`) and chunks (`chunk_text`/`doc_comment`/`symbol_name_qualified`) matching `FTS_CJK_BOUNDARY_REGEX` through `search-vector-backfill.ts` (checkpoints `fts_cjk_pages`/`fts_cjk_content_chunks`, cleared at the end); every other row's vector is byte-identical under the helper and is not touched. Pinned by `test/fts-cjk-boundary.test.ts` and `test/e2e/fts-cjk-boundary-postgres.test.ts`.
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index 9c44bf5323..061a2aa97c 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/guardrails.ts` — vendor-neutral content guardrail seams (`registerGuardrailProvider`, `classify`). `loadGuardrailProvidersFromEnv(env = process.env, opts?: { cwd, skipCwdCheck })` accepts ONLY an absolute path or a `~/` path for `GBRAIN_GUARDRAILS_MODULE`; cwd-relative specs (`./`, `../`, bare `.`) and bare package specifiers (`pkg`, `@scope/pkg`, `pkg/sub` — in the compiled binary Bun's module walk-up starts at the cwd, so a hostile checkout's `node_modules/<name>/` would load) throw `GuardrailLoadError` before any import, and when `env` is `process.env` (or `opts.cwd` is given) a spec that a cwd .env file assigns is refused via `cwdDotenvAssignsKey` (message composed from env-trust's `CWD_DOTENV_REMEDIATION`) unless `opts.skipCwdCheck` (preflight's cwd == config-dir case). node:path/url/os are static imports. Registration is counted by EVENTS against a pre-import baseline so import-time side-effect registration and same-id replacement are accepted (#3688 residual). Pinned by `test/guardrails.test.ts` + `test/guardrails-env-load.test.ts`.
-- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Issuance caps the resolved access-token lifetime (positive `oauth_clients.token_ttl` override, else the server default) at `TOKEN_TTL_MAX_SECONDS` from `src/core/grants/model.ts`, so a stored or configured lifetime above 90 days never mints a longer token (`test/oauth-token-ttl-clamp.test.ts`, both engines). `canonicalOAuthResource(requested, canonical)` is the one RFC 8707 resource canonicalizer: with the provider's `resourceUrl` (serve-http passes the /mcp URL derived from the configured public URL, never `Host`), `begin()`, code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else with `invalid_target` naming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. #6202 first-consent source choice: `begin()` marks a request `sourceChoice.editable` only for a self-registered client's first consent (`registered_via='dcr'`, set by the DCR insert and by migration `oauth_client_registered_via` as a nullable column; `grant_revision = 0`; no `client_credentials`; a source grant) and offers the active sources; `decide(id, approve, choice?)` refuses a choice on a denial, a read-only request or an unoffered source with 403 before claiming the request, and for an editable request calls `recordFirstConsentInTransaction` (`grants/service.ts`) inside the locked transaction before the code insert: revision 0 → 1 with an `action='consent'`, `actor='owner'` audit row even for an unchanged source, the chosen source validated against active sources (a `GrantError` maps to 409 `client_policy_changed`, request terminal). `registered_via` is part of `policyDigest`. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions (the POST body allows `source_id` only as a string on `approve`; any other key or shape is 403 `invalid_consent`), and adds a `read write` bootstrap scope hint to scope-less `/mcp` Bearer challenges without changing token authority (`grantScopes` caps every request to the client row's scope, so a read-only row still yields a read-only token); `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell; for an editable request the write source is a select of the offered sources (read sources mirror it) and `source_id` is posted only when it differs from the current source. Tests: `test/oauth-owner-consent.test.ts`, `test/oauth-consent-security.test.ts`, `test/oauth-client-registered-via-migration.test.ts`, `test/e2e/oauth-owner-consent-source-postgres.test.ts`, `test/e2e/oauth-client-registered-via-postgres.test.ts`, `admin/e2e/admin.pw.ts`.
+- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Issuance caps the resolved access-token lifetime (positive `oauth_clients.token_ttl` override, else the server default) at `TOKEN_TTL_MAX_SECONDS` from `src/core/grants/model.ts`, so a stored or configured lifetime above 90 days never mints a longer token (`test/oauth-token-ttl-clamp.test.ts`, both engines). `canonicalOAuthResource(requested, canonical)` is the one RFC 8707 resource canonicalizer: with the provider's `resourceUrl` (serve-http passes the /mcp URL derived from the configured public URL, never `Host`), `begin()`, code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else with `invalid_target` naming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. #6202 first-consent source choice: `begin()` marks a request `sourceChoice.editable` only for a self-registered client's first consent (`registered_via='dcr'`, set by the DCR insert and by migration `oauth_client_registered_via` as a nullable column; `grant_revision = 0`; no `client_credentials`; a source grant) and offers the active sources; `decide(id, approve, choice?)` refuses a choice on a denial, a read-only request or an unoffered source with 403 before claiming the request, and for an editable request calls `recordFirstConsentInTransaction` (`grants/service.ts`) inside the locked transaction before the code insert: revision 0 → 1 with an `action='consent'`, `actor='owner'` audit row even for an unchanged source, the final source share-locked and required active on every first consent, changed or not (a `GrantError` maps to 409 `client_policy_changed`, request terminal). `registered_via` is part of `policyDigest`. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions (the POST body allows `source_id` only as a string on `approve`; any other key or shape is 403 `invalid_consent`), and adds a `read write` bootstrap scope hint to scope-less `/mcp` Bearer challenges without changing token authority (`grantScopes` caps every request to the client row's scope, so a read-only row still yields a read-only token); `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell; for an editable request the write source is a select of the offered sources (read sources mirror it) and `source_id` is posted only when it differs from the current source. Tests: `test/oauth-owner-consent.test.ts`, `test/oauth-consent-security.test.ts`, `test/oauth-client-registered-via-migration.test.ts`, `test/e2e/oauth-owner-consent-source-postgres.test.ts`, `test/e2e/oauth-client-registered-via-postgres.test.ts`, `admin/e2e/admin.pw.ts`.
- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and reads the token's source, operation and takes-holder grant through `resolveTokenGrant` (`src/core/grants/legacy-token.ts`, shared with the legacy HTTP transport so the two transports cannot drift; a legacy-shape row converts to the grant columns on that read; `[]` takes-holders preserved as explicit deny-all, NULL → the `/mcp` dispatch site's fail-closed `['world']`). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`). `authorize()` only calls `grants.begin()` and redirects to `/admin/?oauth_request=<id>#oauth-consent`; codes are minted solely in `OAuthGrants.decide()` behind the admin cookie session and session-bound CSRF. `registerClient` (the unauthenticated DCR store method) computes the `grant_types` default (`authorization_code`) BEFORE the scope block, then calls `dcrScopeViolation` once and throws `InvalidClientMetadataError` (HTTP 400) on a privileged request — rejected, never silently dropped — before the unknown-scope filter runs; a registration that omits `scope` registers an empty scope (no default scope) and its consent request carries `scopes: []`. `allowClientCredentialsDcr` (`--enable-dcr-insecure`) yields anonymous READ-ONLY machine clients; that gate is evaluated BEFORE `dcrScopeViolation`, so a `client_credentials` request without the flag gets 'not permitted via dynamic client registration' rather than the misleading 'limited to `read`' ceiling message (pinned in `test/oauth-dcr-scope-ceiling.test.ts`). Downstream is already bounded: `OAuthGrants.begin()` snapshots the intersected grant, `exchangeCode` and `verifyAccessToken` re-intersect with the client's current scope. Operator paths (`registerClientManual`, CLI, admin API) do not use this store method and accept every canonical scope. Pinned in-process by `test/oauth-consent-security.test.ts` (live SDK `/register` with a foreign `redirect_uri`), against the real server by `test/e2e/serve-http-consent.test.ts`, and for the ceiling by `test/oauth-dcr-scope-ceiling.test.ts` + `test/oauth-authorize-scope-default.test.ts` (DCR client: `/authorize` `read write admin` -> code `['read','write']`, `admin` alone -> `[]`).
diff --git a/src/core/grants/service.ts b/src/core/grants/service.ts
index 6426ffc016..91dc4b80d3 100644
--- a/src/core/grants/service.ts
+++ b/src/core/grants/service.ts
@@ -163,8 +163,9 @@ export async function clientHoldsAuthorization(db: GrantDatabase, clientId: stri
* the revision moves 0 → 1 with an `action='consent'` audit row even when the
* source is unchanged, so the client is never offered the choice again and a
* second pending request fails its policy check. A new `sourceId` lands in
- * `source_id` + `federated_read` and is validated against active sources;
- * nothing else in the grant changes.
+ * `source_id` + `federated_read`; nothing else in the grant changes. The
+ * final grant is validated on every first consent, and its source is
+ * share-locked and must be active, changed or not.
*/
export async function recordFirstConsentInTransaction(db: GrantDatabase, clientId: string, sourceId: string | undefined, actor: string): Promise<GrantMutationResult> {
const sql = query(db);
@@ -175,10 +176,13 @@ export async function recordFirstConsentInTransaction(db: GrantDatabase, clientI
if (before.revision !== 0) throw new GrantError('grant_conflict', `Grant changed (expected revision 0, current ${before.revision}); review a fresh request`);
if (await clientHoldsAuthorization(sql, clientId)) throw new GrantError('grant_conflict', 'The client already holds an authorization; review a fresh request');
const after: ClientGrant = { ...before, revision: 1 };
- if (sourceId !== undefined && sourceId !== before.sourceId) {
- Object.assign(after, { sourceId, federatedRead: [sourceId], sourcesNone: false });
- validateClientGrant(after, await grantValidationContext(db));
+ if (sourceId !== undefined && sourceId !== before.sourceId) Object.assign(after, { sourceId, federatedRead: [sourceId], sourcesNone: false });
+ // Share-lock the final source through commit, so it cannot be archived between this check and the code insert.
+ if (after.sourceId != null) {
+ const [source] = await sql`SELECT archived FROM sources WHERE id = ${after.sourceId} FOR SHARE`;
+ if (!source || source.archived === true) throw new GrantError('invalid_grant', `Source "${after.sourceId}" is not active; review a fresh request`);
}
+ validateClientGrant(after, await grantValidationContext(db));
await persistGrant(sql, before, after, actor, 'consent');
return { before, after, revision: 1, dryRun: false };
}
diff --git a/src/core/search-vector-backfill.ts b/src/core/search-vector-backfill.ts
index dd7de2b052..b22687d234 100644
--- a/src/core/search-vector-backfill.ts
+++ b/src/core/search-vector-backfill.ts
@@ -66,23 +66,43 @@ export async function backfillChunkVectors(engine: BrainEngine, opts: VectorBack
* only, never across the TypeScript sanitize), sanitizes the timeline exactly
* as the seal does, then writes `search_vector` guarded by the knowledge
* revision it read: a page edited in between is skipped, and its own seal
- * indexes it under the current trigger. Returns rows read.
+ * indexes it under the current trigger. The timeline is the seal's input: a
+ * page with a database withdrawal or purge (its own or source-wide) is read
+ * through `readPageSnapshot`, whose timeline carries that overlay, so a
+ * withdrawn fact never returns to the vector; other pages' raw timeline is
+ * already their effective one. Returns rows read.
*/
export async function backfillPageVectors(engine: BrainEngine, opts: VectorBackfillOpts): Promise<number> {
let cursor = await savedCursor(engine, opts.checkpoint);
let total = 0;
for (;;) {
- const rows = await engine.executeRaw<{ id: number; timeline: string | null; knowledge_revision: string }>(`
+ const rows = await engine.executeRaw<{ id: number; slug: string; source_id: string; timeline: string | null; knowledge_revision: string; withdrawn: boolean }>(`
UPDATE pages SET id = id
WHERE id IN (${batchIds('pages', cursor, opts.where)})
- RETURNING id, timeline, knowledge_revision::text AS knowledge_revision
+ RETURNING id, slug, source_id, timeline, knowledge_revision::text AS knowledge_revision,
+ (EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = pages.source_id AND (w.subject = '*' OR w.subject = pages.slug))
+ OR EXISTS (SELECT 1 FROM fact_purges x WHERE x.source_id = pages.source_id AND (x.subject = '*' OR x.subject = pages.slug))) AS withdrawn
`);
if (rows.length === 0) break;
+ const ids: number[] = [];
+ const timelines: string[] = [];
+ const revisions: string[] = [];
+ for (const r of rows) {
+ let timeline = r.timeline ?? '';
+ if (r.withdrawn) {
+ const snapshot = await engine.readPageSnapshot(r.slug, { sourceId: r.source_id, includeDeleted: true });
+ if (!snapshot) continue;
+ timeline = snapshot.page.timeline ?? '';
+ }
+ ids.push(Number(r.id));
+ timelines.push(sanitizeRemoteBody(timeline));
+ revisions.push(r.knowledge_revision);
+ }
await engine.executeRaw(`
UPDATE pages p SET search_vector = ${pageSearchVectorSql('p.title', 'v.timeline', opts.lang)}
FROM unnest($1::int[], $2::text[], $3::uuid[]) AS v(id, timeline, revision)
WHERE p.id = v.id AND p.knowledge_revision = v.revision
- `, [rows.map(r => Number(r.id)), rows.map(r => sanitizeRemoteBody(r.timeline ?? '')), rows.map(r => r.knowledge_revision)]);
+ `, [ids, timelines, revisions]);
total += rows.length;
opts.tick?.(rows.length);
cursor = rows.reduce((m, r) => Math.max(m, Number(r.id)), cursor);
diff --git a/test/oauth-owner-consent.test.ts b/test/oauth-owner-consent.test.ts
index e523c88373..cde4ab37e9 100644
--- a/test/oauth-owner-consent.test.ts
+++ b/test/oauth-owner-consent.test.ts
@@ -187,6 +187,25 @@ describe('#6202: the owner picks a self-registered client\'s source at its first
expect(await clientRow(racing)).toMatchObject({ source_id: 'default', grant_revision: 0 });
});
+ for (const explicit of [false, true]) {
+ test(`an unchanged source archived after review fails 409 and keeps eligibility (${explicit ? 'explicit' : 'omitted'} choice)`, async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('kept-example', 'kept-example') ON CONFLICT (id) DO NOTHING`);
+ const clientId = await registerDcr();
+ await engine.executeRaw(`UPDATE oauth_clients SET source_id = 'kept-example', federated_read = '{kept-example}' WHERE client_id = $1`, [clientId]);
+ const id = await beginFor(clientId);
+ await engine.executeRaw(`UPDATE sources SET archived = true WHERE id = 'kept-example'`);
+ try {
+ await expect(dcrProvider.grants.decide(id, true, explicit ? { sourceId: 'kept-example' } : undefined))
+ .rejects.toMatchObject({ status: 409, code: 'client_policy_changed' });
+ expect(await clientRow(clientId)).toMatchObject({ source_id: 'kept-example', grant_revision: 0 });
+ expect(await audits(clientId)).toEqual([]);
+ expect(await codes(clientId)).toHaveLength(0);
+ } finally {
+ await engine.executeRaw(`UPDATE sources SET archived = false WHERE id = 'kept-example'`);
+ }
+ });
+ }
+
test('a pre-migration DCR row (no marker) keeps read-only consent', async () => {
const clientId = await registerDcr();
await engine.executeRaw('UPDATE oauth_clients SET registered_via = NULL WHERE client_id = $1', [clientId]);
diff --git a/test/search-vector-backfill-withdrawal.test.ts b/test/search-vector-backfill-withdrawal.test.ts
new file mode 100644
index 0000000000..993688dcb4
--- /dev/null
+++ b/test/search-vector-backfill-withdrawal.test.ts
@@ -0,0 +1,62 @@
+/**
+ * Page-vector rebuilds read the seal's effective timeline (CSO finding on
+ * wave 13 PR4): a fact withdrawn in the database ledger stays in the raw
+ * timeline column, and the seal indexes the snapshot with the withdrawal
+ * overlay. `reindex-search-vector` (backfillPageVectors) and the
+ * fts_cjk_boundary migration must not put the withdrawn term back.
+ *
+ * R3/R4: engine in beforeAll, disconnect in afterAll; state reset per test.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';
+import { rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';
+import { backfillPageVectors } from '../src/core/search-vector-backfill.ts';
+import { MIGRATIONS } from '../src/core/migrate.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+const SLUG = 'notes/withdrawal-example';
+const CLAIM = 'withdrawncanary example fact';
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); });
+
+async function withdrawnPage(title: string): Promise<void> {
+ const fence = renderFactsTable([{ rowNum: 1, claim: CLAIM, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true }]);
+ await engine.putPage(SLUG, { type: 'note', title, compiled_truth: 'Safe prose.', timeline: fence, frontmatter: {} });
+ const fact = await engine.insertFact({ fact: CLAIM, source: 'withdrawal-fixture', visibility: 'world' }, { source_id: 'default' });
+ await recordFactWithdrawal(engine, fact.id, 'default', true, { semanticReview: false });
+ await rebuildPendingPageProjections(engine, 100);
+}
+const state = async () => (await engine.executeRaw<{ v: string; raw: string; sealed: boolean }>(
+ `SELECT search_vector::text AS v, timeline AS raw, text_projection_revision = knowledge_revision AS sealed FROM pages WHERE slug = $1`, [SLUG]))[0]!;
+
+describe('page-vector rebuilds keep database withdrawals out', () => {
+ test('backfillPageVectors indexes the withdrawal overlay, not the raw timeline', async () => {
+ await withdrawnPage('Withdrawal example');
+ const before = await state();
+ expect(before.raw).toContain(CLAIM);
+ expect(before.v).not.toContain('withdrawncanari');
+ await backfillPageVectors(engine, { lang: 'english', checkpoint: 'withdrawal-test' });
+ const after = await state();
+ expect(after.v).not.toContain('withdrawncanari');
+ expect(after.sealed).toBe(true);
+ expect((await engine.searchTitles('withdrawncanary')).map(r => r.slug)).toEqual([]);
+ });
+
+ test('the fts_cjk_boundary migration rebuild does the same for a CJK-titled page', async () => {
+ await withdrawnPage('升级PostgreSQL17指南');
+ await MIGRATIONS.find(m => m.name === 'fts_cjk_boundary')!.handler!(engine);
+ const after = await state();
+ expect(after.v).toContain("'postgresql17'");
+ expect(after.v).not.toContain('withdrawncanari');
+ expect((await engine.searchTitles('withdrawncanary')).map(r => r.slug)).toEqual([]);
+ });
+});