Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7c6346c799 | |||
| 7af16ee4e6 | |||
| 413849f066 | |||
| 9227cf4883 | |||
| 7dfa1ad830 | |||
| 8f5a069e77 | |||
| 07717afd01 | |||
| d8f6981be1 | |||
| d7bb314087 | |||
| 7679fada0a | |||
| a164c24e8e | |||
| 6148ae6439 | |||
| f54a13fc8a | |||
| f7f90a71fc | |||
| f1b0a53520 | |||
| f32e9a6889 | |||
| a1b27b5501 | |||
| ae0ce3824f | |||
| f98c5ccaf7 | |||
| 61f23e47f1 | |||
| ab5f08e4c0 | |||
| 5accf73363 | |||
| 299a157561 | |||
| af1af5c211 | |||
| 713e8bf415 | |||
| 8d42bfffc9 | |||
| 095efb1cca | |||
| 632dadd064 | |||
| dace2c4e66 | |||
| c01e4acf0a | |||
| 10b78d810d | |||
| cdeebec021 | |||
| 1d6b906202 | |||
| 277f459237 | |||
| ef18ed7376 | |||
| d61607f4c5 | |||
| 2853ce73a5 | |||
| 1e0747324d | |||
| b4b48f7b50 | |||
| fe412933ea | |||
| cd2f60e282 | |||
| 6702086c7b | |||
| 27e6674b9a |
@@ -102,7 +102,7 @@ jobs:
|
||||
git.farh.net/groombook/api:${{ steps.version.outputs.tag }}
|
||||
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/api:latest' || '' }}
|
||||
cache-from: type=registry,ref=git.farh.net/groombook/cache:api
|
||||
cache-to: type=registry,ref=git.farh.net/groombook/cache:api,mode=max
|
||||
cache-to: type=registry,ref=git.farh.net/groombook/cache:api,mode=max,ignore-error=true
|
||||
|
||||
- name: Build and push Migrate image
|
||||
uses: docker/build-push-action@v6
|
||||
@@ -116,7 +116,7 @@ jobs:
|
||||
git.farh.net/groombook/migrate:${{ steps.version.outputs.tag }}
|
||||
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/migrate:latest' || '' }}
|
||||
cache-from: type=registry,ref=git.farh.net/groombook/cache:migrate
|
||||
cache-to: type=registry,ref=git.farh.net/groombook/cache:migrate,mode=max
|
||||
cache-to: type=registry,ref=git.farh.net/groombook/cache:migrate,mode=max,ignore-error=true
|
||||
|
||||
- name: Smoke test migrate image (blackhole npmjs.org)
|
||||
run: |
|
||||
@@ -141,7 +141,7 @@ jobs:
|
||||
git.farh.net/groombook/seed:${{ steps.version.outputs.tag }}
|
||||
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/seed:latest' || '' }}
|
||||
cache-from: type=registry,ref=git.farh.net/groombook/cache:seed
|
||||
cache-to: type=registry,ref=git.farh.net/groombook/cache:seed,mode=max
|
||||
cache-to: type=registry,ref=git.farh.net/groombook/cache:seed,mode=max,ignore-error=true
|
||||
|
||||
- name: Build and push Reset image
|
||||
uses: docker/build-push-action@v6
|
||||
@@ -155,7 +155,7 @@ jobs:
|
||||
git.farh.net/groombook/reset:${{ steps.version.outputs.tag }}
|
||||
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/reset:latest' || '' }}
|
||||
cache-from: type=registry,ref=git.farh.net/groombook/cache:reset
|
||||
cache-to: type=registry,ref=git.farh.net/groombook/cache:reset,mode=max
|
||||
cache-to: type=registry,ref=git.farh.net/groombook/cache:reset,mode=max,ignore-error=true
|
||||
|
||||
- name: Smoke test seed image (blackhole npmjs.org)
|
||||
run: |
|
||||
@@ -185,3 +185,4 @@ jobs:
|
||||
"$IMAGE" \
|
||||
sh -c 'set -e; test "$(which pnpm)" = "/usr/local/bin/pnpm"; echo "HOME=$HOME"; pnpm --version'
|
||||
echo "reset image: pnpm resolves to /usr/local/bin/pnpm, HOME=/tmp, runs offline ✓"
|
||||
|
||||
|
||||
@@ -65,8 +65,11 @@ Expected: one row, `role = 'groomer'`. If zero rows return, the request hit the
|
||||
| # | Scenario | Steps | Expected |
|
||||
|---|----------|-------|----------|
|
||||
| TC-API-0.1 | Unauthenticated health check | GET /api/health | 200 OK, `{"status":"ok"}` |
|
||||
| TC-API-0.2 | DB-touching readiness check — healthy (GRO-2678) | GET /api/readyz | 200 OK, `{"status":"ready"}` |
|
||||
| TC-API-0.3 | DB-touching readiness check — response body safe | GET /api/readyz and inspect body | Body contains only `status` and (on error) `check` fields — no raw SQL, driver messages, or stack traces |
|
||||
|
||||
> **Note (GRO-1544):** Health endpoint registered on `api` basePath before auth middleware at `/api/health`. The old path `/health` was incorrect (routed to web pod via HTTPRoute `/*` rule).
|
||||
> **Note (GRO-2678):** `/api/readyz` is a separate DB-touching endpoint for monitoring. It is intentionally NOT used for K8s liveness/readiness probes — those remain DB-less to avoid pod cycling on transient DB blips.
|
||||
|
||||
### 4.1 Authentication
|
||||
|
||||
@@ -108,6 +111,11 @@ Expected: one row, `role = 'groomer'`. If zero rows return, the request hit the
|
||||
| TC-API-1.24 | Complete setup creates super user | POST /api/setup with business name (after TC-API-1.23) | First user becomes super user, setup completes | Setup errors, 403 on admin endpoints |
|
||||
| TC-API-1.25 | Super user accesses admin features | After TC-API-1.24, GET /api/staff/me and verify isSuperUser: true | isSuperUser: true, admin endpoints accessible | 403 on admin, isSuperUser: false |
|
||||
| TC-API-1.26 | Auto-provision skipped during OOBE | During fresh setup (needsSetup: true), complete OIDC login — verify no duplicate staff record created before setup completes | No duplicate staff, OOBE completes successfully | Duplicate staff record, 403 before setup, auto-provision interferes with OOBE |
|
||||
| TC-API-1.27 | Multi-origin CORS — demo host sign-in | `POST /api/auth/sign-in/social` with `callbackURL=https://demo.groombook.dev` | 200 OK, no origin-mismatch error | 400/403 "Origin mismatch" |
|
||||
| TC-API-1.28 | Multi-origin CORS — farh.net host sign-in | `POST /api/auth/sign-in/social` with `callbackURL=https://groombook.farh.net` | 200 OK, no origin-mismatch error | 400/403 "Origin mismatch" |
|
||||
| TC-API-1.29 | CORS — untrusted origin blocked (GRO-2586) | POST /api/auth/sign-in/social with `Origin: https://evil.example.com` header | Response has **no** `Access-Control-Allow-Origin` header — attacker origin is not reflected | `Access-Control-Allow-Origin: https://evil.example.com` present in response |
|
||||
| TC-API-1.30 | CORS — trusted origin allowed (GRO-2586) | POST /api/auth/sign-in/social with `Origin: https://uat.groombook.dev` header | `Access-Control-Allow-Origin: https://uat.groombook.dev` + `Access-Control-Allow-Credentials: true` | CORS header absent or trusted origin rejected |
|
||||
| TC-API-1.31 | CORS — untrusted preflight blocked (GRO-2586) | `curl -i -X OPTIONS https://uat.groombook.dev/api/auth/sign-in/social -H 'Origin: https://evil.example.com' -H 'Access-Control-Request-Method: POST'` | Response has **no** `Access-Control-Allow-Origin: https://evil.example.com` | Preflight reflects attacker origin |
|
||||
|
||||
### 4.2 Client Management
|
||||
|
||||
@@ -188,6 +196,7 @@ Geocoding turns a client's street address into `latitude`/`longitude` + `geocode
|
||||
| TC-API-3.27 | Verify coat_type enum has all seed values | After UAT seed completes, inspect the coat_type enum on the UAT DB — it must contain: short, medium, long, double, wire, silky, curly, hairless | UAT seed jobs (`reset-demo-data`, `seed-test-data`) complete 1/1 with no `enum_in` error; coat_type includes all 8 values used by seed.ts `coatTypePool` |
|
||||
| TC-API-3.28 | Verify pet_size_category enum has all seed values | After UAT seed completes, inspect the pet_size_category enum on the UAT DB — it must contain: small, medium, large, extra_large | UAT seed jobs (`reset-demo-data`, `seed-test-data`) complete 1/1 with no `enum_in` error; pet_size_category includes all 4 values used by seed.ts `petSizeCategoryPool` (regression for GRO-1999, mirrors TC-API-3.27) |
|
||||
| TC-API-3.29 | Verify `reset-demo-data` CronJob does not fail with FK 23503 on `invoice_tip_splits` (GRO-2123) | Trigger the CronJob manually: `kubectl create job --from=cronjob/reset-demo-data verify-gro2123 -n groombook-uat`. Wait for pod to terminate. Inspect logs: `kubectl logs -n groombook-uat -l job-name=verify-gro2123` | Pod reaches `Completed` state; logs show `✓ Acquired seed advisory lock` and `✓ Released seed advisory lock` from `seed.ts`; no `PostgresError: … violates foreign key constraint "invoice_tip_splits_invoice_id_invoices_id_fk"` (code 23503); final counts unchanged (500 clients, ~4000 invoices) |
|
||||
| TC-API-3.30 | Verify `reset-demo-data` CronJob is schema-safe — TRUNCATE only, no DDL drops (GRO-2722) | 1. Trigger: `kubectl -n groombook-uat create job --from=cronjob/reset-demo-data reset-verify-$(date +%s) --dry-run=client -o name \| xargs kubectl -n groombook-uat apply -f -` or simply `kubectl -n groombook-uat create job --from=cronjob/reset-demo-data reset-verify-$(date +%s)`. 2. Wait for job completion: `kubectl -n groombook-uat wait job/reset-verify-<ts> --for=condition=complete --timeout=300s`. 3. Check logs: `kubectl -n groombook-uat logs job/reset-verify-<ts>`. 4. Verify schema survival: `kubectl -n groombook-uat exec deploy/api -- psql $DATABASE_URL -c "\dt public.*"` and `kubectl -n groombook-uat exec deploy/api -- psql $DATABASE_URL -c "\dt drizzle.*"`. 5. Verify readyz: `curl -s https://uat.groombook.dev/api/readyz` | Job reaches `Completed` (exit 0); logs show `✓ All public tables truncated, sequences reset` — no `DROP TABLE`/`DROP TYPE`/`DROP SCHEMA` in output; all `public.*` tables still present after reset; `drizzle.__drizzle_migrations` still populated (row count unchanged); `https://uat.groombook.dev/api/readyz` returns HTTP 200; demo data reseeded (500 clients visible via GET /api/clients) |
|
||||
|
||||
### 4.4 Appointment Scheduling
|
||||
|
||||
@@ -434,6 +443,38 @@ Both use the stops' stored `latitude`/`longitude` in `stopOrder`: **origin = fir
|
||||
| TC-API-18.10 | Groomer cannot export another's route | As groomer, export a route owned by a different groomer | 403 Forbidden (`groomers may only access their own route`) |
|
||||
| TC-API-18.11 | Receptionist denied | As **receptionist**, export any route | 403 Forbidden (role not permitted) |
|
||||
|
||||
|
||||
### 4.19 Boot Resilience — ECONNRESET Recovery (GRO-2652)
|
||||
|
||||
Verifies the API process does not crash on transient boot-time DB connection resets and that auth routes degrade gracefully until initialization succeeds.
|
||||
|
||||
| TC | Test Case | Steps | Expected Result |
|
||||
|----|-----------|-------|-----------------|
|
||||
| TC-API-19.1 | Health endpoint available before auth init | 1. Deploy the image (or restart the api pod)<br>2. `GET /health` immediately (within first 2 s of pod start) | 200 `{"status":"ok"}` — server accepts requests before `initAuth()` completes |
|
||||
| TC-API-19.2 | Auth routes return 503 when auth not yet initialized | 1. Temporarily set `OIDC_ISSUER` to an unreachable host so `initAuth()` keeps retrying<br>2. `POST /api/auth/sign-in/email` during the retry window | 503 `{"error":"Authentication not configured"}` — process stays alive, does not exit |
|
||||
| TC-API-19.3 | Pod does not crash on first-attempt DB reset | 1. Review pod restart count after normal deployment<br>2. Confirm `kubectl get pod -n groombook` shows `RESTARTS: 0` (or same as before deploy) for the new pod | No new restarts — ECONNRESET causes retry, not process exit |
|
||||
| TC-API-19.4 | DB query retry log lines visible | After deploy, `kubectl logs -n groombook <api-pod>` | If any DB retry occurred, log lines matching `[auth] DB query attempt N failed` are present; on clean boot no retry lines appear |
|
||||
| TC-API-19.5 | Auth init retry log lines visible | When auth init fails and retries, check pod logs | Log lines matching `[auth] initAuth attempt N failed` present; process continues; no `process.exit` |
|
||||
| TC-API-19.6 | Auth succeeds after transient DB hiccup | 1. Allow pod to retry until DB is available<br>2. `POST /api/auth/sign-in/email` with valid credentials after init succeeds | 200 with session cookie — auth recovers without pod restart |
|
||||
| TC-API-19.7 | Normal sign-in still works end-to-end | Follow TC-WEB-SSO-3 (SSO sign-in) on UAT | Successful sign-in, staff list visible — no regression from resilience changes |
|
||||
| TC-API-19.8 | Public routes unaffected during auth retry | While auth is retrying (TC-API-19.2 setup), `GET /api/branding` | 200 with branding data — public routes bypass auth and serve normally |
|
||||
|
||||
### 4.20 Portal OOBE — Create Client from Auth (GRO-2359)
|
||||
|
||||
Verifies the `POST /api/portal/clients-from-auth` endpoint that creates a new `clients` row for a first-time SSO user (out-of-box-experience registration). This endpoint requires a valid Better Auth session but does NOT require a portal session; it is the pre-portal step in the new-user OOBE flow.
|
||||
|
||||
| TC | Test Case | Steps | Expected Result |
|
||||
|----|-----------|-------|-----------------|
|
||||
| TC-API-20.1 | Successful client creation | 1. Sign in via SSO to obtain a Better Auth session<br>2. `POST /api/portal/clients-from-auth` with `{ "name": "Test User" }` | 201 `{ "id": "<uuid>", "name": "Test User", "email": "<sso-email>" }` — new `clients` row created |
|
||||
| TC-API-20.2 | All optional fields accepted | `POST /api/portal/clients-from-auth` with `{ "name": "Test User", "phone": "555-1234", "address": "1 Main St", "notes": "VIP" }` (authenticated) | 201 with `id`, `name`, `email`; row in DB has all four fields |
|
||||
| TC-API-20.3 | Invalid body — missing name | `POST /api/portal/clients-from-auth` with `{}` (authenticated) | 400 (Zod validation failure); no row created |
|
||||
| TC-API-20.4 | Invalid body — empty name | `POST /api/portal/clients-from-auth` with `{ "name": "" }` (authenticated) | 400 — name must be at least 1 character |
|
||||
| TC-API-20.5 | No session — 401 | `POST /api/portal/clients-from-auth` with a valid body but **no** Better Auth session cookie | 401 `{ "error": "Unauthorized" }` |
|
||||
| TC-API-20.6 | Existing email — 409 | 1. Create a client row whose email matches the signed-in SSO user's email<br>2. `POST /api/portal/clients-from-auth` as that user | 409 `{ "error": "A customer record with this email already exists" }` — no duplicate row |
|
||||
| TC-API-20.7 | Auth not configured — 503 | Temporarily disable auth (e.g., point `OIDC_ISSUER` to an invalid host) so `getAuth()` throws<br>2. `POST /api/portal/clients-from-auth` | 503 `{ "error": "Authentication not configured" }` — graceful degradation |
|
||||
| TC-API-20.8 | Concurrent insert race — 409 | Simulate two near-simultaneous requests from the same SSO user (before any row exists) | At most one request returns 201; the other returns 409 — no duplicate row, no 500 |
|
||||
|
||||
|
||||
## Pass/Fail Criteria
|
||||
|
||||
**Pass:**
|
||||
@@ -455,3 +496,4 @@ Both use the stops' stored `latitude`/`longitude` in `stopOrder`: **origin = fir
|
||||
## Update Policy
|
||||
|
||||
Any PR that changes user-facing behaviour MUST update this file. Test cases must be added, modified, or removed to reflect the new behaviour. The PR description must reference which playbook section was updated (e.g., "Updated UAT_PLAYBOOK.md §4.4 — new appointment rescheduling flow").
|
||||
|
||||
|
||||
@@ -69,9 +69,14 @@ describe("auth init", () => {
|
||||
beforeEach(() => {
|
||||
dbSelectResult = [];
|
||||
vi.clearAllMocks();
|
||||
// Stub fetch so OIDC discovery requests resolve instantly during tests.
|
||||
// Without this, AbortSignal.timeout(5000) in auth.ts races with vitest's
|
||||
// 5000ms default test timeout and causes flaky failures.
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: false, status: 503 }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
|
||||
+30
-36
@@ -1,10 +1,17 @@
|
||||
/**
|
||||
* reset.ts — Drop all application tables and re-run migrations + seed.
|
||||
* reset.ts — Truncate all public tables and restart identity sequences.
|
||||
*
|
||||
* Intended for local development only. Never run against production.
|
||||
* Schema-safe: never issues destructive DDL against any schema.
|
||||
* The drizzle schema and __drizzle_migrations table are preserved so
|
||||
* drizzle-kit migrate remains a no-op on an already-migrated DB.
|
||||
*
|
||||
* NOTE: this file is NOT the deployed reset entrypoint — the reset image
|
||||
* builds from packages/db and runs `pnpm --filter @groombook/db reset`.
|
||||
* apps/api db:reset delegates there too (see apps/api/package.json).
|
||||
* Keep in sync with packages/db/src/reset.ts (GRO-2722).
|
||||
*
|
||||
* Usage:
|
||||
* DATABASE_URL=postgres://... npx tsx packages/db/src/reset.ts
|
||||
* DATABASE_URL=postgres://... npx tsx apps/api/src/db/reset.ts
|
||||
*/
|
||||
|
||||
import postgres from "postgres";
|
||||
@@ -23,43 +30,30 @@ async function reset() {
|
||||
|
||||
const client = postgres(url, { max: 1 });
|
||||
|
||||
console.log("Dropping all application tables...\n");
|
||||
console.log("Truncating all public tables...\n");
|
||||
|
||||
// Drop in dependency order (children before parents)
|
||||
await client`
|
||||
DO $$ DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
FOR r IN (
|
||||
SELECT tablename FROM pg_tables
|
||||
WHERE schemaname = 'public'
|
||||
) LOOP
|
||||
EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE';
|
||||
END LOOP;
|
||||
END $$;
|
||||
// Enumerate all base tables in the public schema dynamically, then
|
||||
// issue a single TRUNCATE with RESTART IDENTITY CASCADE so FK cycles
|
||||
// are not a problem. The drizzle schema and __drizzle_migrations are
|
||||
// intentionally excluded (different schema) so drizzle-kit migrate
|
||||
// stays a no-op on an already-migrated DB.
|
||||
const tables = await client<{ tablename: string }[]>`
|
||||
SELECT tablename FROM pg_tables
|
||||
WHERE schemaname = 'public'
|
||||
`;
|
||||
|
||||
// Drop custom enums
|
||||
await client`
|
||||
DO $$ DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
FOR r IN (
|
||||
SELECT typname FROM pg_type
|
||||
WHERE typtype = 'e' AND typnamespace = (
|
||||
SELECT oid FROM pg_namespace WHERE nspname = 'public'
|
||||
)
|
||||
) LOOP
|
||||
EXECUTE 'DROP TYPE IF EXISTS ' || quote_ident(r.typname) || ' CASCADE';
|
||||
END LOOP;
|
||||
END $$;
|
||||
`;
|
||||
if (tables.length > 0) {
|
||||
// Double-quote each identifier (escaping embedded quotes) to handle
|
||||
// any table name safely without a pg-specific quote_ident helper.
|
||||
const tableList = tables
|
||||
.map((t) => `"${t.tablename.replace(/"/g, '""')}"`)
|
||||
.join(", ");
|
||||
await client.unsafe(
|
||||
`TRUNCATE ${tableList} RESTART IDENTITY CASCADE`,
|
||||
);
|
||||
}
|
||||
|
||||
// Drop the drizzle migrations tracking table
|
||||
await client`DROP TABLE IF EXISTS drizzle.__drizzle_migrations CASCADE`;
|
||||
await client`DROP SCHEMA IF EXISTS drizzle CASCADE`;
|
||||
|
||||
console.log("✓ All tables and enums dropped\n");
|
||||
console.log("✓ All public tables truncated, sequences reset\n");
|
||||
|
||||
await client.end();
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
"wait-for-db": "node ./scripts/wait-for-db.mjs",
|
||||
"migrate": "node ./scripts/wait-for-db.mjs && drizzle-kit migrate",
|
||||
"seed": "node ./scripts/wait-for-db.mjs && tsx src/seed.ts",
|
||||
"reset": "node ./scripts/wait-for-db.mjs && tsx src/reset.ts && drizzle-kit migrate && tsx src/seed.ts",
|
||||
"reset": "node ./scripts/wait-for-db.mjs && tsx src/reset.ts",
|
||||
"studio": "drizzle-kit studio",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
|
||||
+112
-40
@@ -1,13 +1,54 @@
|
||||
/**
|
||||
* reset.ts — Drop all application tables and re-run migrations + seed.
|
||||
* reset.ts — Truncate all public tables and restart identity sequences.
|
||||
*
|
||||
* Intended for local development only. Never run against production.
|
||||
* Schema-safe: never issues destructive DDL against any schema.
|
||||
* The drizzle schema and __drizzle_migrations table are preserved so
|
||||
* drizzle-kit migrate remains a no-op on an already-migrated DB.
|
||||
*
|
||||
* Usage:
|
||||
* DATABASE_URL=postgres://... npx tsx packages/db/src/reset.ts
|
||||
* GRO-2139: the entire truncate→migrate→seed chain runs inside a single
|
||||
* Postgres advisory lock (SEED_ADVISORY_LOCK_KEY) so a concurrent
|
||||
* `seed.ts` (e.g. the dev `seed-test-data-*` Job being recreated at
|
||||
* the top of the hour) cannot interleave between `reset.ts` (TRUNCATE)
|
||||
* and `seed.ts` (TRUNCATE+insert) and collide on `invoices_pkey`.
|
||||
*
|
||||
* Why this matters: `seed.ts` derives every primary key from a single
|
||||
* shared Mulberry32 PRNG seeded with 42 (see `createPrng(42)` and
|
||||
* `uuid()` in seed.ts). Two concurrent same-profile seeders therefore
|
||||
* emit *identical* ids for the same logical row, and any moment
|
||||
* between a concurrent `seed.ts` TRUNCATE and INSERT is exactly the
|
||||
* window in which the second seeder's INSERT can hit a pkey already
|
||||
* taken by the first. Pre-GRO-2123 this raced unconditionally;
|
||||
* GRO-2123 added the advisory lock around `runSeedBody` but left
|
||||
* `reset.ts` and `drizzle-kit migrate` outside the lock. This script
|
||||
* now wraps the *whole* chain in the same lock: `withSeedAdvisoryLock`
|
||||
* pins the lock to one reserved session and the TRUNCATE → migrate → seed
|
||||
* work runs on the rest of the pool, so the lock guarantees mutual
|
||||
* exclusion against any concurrent seeder for the entire chain.
|
||||
*
|
||||
* For a full local schema teardown (nuke tables, enums, drizzle schema)
|
||||
* use `pnpm --filter @groombook/db db:nuke` instead — never change this
|
||||
* script to be destructive (GRO-2722 / GRO-2678 prod incident).
|
||||
*
|
||||
* See: groombook/infra `apps/base/reset-cronjob.yaml` (CronJob) and
|
||||
* `apps/base/seed-job.yaml` (one-shot Job) — both invoke the same
|
||||
* `seed.ts` code path on the same database in `groombook-dev`.
|
||||
*/
|
||||
|
||||
import postgres from "postgres";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import { execSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import * as schema from "./schema.js";
|
||||
import {
|
||||
SEED_ADVISORY_LOCK_KEY,
|
||||
withSeedAdvisoryLock,
|
||||
getProfile,
|
||||
runSeedBody,
|
||||
profiles,
|
||||
} from "./seed.js";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
async function reset() {
|
||||
const url = process.env.DATABASE_URL;
|
||||
@@ -16,52 +57,83 @@ async function reset() {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV === "production" && process.env.ALLOW_RESET !== "true") {
|
||||
console.error("[FATAL] db:reset must not be run in production without ALLOW_RESET=true.");
|
||||
if (
|
||||
process.env.NODE_ENV === "production" &&
|
||||
process.env.ALLOW_RESET !== "true"
|
||||
) {
|
||||
console.error(
|
||||
"[FATAL] db:reset must not be run in production without ALLOW_RESET=true.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = postgres(url, { max: 1 });
|
||||
// Pool sizing is load-bearing here. `withSeedAdvisoryLock` does
|
||||
// `pool.reserve()` to pin the advisory lock to one dedicated session
|
||||
// (a session-level lock released on a *different* pooled connection is
|
||||
// a no-op), and the TRUNCATE / migrate / seed work then runs on the
|
||||
// *remaining* pooled connections. The lock provides mutual exclusion
|
||||
// across processes regardless of how many connections the work uses —
|
||||
// it does NOT require the work to share the lock's session.
|
||||
//
|
||||
// Therefore `max` must be >= 2: 1 reserved for the lock + >=1 free for
|
||||
// the work. `max: 1` would let `reserve()` consume the only connection
|
||||
// and every query inside the callback would block forever waiting for
|
||||
// a connection that never frees (connection-starvation deadlock). We
|
||||
// use `max: 6` to match `seed()`'s headroom (1 reserved + 5 work).
|
||||
const client = postgres(url, { max: 6 });
|
||||
const db = drizzle(client, { schema });
|
||||
|
||||
console.log("Dropping all application tables...\n");
|
||||
try {
|
||||
await withSeedAdvisoryLock(client, async () => {
|
||||
console.log("Truncating all public tables...\n");
|
||||
|
||||
// Drop in dependency order (children before parents)
|
||||
await client`
|
||||
DO $$ DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
FOR r IN (
|
||||
// Enumerate all base tables in the public schema dynamically, then
|
||||
// issue a single TRUNCATE with RESTART IDENTITY CASCADE so FK cycles
|
||||
// are not a problem. The drizzle schema and __drizzle_migrations are
|
||||
// intentionally excluded (different schema) so drizzle-kit migrate
|
||||
// stays a no-op on an already-migrated DB.
|
||||
const tables = await client<{ tablename: string }[]>`
|
||||
SELECT tablename FROM pg_tables
|
||||
WHERE schemaname = 'public'
|
||||
) LOOP
|
||||
EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE';
|
||||
END LOOP;
|
||||
END $$;
|
||||
`;
|
||||
`;
|
||||
|
||||
// Drop custom enums
|
||||
await client`
|
||||
DO $$ DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
FOR r IN (
|
||||
SELECT typname FROM pg_type
|
||||
WHERE typtype = 'e' AND typnamespace = (
|
||||
SELECT oid FROM pg_namespace WHERE nspname = 'public'
|
||||
)
|
||||
) LOOP
|
||||
EXECUTE 'DROP TYPE IF EXISTS ' || quote_ident(r.typname) || ' CASCADE';
|
||||
END LOOP;
|
||||
END $$;
|
||||
`;
|
||||
if (tables.length > 0) {
|
||||
// Double-quote each identifier (escaping embedded quotes) to handle
|
||||
// any table name safely without a pg-specific quote_ident helper.
|
||||
const tableList = tables
|
||||
.map((t) => `"${t.tablename.replace(/"/g, '""')}"`)
|
||||
.join(", ");
|
||||
await client.unsafe(
|
||||
`TRUNCATE ${tableList} RESTART IDENTITY CASCADE`,
|
||||
);
|
||||
}
|
||||
|
||||
// Drop the drizzle migrations tracking table
|
||||
await client`DROP TABLE IF EXISTS drizzle.__drizzle_migrations CASCADE`;
|
||||
await client`DROP SCHEMA IF EXISTS drizzle CASCADE`;
|
||||
console.log("✓ All public tables truncated, sequences reset\n");
|
||||
|
||||
console.log("✓ All tables and enums dropped\n");
|
||||
console.log("Running migrations...");
|
||||
// GRO-2672: drizzle-orm's migrate() has a high-water-mark bug that skips
|
||||
// migrations with stale `when` timestamps (0001, 0003, 0010, 0011). Use
|
||||
// drizzle-kit instead -- it applies migrations by hash, matching the K8s
|
||||
// migrate Job behaviour exactly.
|
||||
execSync("pnpm exec drizzle-kit migrate", {
|
||||
stdio: "inherit",
|
||||
env: { ...process.env },
|
||||
cwd: resolve(__dirname, ".."),
|
||||
});
|
||||
console.log("✓ Migrations applied\n");
|
||||
|
||||
await client.end();
|
||||
console.log("Seeding database...");
|
||||
const profile = getProfile();
|
||||
const cfg = profiles[profile];
|
||||
await runSeedBody(client, db, profile, cfg);
|
||||
});
|
||||
|
||||
console.log(
|
||||
`\n✓ Reset complete (advisory lock key=0x${SEED_ADVISORY_LOCK_KEY.toString(16)})`,
|
||||
);
|
||||
} finally {
|
||||
await client.end();
|
||||
}
|
||||
}
|
||||
|
||||
reset().catch((err) => {
|
||||
|
||||
@@ -24,9 +24,9 @@ import type { MedicalAlert } from "@groombook/types";
|
||||
|
||||
// ── Seed profile configuration ─────────────────────────────────────────────
|
||||
|
||||
type SeedProfile = "dev" | "uat" | "demo";
|
||||
export type SeedProfile = "dev" | "uat" | "demo";
|
||||
|
||||
interface ProfileConfig {
|
||||
export interface ProfileConfig {
|
||||
staffCount: { manager: number; receptionist: number; groomer: number; bather: number };
|
||||
clientCount: number;
|
||||
appointmentsBackDays: number;
|
||||
@@ -35,7 +35,7 @@ interface ProfileConfig {
|
||||
includeUatClients: boolean;
|
||||
}
|
||||
|
||||
const profiles: Record<SeedProfile, ProfileConfig> = {
|
||||
export const profiles: Record<SeedProfile, ProfileConfig> = {
|
||||
dev: {
|
||||
staffCount: { manager: 1, receptionist: 1, groomer: 2, bather: 0 },
|
||||
clientCount: 100,
|
||||
@@ -70,6 +70,8 @@ function getProfile(): SeedProfile {
|
||||
return "uat";
|
||||
}
|
||||
|
||||
export { getProfile };
|
||||
|
||||
// ── Deterministic PRNG (Mulberry32) ──────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -1400,7 +1402,7 @@ async function seedKnownUsers() {
|
||||
// from runbooks without ambiguity and binds to the single-argument
|
||||
// `pg_advisory_lock(int)` form, which postgres-js serializes as a plain
|
||||
// number (no bigint type plumbing required).
|
||||
const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitrary, stable
|
||||
export const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitrary, stable
|
||||
|
||||
/**
|
||||
* Reserve a dedicated connection from `pool`, take the seed advisory lock
|
||||
@@ -1413,7 +1415,7 @@ const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitrary, sta
|
||||
* for the lock and release it from the same reserved connection. The
|
||||
* seed work itself still runs on the pooled connections.
|
||||
*/
|
||||
async function withSeedAdvisoryLock<T>(
|
||||
export async function withSeedAdvisoryLock<T>(
|
||||
pool: ReturnType<typeof postgres>,
|
||||
fn: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
@@ -1471,7 +1473,7 @@ async function seed() {
|
||||
await client.end();
|
||||
}
|
||||
|
||||
async function runSeedBody(
|
||||
export async function runSeedBody(
|
||||
client: ReturnType<typeof postgres>,
|
||||
db: ReturnType<typeof drizzle>,
|
||||
profile: SeedProfile,
|
||||
|
||||
@@ -69,9 +69,14 @@ describe("auth init", () => {
|
||||
beforeEach(() => {
|
||||
dbSelectResult = [];
|
||||
vi.clearAllMocks();
|
||||
// Stub fetch so OIDC discovery requests resolve instantly during tests.
|
||||
// Without this, AbortSignal.timeout(5000) in auth.ts races with vitest's
|
||||
// 5000ms default test timeout and causes flaky failures.
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: false, status: 503 }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { enforceAuthCors } from "../lib/auth-cors.js";
|
||||
|
||||
const TRUSTED = ["https://uat.groombook.dev", "https://dev.groombook.dev"];
|
||||
|
||||
/** Simulates Better Auth reflecting the request Origin (the pre-fix bug). */
|
||||
function makeReflectedResponse(origin: string | null): Response {
|
||||
return new Response('{"ok":true}', {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(origin
|
||||
? {
|
||||
"Access-Control-Allow-Origin": origin,
|
||||
"Access-Control-Allow-Credentials": "true",
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("enforceAuthCors (GRO-2586)", () => {
|
||||
it("passes trusted origin through with credentials", () => {
|
||||
const origin = "https://uat.groombook.dev";
|
||||
const res = enforceAuthCors(origin, TRUSTED, makeReflectedResponse(origin));
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(origin);
|
||||
expect(res.headers.get("Access-Control-Allow-Credentials")).toBe("true");
|
||||
});
|
||||
|
||||
it("strips ACAO for attacker origin (credentialed cross-origin read blocked)", () => {
|
||||
const origin = "https://evil.example.com";
|
||||
const res = enforceAuthCors(origin, TRUSTED, makeReflectedResponse(origin));
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBeNull();
|
||||
expect(res.headers.get("Access-Control-Allow-Credentials")).toBeNull();
|
||||
});
|
||||
|
||||
it("strips ACAO when no Origin header (undefined)", () => {
|
||||
const res = enforceAuthCors(undefined, TRUSTED, makeReflectedResponse(null));
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBeNull();
|
||||
expect(res.headers.get("Access-Control-Allow-Credentials")).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves non-CORS response headers and status from Better Auth", () => {
|
||||
const origin = "https://evil.example.com";
|
||||
const res = enforceAuthCors(origin, TRUSTED, makeReflectedResponse(origin));
|
||||
expect(res.headers.get("Content-Type")).toBe("application/json");
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("second trusted origin is also allowed", () => {
|
||||
const origin = "https://dev.groombook.dev";
|
||||
const res = enforceAuthCors(origin, TRUSTED, makeReflectedResponse(origin));
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(origin);
|
||||
});
|
||||
|
||||
it("empty string origin is treated as untrusted", () => {
|
||||
const res = enforceAuthCors("", TRUSTED, makeReflectedResponse(""));
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { Hono } from "hono";
|
||||
|
||||
// Mock auth lib so getAuth() throws — non-bypass paths hit the 503 "not configured" guard.
|
||||
vi.mock("../lib/auth.js", () => ({
|
||||
getAuth: () => {
|
||||
throw new Error("auth not configured");
|
||||
},
|
||||
initAuth: vi.fn(),
|
||||
getActiveProviders: vi.fn(() => []),
|
||||
}));
|
||||
|
||||
describe("authMiddleware bypass: /api/readyz", () => {
|
||||
it("serves /api/readyz without auth (bypass before auth check)", async () => {
|
||||
// Ensure AUTH_DISABLED is not set so the bypass is exercised, not AUTH_DISABLED shortcut.
|
||||
const prev = process.env.AUTH_DISABLED;
|
||||
delete process.env.AUTH_DISABLED;
|
||||
|
||||
const { authMiddleware } = await import("../middleware/auth.js");
|
||||
const app = new Hono();
|
||||
app.use("/api/*", authMiddleware);
|
||||
app.get("/api/readyz", (c) => c.json({ status: "ok" }, 200));
|
||||
|
||||
const res = await app.request("/api/readyz", { method: "GET" });
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
if (prev !== undefined) process.env.AUTH_DISABLED = prev;
|
||||
});
|
||||
|
||||
it("blocks non-whitelisted /api/* paths when auth is not configured", async () => {
|
||||
const prev = process.env.AUTH_DISABLED;
|
||||
delete process.env.AUTH_DISABLED;
|
||||
|
||||
const { authMiddleware } = await import("../middleware/auth.js");
|
||||
const app = new Hono();
|
||||
app.use("/api/*", authMiddleware);
|
||||
app.get("/api/staff", (c) => c.json({ ok: true }, 200));
|
||||
|
||||
const res = await app.request("/api/staff", { method: "GET" });
|
||||
expect(res.status).toBe(503);
|
||||
|
||||
if (prev !== undefined) process.env.AUTH_DISABLED = prev;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { Hono } from "hono";
|
||||
|
||||
// ─── Mock db module ───────────────────────────────────────────────────────────
|
||||
|
||||
let selectImpl: () => Promise<unknown>;
|
||||
|
||||
vi.mock("@groombook/db", () => {
|
||||
const staff = new Proxy(
|
||||
{ _name: "staff" },
|
||||
{
|
||||
get(_target, prop) {
|
||||
if (prop === "_name") return "staff";
|
||||
return { table: "staff", column: prop };
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
getDb: () => ({
|
||||
select: (_fields: unknown) => ({
|
||||
from: (_table: unknown) => ({
|
||||
limit: (_n: number) => selectImpl(),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
staff,
|
||||
};
|
||||
});
|
||||
|
||||
// ─── Build test app ───────────────────────────────────────────────────────────
|
||||
|
||||
async function makeApp() {
|
||||
// Import after mocks are in place
|
||||
const { getDb, staff } = await import("@groombook/db");
|
||||
|
||||
const app = new Hono();
|
||||
app.get("/api/readyz", async (c) => {
|
||||
try {
|
||||
await getDb().select({ id: staff.id }).from(staff).limit(1);
|
||||
return c.json({ status: "ready" }, 200);
|
||||
} catch (err) {
|
||||
console.error("[readyz] DB check failed:", err);
|
||||
return c.json({ status: "degraded", check: "db" }, 503);
|
||||
}
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
// ─── Tests ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("GET /api/readyz", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("returns 200 {status:'ready'} when DB query succeeds", async () => {
|
||||
selectImpl = () => Promise.resolve([{ id: "staff-1" }]);
|
||||
|
||||
const app = await makeApp();
|
||||
const res = await app.request("/api/readyz", { method: "GET" });
|
||||
const body = (await res.json()) as Record<string, unknown>;
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.status).toBe("ready");
|
||||
});
|
||||
|
||||
it("returns 503 {status:'degraded',check:'db'} when DB query throws", async () => {
|
||||
selectImpl = () => Promise.reject(new Error("42P01: relation staff does not exist"));
|
||||
|
||||
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
|
||||
const app = await makeApp();
|
||||
const res = await app.request("/api/readyz", { method: "GET" });
|
||||
const body = (await res.json()) as Record<string, unknown>;
|
||||
|
||||
expect(res.status).toBe(503);
|
||||
expect(body.status).toBe("degraded");
|
||||
expect(body.check).toBe("db");
|
||||
|
||||
// Raw SQL / driver error must NOT appear in the response body
|
||||
expect(JSON.stringify(body)).not.toContain("42P01");
|
||||
expect(JSON.stringify(body)).not.toContain("relation");
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
+37
-4
@@ -3,6 +3,7 @@ import { Hono } from "hono";
|
||||
import { logger } from "hono/logger";
|
||||
import { cors } from "hono/cors";
|
||||
import { getAuth, initAuth, getActiveProviders } from "./lib/auth.js";
|
||||
import { enforceAuthCors } from "./lib/auth-cors.js";
|
||||
import { clientsRouter } from "./routes/clients.js";
|
||||
import { petsRouter } from "./routes/pets.js";
|
||||
import { servicesRouter } from "./routes/services.js";
|
||||
@@ -64,6 +65,17 @@ app.use(
|
||||
app.get("/health", (c) => c.json({ status: "ok" }));
|
||||
// /api/health: used by Gateway HTTPRoute (/api/* → API pod)
|
||||
app.get("/api/health", (c) => c.json({ status: "ok" }));
|
||||
// /api/readyz: DB-touching deep health check consumed by monitoring (not K8s probes)
|
||||
// Distinct from /health so a dropped schema triggers an alert without cycling pods (GRO-2678)
|
||||
app.get("/api/readyz", async (c) => {
|
||||
try {
|
||||
await getDb().select({ id: staff.id }).from(staff).limit(1);
|
||||
return c.json({ status: "ready" }, 200);
|
||||
} catch (err) {
|
||||
console.error("[readyz] DB check failed:", err);
|
||||
return c.json({ status: "degraded", check: "db" }, 503);
|
||||
}
|
||||
});
|
||||
|
||||
// Public booking routes — no auth required, must be registered before auth middleware
|
||||
app.route("/api/book", bookRouter);
|
||||
@@ -200,9 +212,10 @@ api.use("*", resolveStaffMiddleware);
|
||||
// Better-Auth handler — mounted as sub-app to handle all /api/auth/* routes
|
||||
// authMiddleware and resolveStaffMiddleware both skip /api/auth/ paths
|
||||
const authRouter = new Hono();
|
||||
authRouter.all("/*", (c) => {
|
||||
authRouter.all("/*", async (c) => {
|
||||
try {
|
||||
return getAuth().handler(c.req.raw);
|
||||
const res = await getAuth().handler(c.req.raw);
|
||||
return enforceAuthCors(c.req.header("origin"), TRUSTED_ORIGINS, res);
|
||||
} catch {
|
||||
return c.json({ error: "Authentication not configured" }, 503);
|
||||
}
|
||||
@@ -290,14 +303,34 @@ api.route("/search", searchRouter);
|
||||
api.route("/buffer-rules", bufferRulesRouter);
|
||||
api.route("/routes", routesRouter);
|
||||
|
||||
// Start the HTTP server first so /health and public routes are available immediately.
|
||||
// Auth initialization runs afterward with retry — a transient DB ECONNRESET at boot
|
||||
// must not crash the process (GRO-2652). Auth routes return 503 until initAuth succeeds.
|
||||
const port = Number(process.env.PORT ?? 3000);
|
||||
await initAuth();
|
||||
console.log(`API server listening on port ${port}`);
|
||||
const server = serve({ fetch: app.fetch, port });
|
||||
console.log(`API server listening on port ${port}`);
|
||||
|
||||
// Start background reminder scheduler (runs every minute to check for upcoming appointments)
|
||||
startReminderScheduler();
|
||||
|
||||
let initAttempt = 0;
|
||||
while (true) {
|
||||
try {
|
||||
await initAuth();
|
||||
break;
|
||||
} catch (err) {
|
||||
initAttempt++;
|
||||
const delay = Math.min(2 ** initAttempt * 500, 30_000);
|
||||
console.error(`[auth] initAuth attempt ${initAttempt} failed: ${err}`);
|
||||
if (initAttempt >= 10) {
|
||||
console.error("[auth] auth init permanently failed — auth endpoints will serve 503");
|
||||
break;
|
||||
}
|
||||
console.error(`[auth] retrying in ${delay}ms`);
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
}
|
||||
}
|
||||
|
||||
function shutdown() {
|
||||
console.log("Shutting down gracefully...");
|
||||
// SIGTERM/SIGINT → server.close() → callback → process.exit(0)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Enforces the trusted-origins CORS allowlist on a raw Response from Better Auth.
|
||||
* Better Auth reflects the request Origin into Access-Control-Allow-Origin
|
||||
* regardless of the trustedOrigins config, allowing credentialed cross-origin reads
|
||||
* from arbitrary attacker origins. This wrapper strips CORS headers for any origin
|
||||
* not in the allowlist. (GRO-2586)
|
||||
*/
|
||||
export function enforceAuthCors(
|
||||
requestOrigin: string | undefined,
|
||||
trustedOrigins: string[],
|
||||
res: Response
|
||||
): Response {
|
||||
const headers = new Headers(res.headers);
|
||||
if (requestOrigin && trustedOrigins.includes(requestOrigin)) {
|
||||
headers.set("Access-Control-Allow-Origin", requestOrigin);
|
||||
headers.set("Access-Control-Allow-Credentials", "true");
|
||||
} else {
|
||||
headers.delete("Access-Control-Allow-Origin");
|
||||
headers.delete("Access-Control-Allow-Credentials");
|
||||
}
|
||||
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
||||
}
|
||||
+31
-9
@@ -118,18 +118,34 @@ export async function initAuth(): Promise<void> {
|
||||
updateAge: 60 * 60 * 24,
|
||||
cookieCache: { enabled: false },
|
||||
},
|
||||
trustedOrigins: [process.env.CORS_ORIGIN ?? "http://localhost:5173"],
|
||||
trustedOrigins: (process.env.CORS_ORIGIN ?? "http://localhost:5173")
|
||||
.split(",").map((s) => s.trim()).filter(Boolean),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 1: Try to load config from DB
|
||||
// Step 1: Try to load config from DB, with retry-with-backoff for transient ECONNRESET (GRO-2652).
|
||||
// A single connection reset during boot must not abort initialization.
|
||||
const db = getDb();
|
||||
const [dbConfig] = await db
|
||||
.select()
|
||||
.from(authProviderConfig)
|
||||
.where(eq(authProviderConfig.enabled, true))
|
||||
.limit(1);
|
||||
let dbQueryRows: (typeof authProviderConfig.$inferSelect)[] = [];
|
||||
let dbAttempt = 0;
|
||||
while (true) {
|
||||
try {
|
||||
dbQueryRows = await db
|
||||
.select()
|
||||
.from(authProviderConfig)
|
||||
.where(eq(authProviderConfig.enabled, true))
|
||||
.limit(1);
|
||||
break;
|
||||
} catch (err) {
|
||||
dbAttempt++;
|
||||
if (dbAttempt >= 5) throw err;
|
||||
const delay = Math.min(1000 * 2 ** (dbAttempt - 1), 8_000);
|
||||
console.warn(`[auth] DB query attempt ${dbAttempt} failed (${err}), retrying in ${delay}ms`);
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
}
|
||||
}
|
||||
const [dbConfig] = dbQueryRows;
|
||||
|
||||
let providerConfig: {
|
||||
providerId: string;
|
||||
@@ -308,9 +324,15 @@ export async function initAuth(): Promise<void> {
|
||||
maxAge: 5 * 60, // 5 minutes
|
||||
},
|
||||
},
|
||||
trustedOrigins: [process.env.CORS_ORIGIN ?? "http://localhost:5173"],
|
||||
trustedOrigins: (process.env.CORS_ORIGIN ?? "http://localhost:5173")
|
||||
.split(",").map((s) => s.trim()).filter(Boolean),
|
||||
});
|
||||
})();
|
||||
|
||||
await authInitPromise;
|
||||
try {
|
||||
await authInitPromise;
|
||||
} catch (err) {
|
||||
authInitPromise = null; // allow retry on next call
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ if (process.env.AUTH_DISABLED === "true") {
|
||||
}
|
||||
|
||||
export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
||||
if (c.req.path.startsWith("/api/auth/") || c.req.path === "/api/health") {
|
||||
if (c.req.path.startsWith("/api/auth/") || c.req.path === "/api/health" || c.req.path === "/api/readyz") {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user