diff --git a/.baseline/product/README.md b/.baseline/product/README.md index 6047e64..2a471b1 100644 --- a/.baseline/product/README.md +++ b/.baseline/product/README.md @@ -192,7 +192,45 @@ The embeddings stay on Workers AI (`@cf/baai/bge-base-en-v1.5`) either way: the index's column is sized to that model's 768 dimensions, and a question embedded by one model cannot be compared with docs embedded by another. Changing the embedding model is a migration plus re-indexing every page -(`POST /api/embeddings?refresh=1`); `ai/context/operations.md` says how. +(`POST /api/embeddings?refresh=1`, below); `ai/context/operations.md` says +how. + +## Re-embedding every page + +`POST /api/embeddings` — what every deploy's smoke calls — needs nothing: +it embeds only the pages whose checksum the database does not hold, so a +call with unchanged docs embeds nothing, and two at once embed a page once. +Its `?refresh=1` (upstream's `--refresh`) embeds EVERY page again, billed +to your Workers AI, so it needs a bearer: the environment's +`REINDEX_TOKEN`. Without one stored, refresh answers 403 and embeds +nothing — which is how a new product starts. + +1. **Store a token**, once per environment, as this repository's Orun + secret (stage and prod can each hold their own): + + ```bash + openssl rand -hex 32 # a token; keep it + orun secrets set REINDEX_TOKEN --env stage # prompts for the value + orun secrets set REINDEX_TOKEN --env prod + ``` + + The build never sees it: the deploy hands it to the Worker as a Worker + secret (`wrangler secret bulk`), so it is in no bundle and no log. +2. **Redeploy the app** (storing a secret deploys nothing): Orunbase's + Deploy button, or `gh workflow run ci.yml --ref main -f environment= + -f component=web`. +3. **Refresh**: + + ```bash + curl -X POST -H "Authorization: Bearer " \ + https://doc-search-web-..workers.dev/api/embeddings?refresh=1 + ``` + + A missing or wrong bearer gets 403 and embeds nothing. + +To turn refresh off again, delete the Orun secret and the Worker secret +(`pnpm exec wrangler secret delete REINDEX_TOKEN --name doc-search-web-` +from `apps/web`): a deploy pushes the secrets that exist and deletes none. ## Tuning the search diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index aea79df..bd550ad 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -259,7 +259,7 @@ at the tag and refuses the whole catalogue if it 404s. | web smoke fails on `"sections":0` after the index answered ok | the index stored nothing: `pages/docs` holds no `.mdx`, or `lib/docs/index.generated.json` was committed empty. Run `pnpm --filter @app/web docs:index`, commit it, and re-run | | web deploy refused over the `AI` binding (an authentication error naming Workers AI) | the brokered deploy token cannot attach a Workers AI binding in this account. Reconnect Cloudflare with the recipe's permission groups (adding Workers AI if the recipe lists it) and re-run the phase | | the search says the documentation has not been indexed yet | no deploy has indexed this environment (its smoke step never ran), or the database was reset. `curl -X POST /api/embeddings` indexes it now | -| the search answers "Sorry, I don't know how to help with that." to every question | nothing scores above `MATCH_THRESHOLD` (0.6 by default). Lower it with a Worker secret (the product's README, "Tuning the search"), or `POST /api/embeddings?refresh=1` if the sections were embedded by another model | +| the search answers "Sorry, I don't know how to help with that." to every question | nothing scores above `MATCH_THRESHOLD` (0.6 by default). Lower it with a Worker secret (the product's README, "Tuning the search"), or `POST /api/embeddings?refresh=1` with the `REINDEX_TOKEN` bearer if the sections were embedded by another model (the product's README, "Re-embedding every page") | | `build-app` fails: `Symlink apps/web/node_modules/next is invalid, it points out of the filesystem root` | the product's intent pins stack-tectonic ≥ 0.20.0, whose lane-scoped install links each job's node_modules out of its tree, which Next 16's Turbopack refuses. Pin 0.19.0 (`intent.yaml` says why) | | `verify-app-structure` fails: `test -f "wrangler.jsonc"` | the product's `apps/web/wrangler.jsonc` is not committed. It must be — the check runs before the build in a fresh checkout (`pnpm run wire:fixture` renders it) | | Convergence failed AFTER the PR merged; re-running lands nothing | expected on its own — the files are on main. Re-run the phase (`--phase 01-product`, `--redo 01-product`, or the console's Retry): its `retouch` hook gives the landing a diff and the components re-plan; the project and the config are adopted, not recreated | diff --git a/ai/context/open-risks.md b/ai/context/open-risks.md index 0477d37..1596aff 100644 --- a/ai/context/open-risks.md +++ b/ai/context/open-risks.md @@ -12,9 +12,10 @@ what is still live, so it should be short. | DQ-C | The deploy's smoke indexes the docs: a Workers AI or Hyperdrive outage at deploy time fails the smoke (and the lane), and a deploy with many changed pages makes one request do every page's embedding | OPEN | The first live deploys; split the indexing into batches if a real doc set needs it | | DQ-D | `MATCH_THRESHOLD`'s default (0.6) is chosen for BGE base, not measured on these docs | OPEN | Measure real scores on the sample docs after the first live bootstrap | -Accepted, and worth knowing before you change them: DQ-E (`POST -/api/embeddings` takes no credential: it can only embed the docs the Worker -was built with, and an unchanged page costs one SELECT), DQ-F (two Supabase +Accepted, and worth knowing before you change them: DQ-E (the plain `POST +/api/embeddings` is open by design — it can only embed the docs the Worker +was built with, and an unchanged page costs one SELECT — while `?refresh=1`, +which re-embeds everything, needs the `REINDEX_TOKEN` bearer), DQ-F (two Supabase projects per product — the organization needs room for both), DQ-G (the e2e's Postgres stand-in creates pgvector as superuser; a real db-migrate apply is the first time `postgres` runs that statement). diff --git a/ai/context/operations.md b/ai/context/operations.md index d6b5253..0f2f135 100644 --- a/ai/context/operations.md +++ b/ai/context/operations.md @@ -105,7 +105,8 @@ Caveats that matter: `nods_page_section.embedding` is `vector(768)` because `@cf/baai/bge-base-en-v1.5` is 768-dimensional. Changing the model means a new migration that resizes the column and the function, AND re-indexing - every page (`POST /api/embeddings?refresh=1`): vectors from two models + every page (`POST /api/embeddings?refresh=1` with the environment's + `REINDEX_TOKEN` as a bearer — README, "Re-embedding every page"): vectors from two models share no space, even at the same size. Changing the ANSWER model is a one-line change in `lib/ai/models.ts`, with no migration. - **How strict the search is** is `MATCH_THRESHOLD` (cosine similarity, @@ -186,10 +187,10 @@ orun integrations list --org --json && orun cloud check --org | deploy a change | merge to `main`; watch the run; failed lanes → `gh run rerun --failed` | | deploy by hand | Orunbase's Deploy button, or `gh workflow run ci.yml --ref main -f environment= [-f component=]` — the named components (blank: every one) run in that environment as a merge runs them; started off `main` it is refused | | change the docs | edit `apps/web/pages/docs/**/*.mdx`, `pnpm --filter @app/web docs:index`, commit both, merge — the deploy embeds the pages that changed | -| index now | `curl -X POST https://doc-search-web-.…workers.dev/api/embeddings` (idempotent: unchanged pages embed nothing; `?refresh=1` embeds every page again) | +| index now | `curl -X POST https://doc-search-web-.…workers.dev/api/embeddings` (open and idempotent: unchanged pages embed nothing). `?refresh=1` embeds every page again and needs `-H "Authorization: Bearer $REINDEX_TOKEN"`, the environment's Orun secret (README, "Re-embedding every page"); without it, 403 | | change the schema | a new `packages/db/src/migrations/_/up.sql` and its manifest entry (`pnpm --filter @saas/db run manifest:fix` for its checksum), merge — db-migrate applies it before the app deploys. Keep row-level security on every table in `public` | | change the answer model | `WORKERS_AI_CHAT_MODEL` in `apps/web/lib/ai/models.ts` | -| change the embedding model | a new migration resizing `nods_page_section.embedding` and `match_page_sections()`, `WORKERS_AI_EMBEDDING_MODEL` and `EMBEDDING_DIMENSIONS` in `lib/ai/models.ts`, then `POST /api/embeddings?refresh=1` per environment | +| change the embedding model | a new migration resizing `nods_page_section.embedding` and `match_page_sections()`, `WORKERS_AI_EMBEDDING_MODEL` and `EMBEDDING_DIMENSIONS` in `lib/ai/models.ts`, then `POST /api/embeddings?refresh=1` with the bearer, per environment | | tune the search | `wrangler secret put MATCH_THRESHOLD --name doc-search-web-` (cosine similarity; default 0.6) | | redeploy without a change | edit the last line of the component's `component.yaml` (`# orun: redeploy `) and merge — it is a deploy trigger, nothing reads it | | use OpenAI for the answers | above | diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example index ce730d3..f4ace1e 100644 --- a/apps/web/.dev.vars.example +++ b/apps/web/.dev.vars.example @@ -14,6 +14,12 @@ # OPENAI_API_KEY= # OPENAI_MODEL=gpt-3.5-turbo # +# The bearer `POST /api/embeddings?refresh=1` (re-embed every page) needs. +# Unset, refresh answers 403; the plain POST, which embeds only changed +# pages, needs nothing. In stage/prod it is the Orun secret REINDEX_TOKEN, +# which the deploy hands to the Worker (README, "Re-embedding every page"). +# REINDEX_TOKEN= +# # How similar a section must be to the question to reach the answer, as # cosine similarity (lib/search.ts, default 0.6). # MATCH_THRESHOLD=0.6 diff --git a/apps/web/.env.example b/apps/web/.env.example index d451c96..d86bfcc 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -11,3 +11,6 @@ DATABASE_URL=postgres://postgres:postgres@localhost:5432/docs # ANSWERS are OpenAI's; `next dev` reads it from here, `wrangler dev` from # .dev.vars. # OPENAI_API_KEY= +# Optional. The bearer POST /api/embeddings?refresh=1 needs; unset, refresh +# answers 403 (the plain POST needs nothing). +# REINDEX_TOKEN= diff --git a/apps/web/README.md b/apps/web/README.md index b885a45..75b3ff3 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -19,7 +19,9 @@ Vercel lists it at https://vercel.com/templates/next.js/nextjs-openai-doc-search `lib/docs/index.generated.json`, with upstream's MDX processing in `lib/docs/process-mdx.ts`); the deploy's smoke step POSTs here, and the Worker embeds every page whose checksum the database does not hold - (`lib/docs/sync.ts`). + (`lib/docs/sync.ts`). `?refresh=1` re-embeds every page and needs the + environment's `REINDEX_TOKEN` as a bearer (`lib/reindex.ts`); unset, it + answers 403. - `/api/health`: 200 only when the database is reachable through Hyperdrive and migrated; it says how much of the docs is indexed and calls no model. diff --git a/apps/web/app/api/embeddings/route.ts b/apps/web/app/api/embeddings/route.ts index 141123e..609b3e8 100644 --- a/apps/web/app/api/embeddings/route.ts +++ b/apps/web/app/api/embeddings/route.ts @@ -3,6 +3,7 @@ import type { DocsIndex } from '@/lib/docs/index-types' import { syncDocs } from '@/lib/docs/sync' import { DatabaseNotConfiguredError, getSql } from '@/lib/db' import { AiNotConfiguredError, embeddingModel } from '@/lib/ai/models' +import { refreshRefusal } from '@/lib/reindex' // Not upstream's route — upstream's step, moved. Upstream embedded the docs // at `pnpm build` (`pnpm run embeddings`), with OpenAI's key and Supabase's @@ -18,11 +19,23 @@ import { AiNotConfiguredError, embeddingModel } from '@/lib/ai/models' // and only the pages whose checksum the database does not already hold, so // calling it again — by the next deploy, a retry, or anybody — does one SELECT // per page and embeds nothing. `?refresh=1` is upstream's `--refresh`: embed -// every page again, which only a change of embedding model calls for. +// every page again, which only a change of embedding model calls for. That +// one costs Workers AI on every call, so it needs the environment's +// REINDEX_TOKEN as a bearer (lib/reindex.ts) — refused with a 403, before the +// database or the model is reached, when it is missing, wrong, or unset. export const dynamic = 'force-dynamic' export async function POST(req: Request) { const refresh = new URL(req.url).searchParams.get('refresh') === '1' + if (refresh) { + const refusal = await refreshRefusal(req) + if (refusal) { + return Response.json( + { ok: false, error: refusal }, + { status: 403, headers: { 'cache-control': 'no-store' } } + ) + } + } let sql: Awaited> | undefined try { sql = await getSql() diff --git a/apps/web/cloudflare-env.d.ts b/apps/web/cloudflare-env.d.ts index 040f0cb..7397ef5 100644 --- a/apps/web/cloudflare-env.d.ts +++ b/apps/web/cloudflare-env.d.ts @@ -10,6 +10,9 @@ interface CloudflareEnv { ASSETS: Fetcher; // Optional Worker secret (lib/ai/models.ts): upstream's OpenAI answer model. OPENAI_API_KEY?: string; + // Optional Worker secret (lib/reindex.ts): the bearer POST + // /api/embeddings?refresh=1 needs. Unset, refresh is off. + REINDEX_TOKEN?: string; // Optional Worker vars: which OpenAI chat model (default upstream's), and // how similar a section must be to reach the answer (lib/search.ts). OPENAI_MODEL?: string; diff --git a/apps/web/component.yaml b/apps/web/component.yaml index b63fceb..bd39a90 100644 --- a/apps/web/component.yaml +++ b/apps/web/component.yaml @@ -55,6 +55,16 @@ spec: secretEnv: WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://doc-search/doc-search/stage/WIRING_CLOUDFLARE_HYPERDRIVE" WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://doc-search/doc-search/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + # REINDEX_TOKEN: the bearer `POST /api/embeddings?refresh=1` (re-embed every + # page) needs (lib/reindex.ts). The owner stores it as an Orun secret per + # environment (README → Re-embedding every page); the build runs without it + # and then hands it to the Worker as a SECRET (buildCommand below). + # BEST-EFFORT, wire-now-seed-later: a key nobody has stored is skipped when + # the job resolves its secrets (no env var, no failure), and the Worker + # without it refuses refresh — so a fresh product deploys and indexes + # before anyone has chosen a token. + optionalSecretEnv: + REINDEX_TOKEN: "secret://doc-search/doc-search/{{ .environment }}/REINDEX_TOKEN" subscribe: environments: - name: dev @@ -104,7 +114,14 @@ spec: # No public origin is baked in: the page renders no absolute URL (no Open # Graph image, no canonical link), and every request it makes is to its # own origin. ${ORUN_ENVIRONMENT} the runner sets for every step. - buildCommand: if [ "${ORUN_ENVIRONMENT}" != dev ]; then node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-hyperdrive --env "${ORUN_ENVIRONMENT}"; fi && pnpm exec turbo run build --filter=@app/web + # + # REINDEX_TOKEN never reaches the build (`env -u`), so neither a bundle + # nor the bundler's cache holds it. Then, if the environment has one, it + # goes to the Worker as a SECRET (tooling/wire/worker-secrets.mjs: + # `wrangler secret bulk`, the value over stdin) before the composition + # deploys it. Only the deploy lane holds a Cloudflare credential, so a + # verify lane builds the same and pushes nothing. + buildCommand: if [ "${ORUN_ENVIRONMENT}" != dev ]; then node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-hyperdrive --env "${ORUN_ENVIRONMENT}"; fi && env -u REINDEX_TOKEN pnpm exec turbo run build --filter=@app/web && node ../../tooling/wire/worker-secrets.mjs --secret REINDEX_TOKEN --worker "doc-search-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc # Smoke — and the docs' indexing, which is the step upstream ran at build # time (`pnpm run embeddings`). After `wrangler deploy`: diff --git a/apps/web/docs/architecture.md b/apps/web/docs/architecture.md index 8f8be94..c203268 100644 --- a/apps/web/docs/architecture.md +++ b/apps/web/docs/architecture.md @@ -26,3 +26,7 @@ Resolved at deploy time from secrets the infrastructure lanes publish (names onl - `WIRING_CLOUDFLARE_HYPERDRIVE_PROD` - `WIRING_CLOUDFLARE_HYPERDRIVE_STAGE` + +## Secrets resolved by the lane (names only) + +- `REINDEX_TOKEN` (optional) diff --git a/apps/web/lib/reindex.ts b/apps/web/lib/reindex.ts new file mode 100644 index 0000000..a7c592f --- /dev/null +++ b/apps/web/lib/reindex.ts @@ -0,0 +1,48 @@ +import { getCloudflareContext } from '@opennextjs/cloudflare' + +// Not upstream's. `POST /api/embeddings` is open: it embeds only the pages +// whose checksum the database does not hold, so anybody calling it costs one +// SELECT per page, and the deploy's smoke calls it with no credential. Its +// `?refresh=1` — upstream's `--refresh` — is not: it embeds EVERY page again, +// billed to the owner's Workers AI, so it needs the environment's +// REINDEX_TOKEN as a bearer. The token is an optional Worker secret (an Orun +// secret the deploy hands to the Worker, README "Re-embedding every page"). +// Unset, refresh is off. +export const REFRESH_DISABLED = + 'refresh=1 re-embeds every page and is off here: this environment has no REINDEX_TOKEN (README, "Re-embedding every page")' +export const REFRESH_NEEDS_BEARER = 'refresh=1 needs Authorization: Bearer ' + +async function configuredToken(): Promise { + let env: Partial = {} + try { + env = (await getCloudflareContext({ async: true })).env + } catch { + // Not running under OpenNext (a script, a test): no bindings. + } + return env.REINDEX_TOKEN || process.env.REINDEX_TOKEN || undefined +} + +async function digest(value: string): Promise { + return new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))) +} + +/** + * Whether two secrets are equal, in time that depends on neither: both are + * hashed to 32 bytes first (so their lengths are not compared), and every byte + * of the digests is compared, whatever the first difference. + */ +export async function sameSecret(a: string, b: string): Promise { + const [x, y] = await Promise.all([digest(a), digest(b)]) + let difference = 0 + for (let i = 0; i < x.length; i++) difference |= x[i] ^ y[i] + return difference === 0 +} + +/** Null when the request may re-embed everything, else why it may not. */ +export async function refreshRefusal(req: Request): Promise { + const token = await configuredToken() + if (!token) return REFRESH_DISABLED + const bearer = /^Bearer\s+(\S+)\s*$/i.exec(req.headers.get('authorization') ?? '')?.[1] + if (!bearer) return REFRESH_NEEDS_BEARER + return (await sameSecret(bearer, token)) ? null : REFRESH_NEEDS_BEARER +} diff --git a/hooks/render-deployment-docs.sh b/hooks/render-deployment-docs.sh index 6e6a837..47af104 100755 --- a/hooks/render-deployment-docs.sh +++ b/hooks/render-deployment-docs.sh @@ -159,6 +159,7 @@ for the answers is a Worker secret the owner adds per environment (README, | \`SUPABASE_ORG_ID\` | the workspace | the Supabase connection's organization id — a fact, not a credential | | \`SUPABASE_PROJECT_REF\`, \`SUPABASE_DB_PASSWORD\`, \`SUPABASE_DB_URL\` | \`${repo}\` on stage and on prod | written by the Supabase root's apply: the project's ref, its database password and its connection URL, read by Hyperdrive and the migrations | | \`WIRING_CLOUDFLARE_HYPERDRIVE\` | \`${repo}\` on stage and on prod | written by the Hyperdrive root's apply: the config's id and name, not a credential | +| \`REINDEX_TOKEN\` (optional) | \`${repo}\` on stage and on prod, if the owner stores it | the bearer \`POST /api/embeddings?refresh=1\` (re-embed every page) needs; each deploy hands it to the Worker as a Worker secret. Unset, refresh is refused (README, "Re-embedding every page") | Brokered secrets are minted per run, so no long-lived value is at rest. No AI vendor key is a workspace secret: OpenAI's key, if the owner adds it, is diff --git a/specs/epics/README.md b/specs/epics/README.md index 62f0a38..d541db6 100644 --- a/specs/epics/README.md +++ b/specs/epics/README.md @@ -7,6 +7,6 @@ folder is the adoption; the merge creates the epic in the workspace. | Epic | Cluster | Status | What it is | |------|---------|--------|------------| -| [`doc-search/`](./doc-search/) | **DQ** | ✅ Shipped (`baseline-v1`); live bootstrap pending | Supabase's Next.js OpenAI Doc Search — a ⌘K dialog answering questions about the site's own MDX docs — on Cloudflare Workers with Workers AI and Supabase pgvector through Hyperdrive, the docs indexed by the deployed Worker on every deploy, and an Orun baseline that instantiates it in one landing (DQ2) | +| [`doc-search/`](./doc-search/) | **DQ** | ✅ Shipped (`baseline-v2`); live bootstrap pending | Supabase's Next.js OpenAI Doc Search — a ⌘K dialog answering questions about the site's own MDX docs — on Cloudflare Workers with Workers AI and Supabase pgvector through Hyperdrive, the docs indexed by the deployed Worker on every deploy, and an Orun baseline that instantiates it in one landing (DQ2) | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/doc-search/IMPLEMENTATION-STATUS.md b/specs/epics/doc-search/IMPLEMENTATION-STATUS.md index 751a65a..0f2b6cf 100644 --- a/specs/epics/doc-search/IMPLEMENTATION-STATUS.md +++ b/specs/epics/doc-search/IMPLEMENTATION-STATUS.md @@ -4,7 +4,10 @@ |---|---|---| | DQ0 — the spec | ✅ | DQ-1 | | DQ1 — the doc search on Workers and Supabase | ✅ | DQ-2 | -| DQ2 — a baseline | ✅ | DQ-3, tagged `baseline-v1` | +| DQ2 — a baseline | ✅ | DQ-3, tagged `baseline-v1`; DQ-4, tagged `baseline-v2` | + +`baseline-v2` (DQ-4): `POST /api/embeddings?refresh=1` needs the +environment's `REINDEX_TOKEN` as a bearer (departure 16, risk DQ-E). ## Departures from the upstream template @@ -27,6 +30,7 @@ Everything not listed here is the template as it is at `50d6bb7`. | 13 | `supabase/seed.sql` not carried; `supabase/config.toml` dropped | The seed holds ada-002 vectors; the project is Terraform's | | 14 | `app/api/health/route.ts` added | The deploy's smoke and the record's probe: reachable, migrated, how much is indexed | | 15 | `next.config.js` → `next.config.mjs` (standalone output, the trace root, `images.unoptimized`, the dev platform proxy), `open-next.config.ts` and `wrangler.template.jsonc` added; `@types/unist` pinned at upstream's 2.0.6 | OpenNext's build; upstream's MDX types | +| 16 | `--refresh` (upstream's, a build flag only its owner could pass) → `?refresh=1` behind `Authorization: Bearer ` (`lib/reindex.ts`): an optional Orun secret, kept out of the build and handed to the Worker as a Worker secret by `tooling/wire/worker-secrets.mjs`; unset, missing or wrong, a 403 that reaches neither the database nor the model, the bearer compared in constant time. The plain POST stays open | Moved into a public Worker, a re-embed of every page would be anybody's to trigger, billed to the owner (DQ-E) | ## Departures from the reference @@ -40,7 +44,7 @@ Everything not listed here is the template as it is at `50d6bb7`. ## Verified -- `pnpm typecheck`, `lint`, `test` (tests/web 37, tests/db 11) and `build` +- `pnpm typecheck`, `lint`, `test` (tests/web 46, tests/db 11) and `build` green; the Worker is 1.80 MiB gzipped (Workers Free). - Every contract tier, the leak gate and the placement tier pass locally on orun v2.89.0. The e2e tier needs a PostgreSQL server with pgvector diff --git a/specs/epics/doc-search/README.md b/specs/epics/doc-search/README.md index 1725778..865c015 100644 --- a/specs/epics/doc-search/README.md +++ b/specs/epics/doc-search/README.md @@ -10,7 +10,7 @@ product in one landing.** | | | |---|---| -| Status | ✅ Shipped (`baseline-v1`) — proven offline in Baseline CI; live bootstrap pending (risks DQ-A, DQ-B) | +| Status | ✅ Shipped (`baseline-v2`) — proven offline in Baseline CI; live bootstrap pending (risks DQ-A, DQ-B) | | Upstream | [supabase-community/nextjs-openai-doc-search](https://github.com/supabase-community/nextjs-openai-doc-search) (Apache-2.0), Vercel's [Next.js OpenAI Doc Search Starter](https://vercel.com/templates/next.js/nextjs-openai-doc-search-starter), at `50d6bb7` | | Reference | [rag-chatbot](https://github.com/sourceplane/rag-chatbot) — an AI SDK app on Workers AI and Supabase pgvector through Hyperdrive, the 768-dimension migration, db-migrate, the e2e's Workers AI stand-in | | Key | `DQ` | @@ -32,4 +32,4 @@ product in one landing.** |---|---|---| | DQ0 — the spec | the repository, its intent, CI, tooling and spec index; this doc set | DQ-1 | | DQ1 — the doc search on Workers and Supabase | the template in `apps/web`, the models on Workers AI, the docs index and the Worker's indexing, the migrations, the Supabase and Hyperdrive roots, the tests | DQ-2 | -| DQ2 — a baseline | the console card, the build document, the context pack and the baseline's tests | DQ-3 | +| DQ2 — a baseline | the console card, the build document, the context pack and the baseline's tests; the re-embed of every page behind a bearer | DQ-3, DQ-4 | diff --git a/specs/epics/doc-search/design.md b/specs/epics/doc-search/design.md index 429f635..330560c 100644 --- a/specs/epics/doc-search/design.md +++ b/specs/epics/doc-search/design.md @@ -92,8 +92,13 @@ So the work splits in two. more than zero sections. Every deploy indexes what changed and nothing else; a redeploy with the same docs costs one SELECT per page. -The endpoint takes no credential: all it can do is embed the docs the Worker -was built with (risk DQ-E). +The plain POST takes no credential: all it can do is embed the docs the +Worker was built with, and only what changed (risk DQ-E). `?refresh=1` +re-embeds every page, billed to the owner's Workers AI, so it needs the +environment's `REINDEX_TOKEN` as a bearer (`lib/reindex.ts`, compared in +constant time): an optional Orun secret the build never sees and the deploy +hands to the Worker as a Worker secret. Unset, missing or wrong, refresh is +a 403 that reaches neither the database nor the model. ## 5. The models and the search diff --git a/specs/epics/doc-search/epic.yaml b/specs/epics/doc-search/epic.yaml index 6107f4f..c5f40bf 100644 --- a/specs/epics/doc-search/epic.yaml +++ b/specs/epics/doc-search/epic.yaml @@ -28,4 +28,5 @@ spec: - "blueprint.yaml (the console card) and repo-blueprint.yaml (the build) take a new product from nothing to live on stage and prod in one landing, its docs indexed by the deploy's smoke, then record it" - "a product built from it carries the product only, renamed throughout to its own name, repository, Worker, Supabase project and Hyperdrive config" - "Baseline CI is green: contract tests, generated component docs, the blueprint read by the pinned orun, the leak gate, the offline bootstrap and the end-to-end tier" - tasks: [DQ-3] + - "re-embedding every page (POST /api/embeddings?refresh=1) needs the environment's REINDEX_TOKEN as a bearer, refused with a 403 otherwise; the plain POST stays open" + tasks: [DQ-3, DQ-4] diff --git a/specs/epics/doc-search/risks-and-open-questions.md b/specs/epics/doc-search/risks-and-open-questions.md index 00ad0a5..244a019 100644 --- a/specs/epics/doc-search/risks-and-open-questions.md +++ b/specs/epics/doc-search/risks-and-open-questions.md @@ -6,7 +6,7 @@ | DQ-B | The brokered `workers-deploy` token and the `ai` binding | OPEN | No deploy with the brokered token has uploaded a script with an `ai` binding. Cloudflare may ask for a Workers AI permission group; BOOTSTRAP.md's troubleshooting names the fix. The first live deploy closes it | | DQ-C | The deploy's smoke indexes the docs | OPEN | A Workers AI or Hyperdrive outage at deploy time fails the smoke and the lane (a re-run skips the stored pages), and a deploy with many changed pages makes one request embed them all. The sample is one page; a large doc set may need the indexing split into batches | | DQ-D | `MATCH_THRESHOLD`'s default | OPEN | 0.6 cosine is chosen for BGE base, not measured on these docs; upstream's 0.78 was ada-002's inner product. It is a Worker secret per environment (not a var, which the next deploy would reset); measure real scores after the first live bootstrap | -| DQ-E | `POST /api/embeddings` takes no credential | ACCEPTED | It can only embed the docs the Worker was built with; an unchanged page costs one SELECT, and `?refresh=1` re-embeds a handful of sections. A large doc set would want it behind a secret | +| DQ-E | The plain `POST /api/embeddings` is open by design; `?refresh=1` is gated | ACCEPTED | The plain POST — what the deploy's smoke calls — can only embed the docs the Worker was built with, skips every page whose checksum is stored (one SELECT each), and the advisory lock keeps two calls at once to one embedding. `?refresh=1` re-embeds every page, billed to the owner's Workers AI, so since `baseline-v2` it needs `Authorization: Bearer `, an optional Orun secret the deploy hands to the Worker; unset, missing or wrong, it is a 403 before the database or the model is reached, the bearer compared in constant time (`lib/reindex.ts`). In `baseline-v1` refresh was open | | DQ-F | Two Supabase projects per product | ACCEPTED | Stage and prod are a project each; Supabase's free plan allows two active projects per organization. BOOTSTRAP.md lists it as a prerequisite | | DQ-G | pgvector on a real Supabase project | ACCEPTED | `010` creates the `vector` extension as `postgres` through the Management API, as rag-chatbot's does on Supabase; the e2e's stand-in Postgres creates it as superuser, so a real db-migrate apply is the first time `postgres` itself runs it | | DQ-H | `react-hooks/immutability`, `no-explicit-any`, `prefer-as-const` and `no-empty-object-type` are off | ACCEPTED | Upstream's code, kept as written, fails rules new in eslint-config-next 16; each is off by name with the reason in `eslint.config.mjs` | diff --git a/tasks/DQ-4.TaskContract.yaml b/tasks/DQ-4.TaskContract.yaml new file mode 100644 index 0000000..4b0de51 --- /dev/null +++ b/tasks/DQ-4.TaskContract.yaml @@ -0,0 +1,25 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: DQ-4 + title: "Re-embedding every page needs a bearer" +spec: + goal: POST /api/embeddings?refresh=1, which re-embeds every page billed to the owner's Workers AI, answers only a request carrying the environment's REINDEX_TOKEN as a bearer; the plain POST the deploy's smoke calls stays open + affects: + - apps/web + - tooling/wire + - tests/web + - testing + - hooks + - .baseline/product/README.md + - ai/context + - BOOTSTRAP.md + - specs/epics/doc-search + - specs/epics/README.md + - tasks + doneWhen: + - with no REINDEX_TOKEN, refresh=1 answers 403 and embeds nothing; a missing or wrong bearer answers 403, compared in constant time; the right bearer re-embeds every page + - REINDEX_TOKEN is an optional Orun secret the build never sees and the deploy hands to the Worker as a Worker secret + - tests/web and the end-to-end tier assert all three, and every existing check still holds + - Baseline CI is green on main, tagged baseline-v2 + gates: [] diff --git a/testing/e2e.test.sh b/testing/e2e.test.sh index 5a4dfd8..e558e45 100755 --- a/testing/e2e.test.sh +++ b/testing/e2e.test.sh @@ -53,6 +53,8 @@ # question sharing nothing with the docs answered upstream's "Sorry, I # don't know how to help with that."; an empty index answered with a # message, not a failure; a request without a question refused (400); +# `?refresh=1` refused (403, nothing embedded) without its bearer and +# with a wrong one, and re-embedding every page with the right one; # 6. the Data API's view of the same database: both tables have row-level # security, and `anon` and `authenticated` — granted everything Supabase # grants them — read none of the rows the indexing wrote, write none and @@ -314,14 +316,17 @@ printf '{ "name": "fake-workers-ai", "main": "index.js", "compatibility_date": " # stand-in's space (a bag of words, where a question and the section it # matches share a handful of words out of hundreds — far below what two # texts about the same thing score in bge-base-en-v1.5's). It is the Worker -# var an owner sets the same way (lib/search.ts). Everything else — the -# Hyperdrive binding, the assets, the flags — is the built config, under the -# Worker name the stage deploy gives it. Written beside it, in the throwaway -# tree. -python3 - "$work/apps/web/wrangler.jsonc" "$work/apps/web/wrangler.e2e.json" "$repo-web-stage" <<'PY' \ +# var an owner sets the same way (lib/search.ts). REINDEX_TOKEN, the bearer +# `?refresh=1` needs, is set too — a fresh random one: the Worker reads a var +# and a secret alike from its env, and a deploy hands it the Orun secret. +# Everything else — the Hyperdrive binding, the assets, the flags — is the +# built config, under the Worker name the stage deploy gives it. Written +# beside it, in the throwaway tree. +reindex_token="e2e-$(python3 -c 'import secrets; print(secrets.token_hex(16))')" +python3 - "$work/apps/web/wrangler.jsonc" "$work/apps/web/wrangler.e2e.json" "$repo-web-stage" "$reindex_token" <<'PY' \ || { echo "FAIL: could not derive the dev config from the built one" >&2; exit 1; } import json, sys -src, out, name = sys.argv[1:] +src, out, name, reindex_token = sys.argv[1:] cfg = json.loads("\n".join(l for l in open(src).read().splitlines() if not l.lstrip().startswith("//"))) if cfg.pop("ai", None) != {"binding": "AI"}: sys.exit("the built Worker's wrangler.jsonc does not bind Workers AI as AI") @@ -330,7 +335,7 @@ if "vars" in cfg: cfg.pop("$schema", None) cfg["name"] = name cfg["services"] = [{"binding": "AI", "service": "fake-workers-ai"}] -cfg["vars"] = {"MATCH_THRESHOLD": "0.05"} +cfg["vars"] = {"MATCH_THRESHOLD": "0.05", "REINDEX_TOKEN": reindex_token} json.dump(cfg, open(out, "w"), indent=2) PY port="$(free_port)" @@ -354,9 +359,10 @@ smoke="$(python3 -c "import yaml,sys;print(yaml.safe_load(open(sys.argv[1]))['sp DEPLOYED_URL="$url" bash -c "$smoke" || { echo "FAIL: the deploy's smoke refused the product" >&2; tail -20 "$scratch/dev.log" >&2; exit 1; } echo " ▸ every route the product promises, the index as stored, and questions answered from it" -python3 - "$url" "$values" "$pgurl" "$tree/apps/web/lib/docs/index.generated.json" <<'PY' || { echo "FAIL: the routes; wrangler dev said:" >&2; tail -40 "$scratch/dev.log" >&2; exit 1; } +python3 - "$url" "$values" "$pgurl" "$tree/apps/web/lib/docs/index.generated.json" "$reindex_token" <<'PY' || { echo "FAIL: the routes; wrangler dev said:" >&2; tail -40 "$scratch/dev.log" >&2; exit 1; } import html, http.client, json, re, subprocess, sys, threading, time, urllib.error, urllib.request base, values, pgurl, index_file = sys.argv[1], json.load(open(sys.argv[2])), sys.argv[3], sys.argv[4] +reindex_token = sys.argv[5] index = json.load(open(index_file)) name, repo, org = values["productname"], values["reponame"], values["githuborg"] problems = [] @@ -480,6 +486,24 @@ s, again = index_docs() if s != 200 or again.get("embedded") != [page["path"]]: bad(f"re-indexing an emptied database answered {s} {again}") +# ── ?refresh=1 re-embeds every page, so it needs the bearer ─────────────── +# Refused with a 403 and nothing embedded — the stand-in's call count below +# says so — without a bearer, with a wrong one, and with the token as a bare +# header; then the right bearer re-embeds the whole index. The plain POST +# above took none of these and needed none. +stored = sql("select string_agg(id::text || ':' || coalesce(checksum, ''), ',' order by id) from nods_page") +for label, headers in (("no bearer", {}), ("a wrong bearer", {"authorization": "Bearer wrong-" + reindex_token}), + ("the token without 'Bearer'", {"authorization": reindex_token})): + s, _, body = req("/api/embeddings?refresh=1", b"", headers, "POST") + if s != 403 or json.loads(body) != {"ok": False, "error": "refresh=1 needs Authorization: Bearer "}: + bad(f"refresh=1 with {label} answered {s} {body}") +if sql("select string_agg(id::text || ':' || coalesce(checksum, ''), ',' order by id) from nods_page") != stored: + bad("a refused refresh=1 changed the stored pages") +s, _, body = req("/api/embeddings?refresh=1", b"", {"authorization": f"Bearer {reindex_token}"}, "POST") +refreshed = json.loads(body) if s == 200 else {} +if s != 200 or refreshed.get("embedded") != [page["path"]] or refreshed.get("unchanged") != []: + bad(f"refresh=1 with the right bearer answered {s} {body}") + if problems: for p in problems: print(f" ✕ {p}", file=sys.stderr) @@ -487,7 +511,8 @@ if problems: print(f" / as {name!r} linking github.com/{org}/{repo}, a 404, /api/health; the smoke indexed 1 page as " f"{len(page['sections'])} vector(768) sections; a second indexing embedded nothing, two at once embedded it " f"once; a question answered from the pgvector section, an unrelated one \"Sorry, I don't know how to help " - f"with that.\", a prompt-less request refused, an empty index said so") + f"with that.\", a prompt-less request refused, an empty index said so; refresh=1 refused without its " + f"bearer and with a wrong one, and re-embedding everything with it") PY # What the Workers AI stand-in was asked, read back from wrangler's output: @@ -505,10 +530,12 @@ if refused: page_embeds = [c for c in embeds if len(c["texts"]) == 2] question_embeds = [c for c in embeds if len(c["texts"]) == 1] # The smoke's indexing, the one of the two concurrent indexings that -# embedded, the re-indexing after the empty index: three, each the page's two -# sections in one call. Then the two questions that reached the model. -if len(page_embeds) != 3 or len(question_embeds) != 2 or len(embeds) != 5: - problems.append(f"{len(page_embeds)} page and {len(question_embeds)} question embeddings (of {len(embeds)}); want 3 and 2") +# embedded, the re-indexing after the empty index, and the ONE refresh=1 +# that carried the right bearer (the three refused ones embed nothing): +# four, each the page's two sections in one call. Then the two questions +# that reached the model. +if len(page_embeds) != 4 or len(question_embeds) != 2 or len(embeds) != 6: + problems.append(f"{len(page_embeds)} page and {len(question_embeds)} question embeddings (of {len(embeds)}); want 4 and 2") if len(answers) != 2 or not all(c.get("stream") for c in answers): problems.append(f"the answers were {answers}: want two, both streamed") for p in problems: diff --git a/testing/placement.test.sh b/testing/placement.test.sh index 6a78965..dfa4bc7 100755 --- a/testing/placement.test.sh +++ b/testing/placement.test.sh @@ -352,10 +352,21 @@ for comp in tree.glob("infra/**/component.yaml"): so = str(((yaml.safe_load(comp.read_text()) or {}).get("spec") or {}).get("parameters", {}).get("secretOutputs") or "") published |= {pair.split("=", 1)[0] for pair in so.split(",") if "=" in pair} resolved = set() +# The one key an OWNER stores, neither minted nor published: REINDEX_TOKEN, +# the bearer refresh=1 needs. Only web resolves it, this environment's, and +# BEST-EFFORT — a key nobody has stored is skipped, so the product deploys. +owner_keys = {"REINDEX_TOKEN"} for (comp, env), j in jobs.items(): for r in j.get("secretRefs") or []: ref = r["ref"] - resolved.add(ref.rsplit("/", 1)[1]) + key = ref.rsplit("/", 1)[1] + if key in owner_keys: + if comp != "web" or ref != f"secret://{ws}/{repo}/{env}/{key}" or r.get("optional") is not True: + bad(f"{comp}@{env} resolves {key} as {r} — want web's optional secret://{ws}/{repo}/{env}/{key}") + continue + if r.get("optional"): + bad(f"{comp}@{env} resolves {r['asEnv']} as optional; only {sorted(owner_keys)} may be") + resolved.add(key) if not ref.startswith(f"secret://{ws}/"): bad(f"{comp}@{env} resolves {r['asEnv']} from {ref} — not the product's workspace") if f"/{repo}/" not in ref and f"project:{repo}/" not in ref: @@ -387,6 +398,11 @@ for env in ("stage", "prod"): bad(f"web@{env}'s smoke does not check the product's own /api/health") if "-X POST" not in steps.get("smoke", "") or "/api/embeddings" not in steps.get("smoke", ""): bad(f"web@{env}'s smoke does not index the docs (POST /api/embeddings)") + if not any(r["asEnv"] == "REINDEX_TOKEN" and r.get("optional") is True for r in j.get("secretRefs") or []): + bad(f"web@{env} does not resolve the owner's REINDEX_TOKEN (optional)") + if "env -u REINDEX_TOKEN" not in steps.get("build-app", "") \ + or f'worker-secrets.mjs --secret REINDEX_TOKEN --worker "{repo}-web-${{ORUN_ENVIRONMENT}}"' not in steps.get("build-app", ""): + bad(f"web@{env}'s build does not keep REINDEX_TOKEN out of the bundle and hand it to its own Worker") if problems: for p in problems: diff --git a/tests/web/docs/architecture.md b/tests/web/docs/architecture.md index 014bbc1..d0a2312 100644 --- a/tests/web/docs/architecture.md +++ b/tests/web/docs/architecture.md @@ -2,7 +2,7 @@ A test package at `tests/web`. Its lane runs the suite before it builds. -## Suites (7) +## Suites (8) - `docs-index.test.ts` - `models.test.ts` @@ -10,4 +10,5 @@ A test package at `tests/web`. Its lane runs the suite before it builds. - `site.test.ts` - `sync.test.ts` - `utils.test.ts` +- `worker-secrets.test.ts` - `wrangler-config.test.ts` diff --git a/tests/web/src/routes.test.ts b/tests/web/src/routes.test.ts index 56acf76..23afb07 100644 --- a/tests/web/src/routes.test.ts +++ b/tests/web/src/routes.test.ts @@ -1,6 +1,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { startPostgres, type TestPostgres } from "./support/postgres"; import { fakeAi } from "./support/workers-ai"; +import { REFRESH_DISABLED, REFRESH_NEEDS_BEARER, sameSecret } from "@/lib/reindex"; // The three route handlers, called as OpenNext calls them, over a real // Postgres (PGlite with pgvector, every migration applied) reached through @@ -18,12 +19,14 @@ let pg: TestPostgres; let ai: ReturnType; const env: Record = {}; -const post = (url: string, body?: unknown) => +const post = (url: string, body?: unknown, headers: Record = {}) => new Request(url, { method: "POST", - headers: { "content-type": "application/json" }, + headers: { "content-type": "application/json", ...headers }, body: body === undefined ? undefined : JSON.stringify(body), }); +const TOKEN = "offline-reindex-token-fixture"; +const bearer = (token: string) => ({ authorization: `Bearer ${token}` }); beforeAll(async () => { // The app is the socket's only client (PGlite serves one session at a @@ -87,11 +90,65 @@ describe("POST /api/embeddings", () => { expect(await (await GET()).json()).toMatchObject({ pages: 1, sections: 2 }); }); - it("re-embeds everything with ?refresh=1", async () => { + it("re-embeds everything with ?refresh=1 and the environment's REINDEX_TOKEN as a bearer", async () => { + env.REINDEX_TOKEN = TOKEN; const { POST } = await import("@/app/api/embeddings/route"); await POST(post("https://x.test/api/embeddings")); - const res = await POST(post("https://x.test/api/embeddings?refresh=1")); - expect(await res.json()).toMatchObject({ embedded: ["/docs/openai_embeddings"] }); + ai.run.mockClear(); + const res = await POST(post("https://x.test/api/embeddings?refresh=1", undefined, bearer(TOKEN))); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + ok: true, pages: 1, embedded: ["/docs/openai_embeddings"], unchanged: [], failed: [], + }); + expect(ai.run).toHaveBeenCalledTimes(1); + }); + + describe("?refresh=1 is refused with a 403, reaching neither the model nor the database", () => { + const refused = async (headers: Record, error: string) => { + const { POST } = await import("@/app/api/embeddings/route"); + await POST(post("https://x.test/api/embeddings")); + const before = await pg.db.query<{ n: number }>("select count(*)::int as n from nods_page_section"); + ai.run.mockClear(); + const res = await POST(post("https://x.test/api/embeddings?refresh=1", undefined, headers)); + expect(res.status).toBe(403); + expect(res.headers.get("cache-control")).toBe("no-store"); + expect(await res.json()).toEqual({ ok: false, error }); + expect(ai.run).not.toHaveBeenCalled(); + const after = await pg.db.query<{ n: number }>("select count(*)::int as n from nods_page_section"); + expect(after.rows).toEqual(before.rows); + }; + + it("when the environment has no REINDEX_TOKEN, whatever the bearer", async () => { + await refused({}, REFRESH_DISABLED); + await refused(bearer(TOKEN), REFRESH_DISABLED); + }); + it("without a bearer", async () => { + env.REINDEX_TOKEN = TOKEN; + await refused({}, REFRESH_NEEDS_BEARER); + await refused({ authorization: TOKEN }, REFRESH_NEEDS_BEARER); + }); + it("with a wrong bearer, a prefix of the right one included", async () => { + env.REINDEX_TOKEN = TOKEN; + await refused(bearer("wrong"), REFRESH_NEEDS_BEARER); + await refused(bearer(TOKEN.slice(0, -1)), REFRESH_NEEDS_BEARER); + await refused(bearer(`${TOKEN}x`), REFRESH_NEEDS_BEARER); + }); + }); + + it("compares the bearer as a whole, in time that depends on neither secret", async () => { + expect(await sameSecret(TOKEN, TOKEN)).toBe(true); + expect(await sameSecret(TOKEN, TOKEN.toUpperCase())).toBe(false); + expect(await sameSecret("", TOKEN)).toBe(false); + expect(await sameSecret(TOKEN.slice(0, 8), TOKEN)).toBe(false); + }); + + it("leaves the plain POST open: a bearer, right or wrong, changes nothing", async () => { + env.REINDEX_TOKEN = TOKEN; + const { POST } = await import("@/app/api/embeddings/route"); + const first = await POST(post("https://x.test/api/embeddings", undefined, bearer("wrong"))); + expect(await first.json()).toMatchObject({ ok: true, embedded: ["/docs/openai_embeddings"] }); + const second = await POST(post("https://x.test/api/embeddings", undefined, bearer(TOKEN))); + expect(await second.json()).toMatchObject({ ok: true, embedded: [], unchanged: ["/docs/openai_embeddings"] }); }); it("is a 503 without the AI binding, embedding nothing", async () => { diff --git a/tests/web/src/worker-secrets.test.ts b/tests/web/src/worker-secrets.test.ts new file mode 100644 index 0000000..67e1b86 --- /dev/null +++ b/tests/web/src/worker-secrets.test.ts @@ -0,0 +1,51 @@ +import { spawnSync } from "node:child_process"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { describe, expect, it } from "vitest"; + +// tooling/wire/worker-secrets.mjs: what hands REINDEX_TOKEN to the Worker on +// a deploy, and to wrangler dev locally. Run as the deploy runs it, with a +// made-up value, and never with a Cloudflare credential. +const SCRIPT = path.resolve(__dirname, "../../../tooling/wire/worker-secrets.mjs"); +const TOKEN = "offline-fixture-not-a-token"; +const ARGS = ["--secret", "REINDEX_TOKEN"]; + +function run(args: string[], env: Record) { + const clean = { ...process.env }; + delete clean.CLOUDFLARE_API_TOKEN; + delete clean.REINDEX_TOKEN; + return spawnSync(process.execPath, [SCRIPT, ...args], { env: { ...clean, ...env }, encoding: "utf8" }); +} + +describe("worker-secrets.mjs", () => { + it("skips an unset token and succeeds: a fresh product deploys with refresh off", () => { + const r = run([...ARGS, "--worker", "acme-docs-web-stage"], {}); + expect(r.status).toBe(0); + expect(r.stdout).toContain("not set, skipped: REINDEX_TOKEN"); + expect(r.stdout).toContain("nothing to set"); + }); + + it("pushes nothing from a verify lane (no Cloudflare credential), and prints no value", () => { + const r = run([...ARGS, "--worker", "acme-docs-web-stage"], { REINDEX_TOKEN: TOKEN }); + expect(r.status).toBe(0); + expect(r.stdout).toContain("a verify lane"); + expect(r.stdout + r.stderr).not.toContain(TOKEN); + }); + + it("writes .dev.vars for wrangler dev with the token, readable by its owner only", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "worker-secrets-")); + const file = path.join(dir, ".dev.vars"); + const r = run([...ARGS, "--dev-vars", file], { REINDEX_TOKEN: TOKEN }); + expect(r.status).toBe(0); + expect(fs.readFileSync(file, "utf8")).toBe(`REINDEX_TOKEN="${TOKEN}"\n`); + expect(fs.statSync(file).mode & 0o777).toBe(0o600); + expect(r.stdout + r.stderr).not.toContain(TOKEN); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + it("refuses a name that is not an environment variable", () => { + const r = run(["--secret", "reindex-token", "--worker", "acme-docs-web-stage"], {}); + expect(r.status).toBe(2); + }); +}); diff --git a/tests/web/src/wrangler-config.test.ts b/tests/web/src/wrangler-config.test.ts index c52c4af..7e5d516 100644 --- a/tests/web/src/wrangler-config.test.ts +++ b/tests/web/src/wrangler-config.test.ts @@ -60,6 +60,8 @@ describe("apps/web wrangler config", () => { ]); const vars = (config.vars ?? {}) as Record; expect(Object.keys(vars)).not.toContain("OPENAI_API_KEY"); + // A secret, never a var a deploy would publish in the dashboard. + expect(Object.keys(vars)).not.toContain("REINDEX_TOKEN"); }); it("renders a deploy lane its own environment from the live wiring document", () => { diff --git a/tooling/wire/worker-secrets.mjs b/tooling/wire/worker-secrets.mjs new file mode 100644 index 0000000..43a72d0 --- /dev/null +++ b/tooling/wire/worker-secrets.mjs @@ -0,0 +1,96 @@ +#!/usr/bin/env node +// Worker SECRETS from the job's environment (zero-dependency). +// +// Some values a build is given must reach the Worker at request time and never +// a bundle: REINDEX_TOKEN, the bearer `POST /api/embeddings?refresh=1` needs. +// The deploy lane has it in its environment (an Orun secret the component's +// `optionalSecretEnv` resolves), and this hands the named variables that are +// set to `wrangler secret bulk` as JSON over stdin, so no value is ever on a +// command line or in a log. +// +// node worker-secrets.mjs --worker [--config wrangler.jsonc] \ +// --secret REINDEX_TOKEN [--secret …] +// +// --dev-vars write the same secrets as KEY=value lines instead +// (wrangler dev reads .dev.vars as the Worker's secrets) +// +// The secrets are OPTIONAL, like the Orun secrets they come from: a variable +// that is not set is skipped, named, and the Worker without it keeps refresh +// off (apps/web/lib/reindex.ts). Only a job that can +// deploy holds a Cloudflare credential (the composition's deploy profile +// binds CLOUDFLARE_API_TOKEN; its verify profiles bind nothing), so without +// one this says so and exits 0: a verify lane builds exactly what the deploy +// lane does and pushes nothing. +import * as fs from "node:fs"; +import { spawnSync } from "node:child_process"; + +function arg(name) { + const i = process.argv.indexOf(`--${name}`); + return i >= 0 ? process.argv[i + 1] : undefined; +} +function args(name) { + const out = []; + process.argv.forEach((a, i) => { + if (a === `--${name}` && process.argv[i + 1] !== undefined) out.push(process.argv[i + 1]); + }); + return out; +} + +const worker = arg("worker"); +const config = arg("config"); +const devVars = arg("dev-vars"); +const names = args("secret"); +if (names.length === 0 || (!worker && !devVars)) { + console.error( + "usage: worker-secrets.mjs --secret NAME [--secret …] (--worker [--config ] | --dev-vars )", + ); + process.exit(2); +} +for (const name of names) { + if (!/^[A-Z][A-Z0-9_]*$/.test(name)) { + console.error(`worker-secrets: --secret ${name} is not an environment variable name`); + process.exit(2); + } +} + +const secrets = {}; +const unset = []; +for (const name of names) { + const value = process.env[name]; + if (typeof value === "string" && value.length > 0) secrets[name] = value; + else unset.push(name); +} +if (unset.length > 0) console.log(`worker-secrets: not set, skipped: ${unset.join(", ")}`); +const set = Object.keys(secrets); +if (set.length === 0) { + console.log("worker-secrets: nothing to set"); + process.exit(0); +} +const list = set.join(", "); + +if (devVars) { + // KEY=value, one per line, double-quoted (dotenv's syntax, which wrangler + // reads): a JSON string is a valid dotenv double-quoted value. + const body = Object.entries(secrets) + .map(([k, v]) => `${k}=${JSON.stringify(v)}`) + .join("\n"); + fs.writeFileSync(devVars, `${body}\n`, { mode: 0o600 }); + console.log(`worker-secrets: wrote ${list} to ${devVars}`); + process.exit(0); +} + +if (!process.env.CLOUDFLARE_API_TOKEN) { + console.log(`worker-secrets: no Cloudflare credential in this job (a verify lane) — ${list} reach ${worker} from the deploy lane`); + process.exit(0); +} + +const result = spawnSync( + "pnpm", + ["exec", "wrangler", "secret", "bulk", "--name", worker, ...(config ? ["--config", config] : [])], + { input: JSON.stringify(secrets), stdio: ["pipe", "inherit", "inherit"] }, +); +if (result.status !== 0) { + console.error(`worker-secrets: wrangler secret bulk failed for ${worker}`); + process.exit(result.status ?? 1); +} +console.log(`worker-secrets: ${list} set on ${worker}`);