@selvajs/selva 4.21.0-beta.24 → 4.21.0-beta.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/adapter-node.js +1 -1
- package/build/client/_app/immutable/assets/0.Ct4dsf2W.css +2 -0
- package/build/client/_app/immutable/assets/0.Ct4dsf2W.css.br +0 -0
- package/build/client/_app/immutable/assets/0.Ct4dsf2W.css.gz +0 -0
- package/build/client/_app/immutable/chunks/BUxAHI7i.js +1 -0
- package/build/client/_app/immutable/chunks/BUxAHI7i.js.br +1 -0
- package/build/client/_app/immutable/chunks/BUxAHI7i.js.gz +0 -0
- package/build/client/_app/immutable/chunks/C4PDTpD1.js +6085 -0
- package/build/client/_app/immutable/chunks/C4PDTpD1.js.br +0 -0
- package/build/client/_app/immutable/chunks/C4PDTpD1.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.Dl3HM1mx.js → app.Bqmne5hV.js} +2 -2
- package/build/client/_app/immutable/entry/app.Bqmne5hV.js.br +0 -0
- package/build/client/_app/immutable/entry/app.Bqmne5hV.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.Dv262ba8.js +1 -0
- package/build/client/_app/immutable/nodes/21.Dv262ba8.js.br +1 -0
- package/build/client/_app/immutable/nodes/21.Dv262ba8.js.gz +0 -0
- package/build/client/_app/version.json +1 -1
- package/build/client/_app/version.json.br +0 -0
- package/build/client/_app/version.json.gz +0 -0
- package/build/runtime-meta.json +1 -1
- package/build/server/.vite/manifest.json +24 -21
- package/build/server/_app/immutable/assets/_layout.Ct4dsf2W.css +2 -0
- package/build/server/chunks/capture.js +1 -1
- package/build/server/chunks/compute-profile-D3g1Tuyd.js +92 -0
- package/build/server/chunks/compute-profile-D3g1Tuyd.js.map +1 -0
- package/build/server/chunks/compute.js +1 -1
- package/build/server/chunks/engine.server.js +1 -1
- package/build/server/chunks/errors.js +7 -30
- package/build/server/chunks/errors.js.map +1 -1
- package/build/server/chunks/grasshopper.js +6 -1
- package/build/server/chunks/grasshopper.js.map +1 -1
- package/build/server/chunks/handlers.js +5 -4
- package/build/server/chunks/handlers.js.map +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/ops.js +1 -1
- package/build/server/chunks/package.js +1 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/providers.server.js +48 -15
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/{limits.js → saved-values.js} +35 -2
- package/build/server/chunks/saved-values.js.map +1 -0
- package/build/server/chunks/server.js +134 -17
- package/build/server/chunks/server.js.map +1 -1
- package/build/server/chunks/solve.js +1 -1
- package/build/server/chunks/solve.server.js +8 -3
- package/build/server/chunks/solve.server.js.map +1 -1
- package/build/server/chunks/types2.js.map +1 -1
- package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +5 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/v1/solves/_solveId_/_server.ts.js +1 -1
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js +14 -3
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +164 -38
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/0.js +2 -2
- package/build/server/nodes/21.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +11 -11
- package/build/client/_app/immutable/assets/0.DOeouCe4.css +0 -2
- package/build/client/_app/immutable/assets/0.DOeouCe4.css.br +0 -0
- package/build/client/_app/immutable/assets/0.DOeouCe4.css.gz +0 -0
- package/build/client/_app/immutable/chunks/B58dPMPq.js +0 -1
- package/build/client/_app/immutable/chunks/B58dPMPq.js.br +0 -1
- package/build/client/_app/immutable/chunks/B58dPMPq.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DtmN00GS.js +0 -6085
- package/build/client/_app/immutable/chunks/DtmN00GS.js.br +0 -0
- package/build/client/_app/immutable/chunks/DtmN00GS.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.Dl3HM1mx.js.br +0 -0
- package/build/client/_app/immutable/entry/app.Dl3HM1mx.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.BZJQikE5.js +0 -1
- package/build/client/_app/immutable/nodes/21.BZJQikE5.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.BZJQikE5.js.gz +0 -0
- package/build/server/_app/immutable/assets/_layout.DOeouCe4.css +0 -2
- package/build/server/chunks/async-solve-Doflh4BJ.js +0 -27
- package/build/server/chunks/async-solve-Doflh4BJ.js.map +0 -1
- package/build/server/chunks/limits.js.map +0 -1
- /package/build/client/_app/immutable/nodes/{0.BQ4J6cqX.js → 0.BsaBi01M.js} +0 -0
- /package/build/client/_app/immutable/nodes/{0.BQ4J6cqX.js.br → 0.BsaBi01M.js.br} +0 -0
- /package/build/client/_app/immutable/nodes/{0.BQ4J6cqX.js.gz → 0.BsaBi01M.js.gz} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers.server.js","names":["prefix","resolvePath","fs","path","LAST_LOGIN_DEBOUNCE_MS","empty","toAuthUser","path","empty","path","empty","isLive","path","empty","bindingOf","path","empty","path","isLive","path","empty","path","empty","path","empty","path","path","path","path","fs","mapError","readFile","fs","writeFile","path","path"],"sources":["../../../../platform/src/config/report.ts","../../../../platform/src/config/snapshot.ts","../../../../platform/src/errors/interface.ts","../../../../platform/src/data/interface.ts","../../../../platform/src/storage/safeKey.ts","../../../../platform/src/definitions/paths.ts","../../../../platform/src/events/interface.ts","../../../../platform/src/organizations/paths.ts","../../../../platform/src/permissions/guards.ts","../../../../platform/src/storage/image.ts","../../../../platform/src/storage/assetClasses.ts","../../../../platform/src/storage/cacheBust.ts","../../../../platform/src/userProfile/types.ts","../../../../platform/src/userProfile/guards.ts","../../../../platform/src/utils/audit.ts","../../../../platform/src/metrics/interface.ts","../../../../server/src/providers/create-selva-providers.ts","../../../../providers/local/src/auth/hmac.ts","../../../../providers/local/src/data/fsJson.ts","../../../../providers/local/src/auth/users.ts","../../../../providers/local/src/data/pagination.ts","../../../../providers/local/src/auth/LocalAuthProvider.ts","../../../../providers/local/src/data/LocalInviteStore.ts","../../../../providers/local/src/data/LocalApiTokenStore.ts","../../../../platform/src/computeServer/secrets.ts","../../../../providers/local/src/data/LocalComputeServerStore.ts","../../../../providers/local/src/data/LocalPlatformProjectGrantStore.ts","../../../../providers/local/src/data/LocalOrgStore.ts","../../../../providers/local/src/data/LocalProjectStore.ts","../../../../providers/local/src/data/LocalDefinitionStore.ts","../../../../providers/local/src/data/LocalShareLinkStore.ts","../../../../providers/local/src/data/userData.ts","../../../../providers/local/src/userProfile/LocalUserProfileProvider.ts","../../../../providers/local/src/permissions/LocalPlatformPermissionStore.ts","../../../../providers/local/src/data/LocalDataProvider.ts","../../../../providers/local/src/storage/LocalStorageProvider.ts","../../../../providers/supabase/src/storage/SupabaseStorageProvider.ts","../../../../providers/supabase/src/data/errors.ts","../../../../providers/supabase/src/data/SupabasePlatformProjectGrantStore.ts","../../../../providers/supabase/src/data/pagination.ts","../../../../providers/supabase/src/data/rowStamp.ts","../../../../providers/supabase/src/data/SupabaseOrgStore.ts","../../../../providers/supabase/src/data/SupabaseProjectStore.ts","../../../../providers/supabase/src/data/SupabaseDefinitionStore.ts","../../../../providers/supabase/src/data/SupabaseInviteStore.ts","../../../../providers/supabase/src/data/SupabaseComputeServerStore.ts","../../../../providers/supabase/src/data/SupabaseShareLinkStore.ts","../../../../providers/supabase/src/data/SupabaseApiTokenStore.ts","../../../../providers/supabase/src/data/migrationHead.ts","../../../../providers/supabase/src/data/client.ts","../../../../providers/supabase/src/data/SupabaseEventSink.ts","../../../../providers/supabase/src/data/SupabaseSolveMetricSink.ts","../../../../providers/supabase/src/data/SupabaseAuditQuery.ts","../../../../providers/supabase/src/userProfile/SupabaseUserProfileProvider.ts","../../../../providers/supabase/src/permissions/SupabasePlatformPermissionStore.ts","../../../../providers/supabase/src/data/SupabaseDataProvider.ts","../../../../providers/supabase/src/auth/SupabaseDelegatedSession.ts","../../../../providers/supabase/src/config.ts","../../../../providers/supabase/src/auth/SupabaseAuthProvider.ts","../../../../providers/header-auth/src/users.ts","../../../../providers/header-auth/src/HeaderAuthProvider.ts","../../../../server/src/definitions/definition-service.ts","../../../../server/src/organizations/org-asset-service.ts","../../../../server/src/errors/scrub.ts","../../../../server/src/errors/SentryErrorReporter.ts","../../../../server/src/notifications/smtp-config.ts","../../../../server/src/notifications/smtp-provider.ts","../../../../providers/header-auth/src/config.ts","../../../../providers/local/src/config.ts","../../../src/lib/server/config/settings.ts","../../../src/lib/server/providers.server.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { IntUnit, Manifest, SettingClass, SettingSpec } from './manifest.js';\nimport {\n\tresolveConfig,\n\ttype EnvRecord,\n\ttype KeyReport,\n\ttype KeyStatus,\n\ttype ResolveOptions,\n\ttype UnknownKey,\n\ttype ValueSource\n} from './resolve.js';\nimport { rawValue } from './raw-value.js';\n\nexport interface ReportRow {\n\tkey: string;\n\tlabel?: string;\n\ttype: SettingSpec['type'];\n\trequired: boolean;\n\t/** What 0 means for an int whose 0 is a sentinel. */\n\tzero?: string;\n\tunit?: IntUnit;\n\tclass: SettingClass;\n\tsummary: boolean;\n\tdescription: string;\n\timpact?: string;\n\tsource: ValueSource;\n\tstatus: KeyStatus;\n\t/** Safe to print: secrets are a fingerprint or \"set\", never the value. */\n\tdisplay: string;\n\tproblem?: string;\n\talias?: string;\n}\n\nexport interface ConfigReport {\n\t/** Summary rows first, then the rest, each in manifest order. */\n\trows: ReportRow[];\n\t/** Rows whose value failed its rule. */\n\tproblems: ReportRow[];\n\tunknown: UnknownKey[];\n}\n\n/**\n * What `selva config show` and the admin page render. Pure, and free of\n * secret values, so the result can go to a browser or a terminal as is.\n */\nexport function buildConfigReport(\n\tmanifest: Manifest,\n\tenv: EnvRecord,\n\toptions: ResolveOptions = {}\n): ConfigReport {\n\tconst resolved = resolveConfig(manifest, env, options);\n\tconst rows: ReportRow[] = manifest.map((spec) => {\n\t\tconst k = resolved.keys[spec.key];\n\t\treturn {\n\t\t\tkey: spec.key,\n\t\t\t...(spec.label ? { label: spec.label } : {}),\n\t\t\ttype: spec.type,\n\t\t\trequired: spec.required === true,\n\t\t\t...(spec.type === 'int' && spec.zero ? { zero: spec.zero } : {}),\n\t\t\t...(spec.type === 'int' && spec.unit ? { unit: spec.unit } : {}),\n\t\t\tclass: spec.class,\n\t\t\tsummary: spec.summary === true,\n\t\t\tdescription: spec.description,\n\t\t\t...(spec.impact ? { impact: spec.impact } : {}),\n\t\t\tsource: k.source,\n\t\t\tstatus: k.status,\n\t\t\tdisplay: display(spec, k, rawValue(spec, env)?.raw),\n\t\t\t...(k.problem ? { problem: k.problem } : {}),\n\t\t\t...(k.alias ? { alias: k.alias } : {})\n\t\t};\n\t});\n\treturn {\n\t\trows: [...rows.filter((r) => r.summary), ...rows.filter((r) => !r.summary)],\n\t\tproblems: rows.filter((r) => r.status !== 'ok'),\n\t\tunknown: resolved.unknown\n\t};\n}\n\n/** `raw` is the env text the value came from, undefined when it is the default. */\nfunction display(spec: SettingSpec, k: KeyReport, raw: string | undefined): string {\n\tif (k.source === 'unset') return '';\n\tif (spec.sensitive) {\n\t\t// A fingerprint of a 256-bit random key reveals nothing; of a password it\n\t\t// would be an offline guessing oracle.\n\t\treturn raw !== undefined && spec.generated ? fingerprint(raw) : 'set';\n\t}\n\treturn raw === undefined ? formatValue(k.value) : raw.trim();\n}\n\nfunction formatValue(value: unknown): string {\n\tif (Array.isArray(value)) return value.join(',');\n\treturn value === undefined ? '' : String(value);\n}\n\n/** Short, stable id for a generated key, so two machines can be compared. */\nexport function fingerprint(value: string): string {\n\treturn `sha256:${createHash('sha256').update(value.trim()).digest('hex').slice(0, 8)}`;\n}\n","import { createHmac, randomBytes } from 'node:crypto';\nimport type { Manifest } from './manifest.js';\nimport type { EnvRecord } from './resolve.js';\nimport { rawValue } from './raw-value.js';\n\n/**\n * The set keys of one boot, written beside `.env` so the next boot, and the\n * CLI, can say what changed. The file must not become a second copy of the\n * secrets: a generated key is stored as a salted HMAC, any other sensitive\n * value as a fixed marker, since a digest of a password or an email address\n * can be guessed back with the salt beside it.\n */\nexport interface ConfigSnapshot {\n\tversion: 1;\n\tsalt: string;\n\tvalues: Record<string, string>;\n\t/** Keys whose `values` entry is a digest or the marker, not the value. */\n\tsensitive: string[];\n}\n\nexport interface ConfigChange {\n\tkey: string;\n\tchange: 'added' | 'removed' | 'changed';\n\t/** Absent for sensitive keys. */\n\tfrom?: string;\n\tto?: string;\n}\n\nconst SENSITIVE_MARKER = 'set';\n\nexport function takeSnapshot(manifest: Manifest, env: EnvRecord, salt?: string): ConfigSnapshot {\n\t// A JS caller passes the previous file's salt as parsed; anything else starts afresh.\n\tconst key = typeof salt === 'string' && salt !== '' ? salt : randomBytes(16).toString('hex');\n\tconst values: Record<string, string> = {};\n\tconst sensitive: string[] = [];\n\tfor (const spec of manifest) {\n\t\tconst found = rawValue(spec, env);\n\t\tif (!found) continue;\n\t\tconst raw = found.raw.trim();\n\t\tif (spec.sensitive) {\n\t\t\tvalues[spec.key] = spec.generated\n\t\t\t\t? createHmac('sha256', key).update(raw).digest('hex').slice(0, 16)\n\t\t\t\t: SENSITIVE_MARKER;\n\t\t\tsensitive.push(spec.key);\n\t\t} else {\n\t\t\tvalues[spec.key] = raw;\n\t\t}\n\t}\n\treturn { version: 1, salt: key, values, sensitive };\n}\n\n/**\n * What changed since `before`, the previous snapshot as read from disk; anything\n * that is not a snapshot counts as none. Take `after` with `before.salt`, or every\n * generated key reads as changed.\n */\nexport function diffSnapshots(before: unknown, after: ConfigSnapshot): ConfigChange[] {\n\tif (!isSnapshot(before)) return [];\n\tconst secret = new Set([...before.sensitive, ...after.sensitive]);\n\tconst changes: ConfigChange[] = [];\n\tconst plain = (key: string, from?: string, to?: string) =>\n\t\tsecret.has(key)\n\t\t\t? {}\n\t\t\t: { ...(from !== undefined ? { from } : {}), ...(to !== undefined ? { to } : {}) };\n\n\tfor (const [key, to] of Object.entries(after.values)) {\n\t\tconst from = before.values[key];\n\t\tif (from === undefined) changes.push({ key, change: 'added', ...plain(key, undefined, to) });\n\t\telse if (from !== to) changes.push({ key, change: 'changed', ...plain(key, from, to) });\n\t}\n\tfor (const [key, from] of Object.entries(before.values)) {\n\t\tif (!(key in after.values)) changes.push({ key, change: 'removed', ...plain(key, from) });\n\t}\n\treturn changes;\n}\n\nfunction isSnapshot(value: unknown): value is ConfigSnapshot {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst { version, salt, values, sensitive } = value as Record<string, unknown>;\n\treturn (\n\t\tversion === 1 &&\n\t\ttypeof salt === 'string' &&\n\t\tsalt !== '' &&\n\t\ttypeof values === 'object' &&\n\t\tvalues !== null &&\n\t\t!Array.isArray(values) &&\n\t\tObject.values(values).every((v) => typeof v === 'string') &&\n\t\tArray.isArray(sensitive) &&\n\t\tsensitive.every((k) => typeof k === 'string')\n\t);\n}\n","/**\n * Structured context attached to a reported error. All fields optional — a\n * report can fire before any request context is built (e.g. an\n * `unhandledRejection` with no active request). Deliberately NOT a\n * `RequestContext`: reporters must never receive the opaque `adapterContext`, so\n * only non-sensitive routing/identity fields are surfaced here.\n */\nexport interface ErrorContext {\n\tmethod?: string;\n\t/** Never the query string — it can carry share tokens. */\n\troute?: string;\n\tuserId?: string;\n\torgId?: string;\n\ttags?: Record<string, string>;\n\t/** How urgent the report is. Default `error`; `warning` for a handled fault worth watching. */\n\tlevel?: 'fatal' | 'error' | 'warning';\n\t/**\n\t * Groups reports of one fault across messages (`compute-auth`, `compute-unreachable`), so\n\t * a fault whose message varies still reads as one issue.\n\t */\n\tkind?: string;\n}\n\n/**\n * Sink for unexpected server errors, including unhandled rejections and uncaught\n * exceptions.\n *\n * MUST NOT throw — reporting is best-effort and sits on the error path, where a\n * second failure would mask the first. Implementations catch and log their own\n * failures. MAY be fire-and-forget.\n */\nexport interface IErrorReporter {\n\t/**\n\t * `error` is whatever was thrown/rejected — often an `Error`, but adapters\n\t * occasionally reject with a plain object, so implementations must render\n\t * defensively.\n\t */\n\tcapture(error: unknown, context?: ErrorContext): void;\n}\n\n/**\n * Default `IErrorReporter` — discards every report, so call sites can report\n * unconditionally when no error-tracking backend is configured.\n */\nexport class NoopErrorReporter implements IErrorReporter {\n\tcapture(_error: unknown, _context?: ErrorContext): void {}\n}\n","/**\n * Composition root bundling every store an adapter implements. Individual\n * interfaces (`IOrgStore`, `IProjectStore`, …) live next to their types in\n * their own subdirs.\n *\n * Every store method takes a `RequestContext` first. **The query itself is\n * the security boundary** — adapters MUST scope reads/writes by `ctx`. An\n * unauthorized caller sees an empty page, `null`, or a `ProviderError`.\n *\n * Access-control predicates live in `@selvajs/platform/access`, not here.\n */\n\nimport type { IOrgStore } from '../organizations/interface.js';\nimport type { IProjectStore } from '../projects/interface.js';\nimport type { IDefinitionStore } from '../definitions/interface.js';\nimport type { IComputeServerStore } from '../computeServer/interface.js';\nimport type { IShareLinkStore } from '../shareLinks/interface.js';\nimport type { IPlatformProjectGrantStore } from '../platformProjects/interface.js';\nimport type { IInviteStore } from '../invites/interface.js';\nimport type { IApiTokenStore } from '../apiTokens/interface.js';\nimport type { IUserProfileStore } from '../userProfile/interface.js';\nimport type { IPlatformPermissionStore } from '../permissions/interface.js';\nimport type { IAuditQuery } from '../events/audit.js';\nimport type { IEventSink } from '../events/interface.js';\nimport type { RequestContext } from '../context.js';\n\n/**\n * Result of the app↔DB schema handshake. `expected` is the migration head\n * the running app was built against; `actual` is what the database reports\n * (`null` when the database can't even answer — e.g. the handshake function\n * itself was never migrated in).\n */\nexport interface SchemaVersionReport {\n\tok: boolean;\n\texpected: string;\n\tactual: string | null;\n\t/** Operator-facing explanation + recovery hint: why not ok, or, when ok, what is still pending. */\n\tmessage?: string;\n}\n\n/** Extra identifiers {@link IDataProvider.onUserDeleted} needs but can't derive from userId alone. */\nexport interface UserErasureOptions {\n\t/** The deleted user's email, for scrubbing invite/audit rows keyed by it. */\n\temail?: string;\n}\n\n/**\n * Written to `solve_metrics.actor_id` when a user is erased, so capacity/billing\n * aggregates survive without identifying the person. Distinct from `'system'`,\n * which marks solves never attributed to a user (share-link / server flows).\n */\nexport const ERASED_ACTOR_ID = 'deleted';\n\nexport interface IDataProvider {\n\torgs: IOrgStore;\n\tprojects: IProjectStore;\n\tdefinitions: IDefinitionStore;\n\tcomputeServer: IComputeServerStore;\n\tinvites: IInviteStore;\n\tshareLinks: IShareLinkStore;\n\tuserProfile: IUserProfileStore;\n\tpermissions: IPlatformPermissionStore;\n\tplatformProjectGrants: IPlatformProjectGrantStore;\n\t/**\n\t * Optional: a provider without it has API tokens switched off, and token\n\t * requests get 503 `API_TOKENS_UNAVAILABLE`. A provider whose stores scope\n\t * by a user JWT must also implement `IAuthProvider.delegatedSession`.\n\t */\n\tapiTokens?: IApiTokenStore;\n\t/**\n\t * Read-side for the persisted event log. Optional — providers whose event\n\t * sink is a noop (local-provider) leave this undefined and the\n\t * `/admin/audit` UI degrades to its \"no backend wired\" state.\n\t */\n\tauditQuery?: IAuditQuery;\n\t/**\n\t * Write-side event sink this provider's stores emit into. Optional — lets app\n\t * code with no store mutation to piggyback on (e.g. a self-update route) emit\n\t * domain events into the same log. Callers fall back to `NoopEventSink` when absent.\n\t */\n\tevents?: IEventSink;\n\n\t/**\n\t * Optional — only adapters whose schema migrates out-of-band (Supabase:\n\t * `supabase db push` is a manual operator step) need this. Boot health calls\n\t * it and drives `/api/health` to 503 when the database is behind the app,\n\t * so schema skew surfaces as a health check instead of per-request store errors.\n\t *\n\t * MUST NOT throw: report failure via `ok: false`.\n\t */\n\tverifySchemaVersion?(): Promise<SchemaVersionReport>;\n\n\t/**\n\t * Idempotently registers a user in the data layer. Called by `hooks.server.ts`\n\t * after `verifyToken` succeeds, so the data layer always has a row for the\n\t * authenticated user regardless of which auth provider issued the ID.\n\t *\n\t * Adapters with a DB-side trigger that auto-seeds on auth signup (Supabase)\n\t * make this a no-op. Adapters owning a separate user-data table without a\n\t * trigger (local-provider) upsert here.\n\t *\n\t * MUST be safe to call concurrently and on every request. MUST NOT throw on\n\t * a duplicate userId.\n\t */\n\tensureUser(ctx: RequestContext, userId: string): Promise<void>;\n\n\t/**\n\t * Cascade + erasure hook called after the auth provider deletes a user.\n\t * Removes or anonymizes data-layer rows tied to that user.\n\t *\n\t * Most user-owned rows die via FK cascade / `set null` against `auth.users`\n\t * (Supabase) or explicit membership cleanup (local). Some personal data is\n\t * NOT reachable by those FKs and MUST be scrubbed here:\n\t * - audit rows keyed by a plain-text `actor_id` (no FK),\n\t * - invites addressed to the user's `email`, and that email embedded in\n\t * `invite.created` audit payloads,\n\t * - `solve_metrics`, deliberately not FK-cascaded — anonymized (actor\n\t * tombstoned), not deleted.\n\t *\n\t * `opts.email` is the deleted user's email; the CALLER must capture it\n\t * BEFORE `deleteUser` runs (the auth user is already gone by the time this\n\t * hook fires). When absent, email-keyed scrubs are skipped.\n\t *\n\t * MUST tolerate a missing user and missing rows (idempotent — caller may retry).\n\t */\n\tonUserDeleted(ctx: RequestContext, userId: string, opts?: UserErasureOptions): Promise<void>;\n\n\t/**\n\t * Deletes audit events and solve metrics recorded before the given cutoffs.\n\t * Absent on a provider that keeps neither. MUST be idempotent: a janitor\n\t * calls it on a timer and retries after a failure.\n\t */\n\tpurgeExpired?(ctx: RequestContext, cutoffs: RetentionCutoffs): Promise<PurgeResult>;\n}\n\n/** An omitted cutoff keeps that table whole. */\nexport interface RetentionCutoffs {\n\tauditEventsBefore?: Date;\n\tsolveMetricsBefore?: Date;\n}\n\n/** Rows deleted per table. */\nexport interface PurgeResult {\n\tauditEvents: number;\n\tsolveMetrics: number;\n}\n","/** Alphabet of one storage path segment, as regex source. Covers GUIDs and sanitized refs. */\nexport const SAFE_SEGMENT = String.raw`[A-Za-z0-9._-]+`;\n\nconst SAFE_SEGMENT_ONLY = new RegExp(`^${SAFE_SEGMENT}$`);\n\n/**\n * Blocks traversal, separators, NUL and empty segments, so a malicious id can't\n * escape its prefix. The alphabet admits `.` and `..`, so those need their own check.\n */\nexport function assertSafeKey(value: string, label: string): void {\n\tif (!value || !SAFE_SEGMENT_ONLY.test(value) || value === '.' || value === '..') {\n\t\tthrow new Error(`Unsafe ${label}: ${JSON.stringify(value)}`);\n\t}\n}\n","import { assertSafeKey } from '../storage/safeKey.js';\nimport type { DefinitionFileExt } from './types.js';\n\nfunction prefix(guid: string): string {\n\tassertSafeKey(guid, 'guid');\n\treturn `definitions/${guid}/`;\n}\n\nexport const definitionPaths = {\n\tversion: (guid: string, versionNumber: number, ext: DefinitionFileExt) => {\n\t\tconst dir = prefix(guid);\n\t\tif (!Number.isInteger(versionNumber) || versionNumber < 1) {\n\t\t\tthrow new Error(`Unsafe versionNumber: ${versionNumber}`);\n\t\t}\n\t\treturn `${dir}versions/v${versionNumber}.${ext}`;\n\t},\n\timage: (guid: string) => `${prefix(guid)}cover.webp`,\n\tprefix\n} as const;\n","import type { ApiTokenRevokeReason } from '../apiTokens/types.js';\n\ntype DomainEventBody =\n\t| { type: 'org.created'; orgId: string; actorId: string }\n\t| { type: 'org.deleted'; orgId: string; actorId: string }\n\t| { type: 'org_member.added'; orgId: string; userId: string; actorId: string }\n\t| { type: 'org_member.removed'; orgId: string; userId: string; actorId: string }\n\t// Offboarding that left projects with no owner. Removal doesn't wait for a new\n\t// owner, so this event is the only signal that someone needs to reclaim them.\n\t| {\n\t\t\ttype: 'org_member.removed_orphaning_projects';\n\t\t\torgId: string;\n\t\t\tuserId: string;\n\t\t\tprojectIds: readonly string[];\n\t\t\tactorId: string;\n\t }\n\t| {\n\t\t\ttype: 'org_member.role_changed';\n\t\t\torgId: string;\n\t\t\tuserId: string;\n\t\t\trole: string;\n\t\t\tactorId: string;\n\t }\n\t| {\n\t\t\ttype: 'org_member.permissions_changed';\n\t\t\torgId: string;\n\t\t\tuserId: string;\n\t\t\tpermissions: readonly string[];\n\t\t\tactorId: string;\n\t }\n\t| { type: 'project.created'; projectId: string; orgId: string; actorId: string }\n\t| { type: 'project.deleted'; projectId: string; actorId: string }\n\t| { type: 'project_member.added'; projectId: string; userId: string; actorId: string }\n\t// Org leadership forcing its way into a project it holds no membership in.\n\t// Distinct from `project_member.added` because the two are otherwise\n\t// indistinguishable in the log, and the escalation is permitted precisely\n\t// on the strength of being auditable afterwards.\n\t| {\n\t\t\ttype: 'project.reclaimed';\n\t\t\tprojectId: string;\n\t\t\torgId: string;\n\t\t\tactorId: string;\n\t\t\tpriorVisibility: string;\n\t }\n\t| { type: 'project_member.removed'; projectId: string; userId: string; actorId: string }\n\t| {\n\t\t\ttype: 'project_member.role_changed';\n\t\t\tprojectId: string;\n\t\t\tuserId: string;\n\t\t\trole: string;\n\t\t\tactorId: string;\n\t }\n\t| { type: 'definition.created'; definitionId: string; projectId: string; actorId: string }\n\t| { type: 'definition.deleted'; definitionId: string; actorId: string }\n\t| { type: 'definition.published'; definitionId: string; versionId: string; actorId: string }\n\t| {\n\t\t\ttype: 'definition_version.created';\n\t\t\tversionId: string;\n\t\t\tdefinitionId: string;\n\t\t\tactorId: string;\n\t }\n\t| { type: 'definition_version.deleted'; versionId: string; actorId: string }\n\t| { type: 'share_link.minted'; linkId: string; definitionId: string; actorId: string }\n\t| { type: 'share_link.revoked'; linkId: string; actorId: string }\n\t| {\n\t\t\ttype: 'invite.created';\n\t\t\tinviteId: string;\n\t\t\torgId: string;\n\t\t\t/** Plain text, unlike every other identifier here — redacted on erasure via `redact_audit_event_email`. */\n\t\t\temail: string;\n\t\t\tactorId: string;\n\t }\n\t| { type: 'invite.accepted'; inviteId: string; orgId: string; userId: string; actorId: string }\n\t| { type: 'invite.revoked'; inviteId: string; orgId: string; actorId: string }\n\t// Ids only: the token name is free text people fill with personal detail.\n\t| {\n\t\t\ttype: 'api_token.created';\n\t\t\tapiTokenId: string;\n\t\t\torgId: string;\n\t\t\tuserId: string;\n\t\t\tactorId: string;\n\t }\n\t| {\n\t\t\ttype: 'api_token.revoked';\n\t\t\tapiTokenId: string;\n\t\t\torgId: string;\n\t\t\treason: ApiTokenRevokeReason;\n\t\t\tactorId: string;\n\t }\n\t// Platform scope. `instance_admin` reaches every tenant's data, so a change\n\t// to it is the one grant whose history has to survive the admin who made it —\n\t// including the self-elevate/act/revoke sequence, which leaves no other trace.\n\t| { type: 'user.created'; userId: string; actorId: string }\n\t| { type: 'user.deleted'; userId: string; actorId: string }\n\t| { type: 'user.disabled'; userId: string; actorId: string }\n\t| {\n\t\t\ttype: 'platform_permissions.changed';\n\t\t\tuserId: string;\n\t\t\t/** Post-change set. The prior set is not recorded — read the preceding event of this type. */\n\t\t\tpermissions: readonly string[];\n\t\t\tactorId: string;\n\t }\n\t// `started` is emitted by the process that launches the update; the app\n\t// restarts mid-update, so the terminal event comes from post-restart\n\t// reconciliation of the persisted update log, not the launching process.\n\t| { type: 'system.update.started'; channel: string; fromVersion?: string; actorId: string }\n\t| {\n\t\t\ttype: 'system.update.finished';\n\t\t\tfromVersion?: string;\n\t\t\ttoVersion?: string;\n\t\t\tdetail?: string;\n\t\t\tactorId: string;\n\t }\n\t| {\n\t\t\ttype: 'system.update.rolled_back';\n\t\t\tfromVersion?: string;\n\t\t\ttoVersion?: string;\n\t\t\tdetail?: string;\n\t\t\tactorId: string;\n\t }\n\t| {\n\t\t\ttype: 'system.update.failed';\n\t\t\tfromVersion?: string;\n\t\t\ttoVersion?: string;\n\t\t\tdetail?: string;\n\t\t\tactorId: string;\n\t };\n\n/**\n * `tokenId` is set on any event written during an API-token request, so a\n * key's actions can be told apart from the same person's browser actions.\n * Spread {@link actorOf} rather than setting it by hand.\n */\nexport type DomainEvent = DomainEventBody & { tokenId?: string };\n\nexport type DomainEventType = DomainEvent['type'];\n\n/**\n * What every event a sink accepts carries. A host writes its own events beside Selva's\n * through an `IEventSink<DomainEvent | HostEvent>`, which still satisfies Selva's\n * `IEventSink`. Prefix host `type`s so they can't collide with a later Selva event.\n */\nexport interface BaseEvent {\n\ttype: string;\n\tactorId: string;\n\ttokenId?: string;\n}\n\n/**\n * A durable sink (e.g. Supabase `audit_events.event_version`) stamps every row\n * with this so a reader dispatches on an explicit version instead of\n * inferring the shape. Bump when the union's persisted form changes in a\n * non-additive way.\n */\nexport const AUDIT_EVENT_VERSION = 1;\n\nexport interface IEventSink<E extends BaseEvent = DomainEvent> {\n\t/**\n\t * Stores call this AFTER a successful mutation; a failed write does not\n\t * emit.\n\t *\n\t * MUST NOT throw — an exception here would surface as a failed write even\n\t * though the mutation already committed. Implementations must catch\n\t * network errors, queue overflows, and other failures internally and log\n\t * them; the caller only ever sees a fulfilled promise.\n\t *\n\t * MAY be fire-and-forget: the contract is best-effort durable recording,\n\t * not synchronous persistence. Adapters that queue and flush\n\t * asynchronously are fine as long as they preserve event ordering per\n\t * `actorId`.\n\t */\n\temit(event: E): Promise<void>;\n}\n\n/**\n * `ctx.userId === ''` is the `SYSTEM_CONTEXT` convention for a server-internal\n * caller (bootstrap, janitors, migrations), which resolves to `'system'` here.\n */\nexport function actorFrom(ctx: {\n\tuserId: string;\n\t/** @deprecated Never read: an empty `userId` alone marks a system caller. */\n\tsystem?: boolean;\n}): string {\n\treturn ctx.userId || 'system';\n}\n\n/** `actorId` plus, for an API-token request, `tokenId`. Spread into an event. */\nexport function actorOf(ctx: {\n\tuserId: string;\n\t/** @deprecated Never read: an empty `userId` alone marks a system caller. */\n\tsystem?: boolean;\n\tapiScope?: { tokenId: string };\n}): { actorId: string; tokenId?: string } {\n\tconst actorId = actorFrom(ctx);\n\treturn ctx.apiScope ? { actorId, tokenId: ctx.apiScope.tokenId } : { actorId };\n}\n\n/** Discards every event. Used when `SelvaConfig.events` is omitted. */\nexport class NoopEventSink<E extends BaseEvent = DomainEvent> implements IEventSink<E> {\n\tasync emit(_event: E): Promise<void> {}\n}\n","import { assertSafeKey } from '../storage/safeKey.js';\nimport type { OrgAssetKind } from './schemas.js';\n\nfunction prefix(id: string): string {\n\tassertSafeKey(id, 'orgId');\n\treturn `orgs/${id}/`;\n}\n\n/**\n * Every branding asset is stored as `.webp` (uploads go through the shared\n * transcoder), so the path per kind is fixed and a re-upload overwrites in\n * place via `IStorageProvider.put`'s upsert.\n *\n * Branding lives under `orgs/{id}/branding/` because it's a *public* asset\n * class — anyone, including logged-out viewers, may read a company logo.\n * `classifyAssetPath` / `ASSET_CLASSES` decide visibility from these prefixes.\n */\nexport const orgPaths = {\n\tasset: (id: string, kind: OrgAssetKind) => {\n\t\tassertSafeKey(kind, 'assetKind');\n\t\treturn `${prefix(id)}branding/${kind}.webp`;\n\t},\n\tprefix\n} as const;\n","import { assertNotShareContext, hasPermission, type RequestContext } from '../context.js';\nimport { ProviderError } from '../errors/index.js';\n\n// For `IPlatformPermissionStore` adapters whose backing store is too coarse to enforce\n// these themselves. Reading one row and reading many agree, and read access is not\n// authority: `set` stays `instance_admin`-only.\n\n/** May `ctx` read `userId`'s platform permissions? Throws `ProviderError(403)` if not. */\nexport function assertCanReadPermissions(ctx: RequestContext, userId: string): void {\n\tassertNotShareContext(ctx, 'read permissions');\n\tif (ctx.userId === userId || hasPermission(ctx, 'manage_instance_users')) return;\n\tthrow new ProviderError('Forbidden: cannot read another user’s permissions', 403);\n}\n\n/** May `ctx` read several users' platform permissions? Throws `ProviderError(403)` if not. */\nexport function assertCanReadPermissionsBatch(ctx: RequestContext): void {\n\tassertNotShareContext(ctx, 'read permissions');\n\tif (hasPermission(ctx, 'manage_instance_users')) return;\n\tthrow new ProviderError('Forbidden: instance admin or manage_instance_users required', 403);\n}\n\n/** May `ctx` change platform permissions? Throws `ProviderError(403)` if not. */\nexport function assertCanManagePermissions(ctx: RequestContext): void {\n\tassertNotShareContext(ctx, 'manage permissions');\n\tif (hasPermission(ctx, 'instance_admin')) return;\n\tthrow new ProviderError('Forbidden: instance admin required', 403);\n}\n","/**\n * Shared image-transcoding helper for `IStorageProvider` implementations.\n * Normalizes uploads to WebP (at most 1200px on either side, quality 85) so\n * storage, bandwidth, and the viewer path stay predictable.\n *\n * `sharp` is a dynamic import, not a hard dependency of this package —\n * providers that need transcoding install it themselves.\n */\n\nimport { ProviderError } from '../errors/index.js';\n\nexport const IMAGE_MAX_WIDTH = 1200;\nexport const IMAGE_WEBP_QUALITY = 85;\n\n// A small upload can decode to gigabytes or burn seconds of CPU: the size cap on\n// the request says nothing about either. 60 MP covers a phone camera's full frame.\nconst MAX_INPUT_PIXELS = 60_000_000;\n// Area alone lets a 1 x 59,000,000 strip through, which decodes past the timeout.\nconst MAX_INPUT_SIDE = 16_384;\nconst TRANSCODE_TIMEOUT_SECONDS = 10;\nexport const MAX_CONCURRENT_TRANSCODES = 2;\nexport const MAX_WAITING_TRANSCODES = 8;\n// Two worst-case transcodes ahead of a waiter; past that the client should retry.\nconst TRANSCODE_WAIT_MS = 2 * TRANSCODE_TIMEOUT_SECONDS * 1000;\n\n// librsvg can draw for minutes without sharp's timeout firing: a filter, nested\n// `<use>`, masks or markers, a fine dash pattern. A declared SVG has to be cheap\n// before it reaches sharp.\nconst SVG_MAX_BYTES = 1024 * 1024;\nconst SVG_MAX_ELEMENTS = 10_000;\n// Encodings that spell markup in plain ASCII bytes, so the checks can see it.\nconst SVG_ENCODINGS = new Set(['utf-8', 'us-ascii', 'iso-8859-1']);\n\ntype ImageFormat = 'jpeg' | 'png' | 'gif' | 'webp' | 'tiff' | 'svg';\n\nexport interface TranscodeResult {\n\tdata: Uint8Array;\n\tcontentType: string;\n\t/** Possibly-rewritten path (non-webp inputs become `.webp`). */\n\tpath: string;\n}\n\n/** True if the input is an image to process. The content type decides, unless it says nothing. */\nexport function isImageUpload(contentType: string | undefined, storagePath: string): boolean {\n\tconst type = mediaType(contentType);\n\tif (type && type !== 'application/octet-stream') {\n\t\treturn type.startsWith('image/');\n\t}\n\treturn /\\.(webp|png|jpe?g|gif|tif?f|svg)$/i.test(storagePath);\n}\n\n/**\n * Rewrites a path's extension to `.webp`; unchanged for non-image extensions.\n * SVG is rasterized like any other input, so no vector blob is ever\n * persisted — served bytes stay XSS-free without a sanitizer.\n */\nexport function toWebpPath(storagePath: string): string {\n\treturn storagePath.replace(/\\.(png|jpe?g|gif|tif?f|svg)$/i, '.webp');\n}\n\n/**\n * Transcodes images to WebP; passes non-images through unchanged, so\n * providers can call this unconditionally before `put`.\n *\n * Throws `ProviderError(422)` for bytes it won't process, `ProviderError(503)`\n * when too many transcodes are queued, and a plain error if `sharp` isn't\n * installed, which is a config problem rather than a bad upload.\n */\nexport async function transcodeImageIfNeeded(\n\tdata: Uint8Array,\n\tcontentType: string | undefined,\n\tstoragePath: string\n): Promise<TranscodeResult> {\n\tif (!isImageUpload(contentType, storagePath)) {\n\t\treturn { data, contentType: contentType ?? 'application/octet-stream', path: storagePath };\n\t}\n\n\tconst input = Buffer.from(data);\n\tconst format = checkFormat(input, contentType, storagePath);\n\tconst sharp = await loadSharp();\n\tconst compressed = await withTranscodeSlot(() => rasterize(sharp, input, format));\n\n\treturn {\n\t\tdata: new Uint8Array(compressed),\n\t\tcontentType: 'image/webp',\n\t\tpath: toWebpPath(storagePath)\n\t};\n}\n\nfunction mediaType(contentType: string | undefined): string {\n\treturn (contentType ?? '').split(';')[0].trim().toLowerCase();\n}\n\n/** Refuses what sharp should never parse, from the bytes alone. */\nfunction checkFormat(\n\tinput: Buffer,\n\tcontentType: string | undefined,\n\tstoragePath: string\n): ImageFormat {\n\tconst format = sniffFormat(input);\n\tif (!format) throw new ProviderError('Unsupported image format', 422);\n\tif (format === 'svg') {\n\t\t// SVG is the expensive format, so it has to be asked for: a route that only\n\t\t// checks the declared type must not let one in as a PNG.\n\t\tconst declared = mediaType(contentType) === 'image/svg+xml' || /\\.svg$/i.test(storagePath);\n\t\tif (!declared) throw new ProviderError('SVG content needs the image/svg+xml type', 422);\n\t\tcheckSvg(input);\n\t}\n\treturn format;\n}\n\nfunction sniffFormat(input: Buffer): ImageFormat | null {\n\tconst head = input.subarray(0, 12).toString('latin1');\n\tif (head.startsWith('\\xFF\\xD8\\xFF')) return 'jpeg';\n\tif (head.startsWith('\\x89PNG\\r\\n\\x1A\\n')) return 'png';\n\tif (head.startsWith('GIF87a') || head.startsWith('GIF89a')) return 'gif';\n\tif (head.startsWith('RIFF') && head.slice(8, 12) === 'WEBP') return 'webp';\n\tif (head.startsWith('II*\\0') || head.startsWith('MM\\0*')) return 'tiff';\n\tif (/^(?:\\xEF\\xBB\\xBF)?[\\t\\n\\r ]*</.test(input.subarray(0, 1024).toString('latin1')))\n\t\treturn 'svg';\n\treturn null;\n}\n\n/**\n * Refuses an SVG that could draw slowly, or pull in one that does: a `data:` URL\n * (librsvg follows it to another SVG or stylesheet) or an entity (which can spell\n * anything). librsvg decodes character references and CSS escapes, and joins\n * `<style>` text across comments and child elements, so the checks read the text\n * the same way.\n */\nfunction checkSvg(input: Buffer): void {\n\tconst refuse = (why: string) => new ProviderError(`SVG ${why}`, 422);\n\tif (input.length > SVG_MAX_BYTES) throw refuse(`is larger than ${SVG_MAX_BYTES / 1024} KB`);\n\tconst text = input.toString('latin1');\n\t// A NUL byte means UTF-16 or similar, where markup is not spelled in ASCII.\n\tif (input.includes(0) || !SVG_ENCODINGS.has(declaredEncoding(text))) {\n\t\tthrow refuse('must be UTF-8');\n\t}\n\tif (/<!ENTITY/i.test(text)) throw refuse('may not declare entities');\n\tlet elements = 0;\n\tfor (const _ of text.matchAll(/<[A-Za-z_:]/g)) {\n\t\tif (++elements > SVG_MAX_ELEMENTS) throw refuse(`has more than ${SVG_MAX_ELEMENTS} elements`);\n\t}\n\tfor (const seen of [unescapeSvg(text), unescapeSvg(textContent(text))]) {\n\t\tif (/filter/i.test(seen) || /<(?:[\\w.-]+:)?fe[A-Z]/.test(seen)) {\n\t\t\tthrow refuse('filters are not accepted');\n\t\t}\n\t\tif (/<(?:[\\w.-]+:)?use\\b/.test(seen) || /mask|marker|dasharray/i.test(seen)) {\n\t\t\tthrow refuse('<use>, masks, markers and dash patterns are not accepted');\n\t\t}\n\t\t// A URL parser drops tabs and newlines, so `da	ta:` is `data:`.\n\t\tif (/d[\\t\\n\\r]*a[\\t\\n\\r]*t[\\t\\n\\r]*a[\\t\\n\\r]*:/i.test(seen)) {\n\t\t\tthrow refuse('may not embed data: URLs');\n\t\t}\n\t}\n}\n\nfunction declaredEncoding(text: string): string {\n\tconst decl = /^(?:\\xEF\\xBB\\xBF)?<\\?xml[^>]*\\bencoding\\s*=\\s*[\"']([^\"']*)[\"']/.exec(text);\n\treturn decl ? decl[1].toLowerCase() : 'utf-8';\n}\n\nfunction unescapeSvg(text: string): string {\n\treturn text\n\t\t.replace(/&#(?:x([0-9a-f]+)|(\\d+));/gi, (_, hex: string | undefined, dec: string | undefined) =>\n\t\t\tcodePoint(hex ? parseInt(hex, 16) : Number(dec))\n\t\t)\n\t\t.replace(\n\t\t\t/\\\\(?:([0-9a-f]{1,6})[\\t\\n\\r ]?|([^\\n]))/gi,\n\t\t\t(_, hex: string | undefined, ch: string) => (hex ? codePoint(parseInt(hex, 16)) : ch)\n\t\t);\n}\n\nfunction codePoint(n: number): string {\n\treturn n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : '';\n}\n\n/** Character data only: comments, tags and processing instructions dropped, CDATA kept. */\nfunction textContent(text: string): string {\n\tlet out = '';\n\tlet i = 0;\n\t// indexOf, not a regex: an unterminated `<!--` would make a lazy regex quadratic.\n\twhile (i < text.length) {\n\t\tif (text.startsWith('<!--', i)) {\n\t\t\tconst end = text.indexOf('-->', i + 4);\n\t\t\ti = end < 0 ? text.length : end + 3;\n\t\t} else if (text.startsWith('<![CDATA[', i)) {\n\t\t\tconst end = text.indexOf(']]>', i + 9);\n\t\t\tout += text.slice(i + 9, end < 0 ? text.length : end);\n\t\t\ti = end < 0 ? text.length : end + 3;\n\t\t} else if (text[i] === '<') {\n\t\t\tconst end = text.indexOf('>', i + 1);\n\t\t\ti = end < 0 ? text.length : end + 1;\n\t\t} else {\n\t\t\tconst end = text.indexOf('<', i);\n\t\t\tout += text.slice(i, end < 0 ? text.length : end);\n\t\t\ti = end < 0 ? text.length : end;\n\t\t}\n\t}\n\treturn out;\n}\n\nasync function rasterize(sharp: SharpFn, input: Buffer, format: ImageFormat): Promise<Buffer> {\n\ttry {\n\t\t// Unlimited here: this only reads the header, and sharp's own limit would hide\n\t\t// the reason from the checks below.\n\t\tconst header = sharp(input, { limitInputPixels: false });\n\t\tconst meta = await header.metadata();\n\t\tif (meta.format !== format) {\n\t\t\tthrow new ProviderError(`Unsupported image format: ${meta.format}`, 422);\n\t\t}\n\t\tconst { width = 0, height = 0 } = meta;\n\t\tif (width > MAX_INPUT_SIDE || height > MAX_INPUT_SIDE) {\n\t\t\tthrow new ProviderError(`Image is more than ${MAX_INPUT_SIDE} pixels on a side`, 422);\n\t\t}\n\t\tif (width * height > MAX_INPUT_PIXELS) {\n\t\t\tthrow new ProviderError('Image has too many pixels', 422);\n\t\t}\n\t\treturn await sharp(input, { limitInputPixels: MAX_INPUT_PIXELS })\n\t\t\t.autoOrient()\n\t\t\t.resize({\n\t\t\t\twidth: IMAGE_MAX_WIDTH,\n\t\t\t\theight: IMAGE_MAX_WIDTH,\n\t\t\t\tfit: 'inside',\n\t\t\t\twithoutEnlargement: true\n\t\t\t})\n\t\t\t.webp({ quality: IMAGE_WEBP_QUALITY })\n\t\t\t.timeout({ seconds: TRANSCODE_TIMEOUT_SECONDS })\n\t\t\t.toBuffer();\n\t} catch (err) {\n\t\tif (err instanceof ProviderError) throw err;\n\t\t// libvips words it \"timeout: 40% complete\".\n\t\tif (err instanceof Error && /^timeout:/m.test(err.message)) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`The image took more than ${TRANSCODE_TIMEOUT_SECONDS} seconds to process`,\n\t\t\t\t422\n\t\t\t);\n\t\t}\n\t\tthrow new ProviderError('The image could not be read', 422);\n\t}\n}\n\nlet activeTranscodes = 0;\nconst waitingTranscodes: (() => void)[] = [];\n\n/**\n * Runs `fn` when a slot is free. A finishing transcode hands its slot straight to\n * the next. Throws `ProviderError(503)` when the queue is full or the wait runs out.\n */\nexport async function withTranscodeSlot<T>(fn: () => Promise<T>): Promise<T> {\n\tif (activeTranscodes < MAX_CONCURRENT_TRANSCODES) {\n\t\tactiveTranscodes += 1;\n\t} else {\n\t\tawait waitForSlot();\n\t}\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\tconst next = waitingTranscodes.shift();\n\t\tif (next) next();\n\t\telse activeTranscodes -= 1;\n\t}\n}\n\nfunction waitForSlot(): Promise<void> {\n\tconst busy = () =>\n\t\tnew ProviderError('Too many images are being processed. Try again shortly.', 503);\n\tif (waitingTranscodes.length >= MAX_WAITING_TRANSCODES) return Promise.reject(busy());\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\twaitingTranscodes.splice(waitingTranscodes.indexOf(start), 1);\n\t\t\treject(busy());\n\t\t}, TRANSCODE_WAIT_MS);\n\t\tconst start = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve();\n\t\t};\n\t\twaitingTranscodes.push(start);\n\t});\n}\n\ntype SharpFn = typeof import('sharp').default;\n// Not a literal: a browser build of the root barrel would try to resolve it.\nconst SHARP_MODULE = 'sharp';\nlet cachedSharp: SharpFn | null = null;\n\nasync function loadSharp(): Promise<SharpFn> {\n\tif (cachedSharp) return cachedSharp;\n\ttry {\n\t\tconst mod = (await import(/* @vite-ignore */ SHARP_MODULE)) as unknown as { default: SharpFn };\n\t\t// A bundler can hand back the CommonJS export itself rather than a namespace.\n\t\tcachedSharp = mod.default ?? (mod as unknown as SharpFn);\n\t\treturn cachedSharp;\n\t} catch (err) {\n\t\tthrow new Error(\n\t\t\t'Image transcoding requires `sharp` to be installed. Add it as a dependency in your provider package.',\n\t\t\t{ cause: err }\n\t\t);\n\t}\n}\n","import { ALL_ORG_ASSET_KINDS } from '../organizations/schemas.js';\nimport { UUID_REGEX } from '../definitions/schemas.js';\nimport { SAFE_SEGMENT } from './safeKey.js';\n\n/**\n * How a stored asset is allowed to be read. A property of the asset *class*\n * (its path prefix), never of the individual file — a new asset type is one\n * entry in {@link ASSET_CLASSES} rather than a new route.\n *\n * - `public` — anyone, including logged-out visitors (branding: logo, favicon).\n * - `project` — members of the owning project only; route resolves the\n * definition guid to its project (cover images, per-definition blobs).\n */\nexport type AssetVisibility = 'public' | 'project';\n\n/**\n * What scope id the route must authorize against. `none` for public assets\n * (no scope to check); `project` carries the guid extracted from the path.\n */\nexport type AssetScope = 'none' | 'project';\n\nexport interface AssetClass {\n\t/** Stable identifier — for logging and tests, not user-facing. */\n\treadonly id: string;\n\treadonly visibility: AssetVisibility;\n\treadonly scope: AssetScope;\n\t/**\n\t * Anchored matcher for this class's storage paths. Capture group 1 (when\n\t * present) is the scope id the route authorizes against.\n\t */\n\treadonly pattern: RegExp;\n}\n\nexport interface AssetMatch {\n\treadonly class: AssetClass;\n\t/** The scope id from the path, or null for `scope: 'none'` classes. */\n\treadonly scopeId: string | null;\n}\n\n// Built from the schema enum so a new branding kind extends this pattern automatically.\nconst BRANDING_KINDS = ALL_ORG_ASSET_KINDS.join('|');\n\nconst GUID = UUID_REGEX.source.slice(1, -1);\n\n/**\n * The closed registry of servable asset classes. Patterns are mutually\n * exclusive by prefix, order doesn't matter. Anything matching no class is\n * unservable (the route 404s) — default-deny, so a new blob type is opt-in.\n */\nexport const ASSET_CLASSES: readonly AssetClass[] = [\n\t{\n\t\tid: 'org-branding',\n\t\tvisibility: 'public',\n\t\tscope: 'none',\n\t\tpattern: new RegExp(\n\t\t\tString.raw`^orgs\\/(${SAFE_SEGMENT})\\/branding\\/(?:${BRANDING_KINDS})\\.webp$`\n\t\t)\n\t},\n\t{\n\t\tid: 'definition-cover',\n\t\tvisibility: 'project',\n\t\tscope: 'project',\n\t\t// `put` transcodes every cover and `definitionPaths.image` names it, so this is\n\t\t// the only cover that can exist.\n\t\tpattern: new RegExp(String.raw`^definitions\\/(${GUID})\\/cover\\.webp$`, 'i')\n\t}\n];\n\n/**\n * Rejects traversal, empty, or backslash segments before a path can match a\n * class. The permissive segment alphabet (`[A-Za-z0-9._-]+`) admits a bare\n * `.` or `..` as a whole segment, which would otherwise let\n * `orgs/../branding/logo.webp` classify as public branding with `..`\n * captured as the orgId. Mirrors `assertSafeKey` on the write side, so a path\n * that can't be written can't be read either.\n */\nfunction hasUnsafeSegment(storagePath: string): boolean {\n\tif (storagePath.includes('\\\\')) return true;\n\tfor (const segment of storagePath.split('/')) {\n\t\tif (segment === '' || segment === '.' || segment === '..') return true;\n\t}\n\treturn false;\n}\n\n/**\n * Classifies a storage path into its asset class and scope id, or null when\n * no class matches (or the path is unsafe). `getPublicUrl` and the serving\n * route both consult this so URL generation and authorization never drift\n * apart.\n *\n * `scopeId` is null for `scope: 'none'` classes even when the pattern\n * captures an id (e.g. `org-branding` captures orgId but is public).\n */\nexport function classifyAssetPath(storagePath: string): AssetMatch | null {\n\tif (hasUnsafeSegment(storagePath)) return null;\n\tfor (const cls of ASSET_CLASSES) {\n\t\tconst m = cls.pattern.exec(storagePath);\n\t\tif (!m) continue;\n\t\treturn { class: cls, scopeId: cls.scope === 'none' ? null : (m[1] ?? null) };\n\t}\n\treturn null;\n}\n","/**\n * Appends a cache-busting token to a stored-asset URL.\n *\n * `IStorageProvider.put` upserts, so a re-upload keeps the same storage path\n * and public URL — a browser/CDN caching the old bytes under that URL keeps\n * serving them past the TTL, which reads as \"the replace didn't work.\"\n * Appending a token that only changes with the content gives each version a\n * distinct URL, forcing a refetch, while unchanged assets stay cached.\n *\n * Generic over asset kind — pass whatever tracks the blob's version (content\n * hash, `updatedAt`, a counter). The serving route ignores the query string\n * (SvelteKit's `[...path]` param never includes it), so this needs no route\n * support.\n *\n * Empty/whitespace tokens return the URL unchanged, so a missing token\n * degrades to \"no cache-bust\" rather than `?v=`.\n */\nexport function withCacheBust(url: string, token: string | number | undefined | null): string {\n\tif (token === undefined || token === null) return url;\n\tconst value = String(token).trim();\n\tif (value === '') return url;\n\tconst hash = url.indexOf('#');\n\tconst base = hash === -1 ? url : url.slice(0, hash);\n\tconst fragment = hash === -1 ? '' : url.slice(hash);\n\tconst sep = base.includes('?') ? '&' : '?';\n\treturn `${base}${sep}v=${encodeURIComponent(value)}${fragment}`;\n}\n","/** How many entries `recordRun` keeps per user. */\nexport const MAX_RECENT_RUNS = 20;\n\nexport interface RecentRun {\n\tdefinitionId: string;\n\trunId: string;\n\tdefinitionName: string;\n\ttimestamp: string;\n}\n\n/** Mutable per-user profile state, owned by `IUserProfileStore`. */\nexport interface UserProfile {\n\tuserId: string;\n\tdisplayName?: string;\n\t/** Definition GUIDs pinned by this user. */\n\tstarredDefinitions: string[];\n\t/** Last N solve runs, newest first. Capped by the adapter. */\n\trecentRuns: RecentRun[];\n}\n\nexport function emptyProfile(userId: string): UserProfile {\n\treturn { userId, starredDefinitions: [], recentRuns: [] };\n}\n","import { assertNotShareContext, hasPermission, type RequestContext } from '../context.js';\nimport { ProviderError } from '../errors/index.js';\n\n/**\n * For provider authors: may `ctx` read or change `userId`'s profile? Throws\n * `ProviderError(403)` if not.\n */\nexport function assertCanAccessProfile(ctx: RequestContext, userId: string): void {\n\tassertNotShareContext(ctx, 'access user profiles');\n\tif (ctx.userId === userId || hasPermission(ctx, 'instance_admin')) return;\n\tthrow new ProviderError('Forbidden: cannot access another user’s profile', 403);\n}\n","import type { RequestContext } from '../context.js';\n\n/**\n * Audit-field stamping helpers. Every mutable entity carries `createdAt` /\n * `createdBy` / `updatedAt` / `updatedBy` / `deletedAt`.\n *\n * `createdAt` / `createdBy` are stamped by the consumer when constructing\n * the record. `updatedAt` / `updatedBy` and `deletedAt` are stamped by\n * stores on every mutation.\n *\n * `fallbackActor` is used when `ctx.userId` is empty (system contexts) —\n * pass the record's prior `updatedBy` (or `ownerId` / `createdBy` if unset).\n */\n\nconst nowIso = (): string => new Date().toISOString();\n\nexport interface AuditUpdate {\n\tupdatedAt: string;\n\tupdatedBy: string;\n}\n\nexport function auditUpdate(\n\tctx: RequestContext,\n\tfallbackActor: string | null | undefined\n): AuditUpdate {\n\treturn {\n\t\tupdatedAt: nowIso(),\n\t\tupdatedBy: ctx.userId || fallbackActor || ''\n\t};\n}\n\nexport interface AuditSoftDelete extends AuditUpdate {\n\tdeletedAt: string;\n}\n\nexport function auditSoftDelete(\n\tctx: RequestContext,\n\tfallbackActor: string | null | undefined\n): AuditSoftDelete {\n\tconst now = nowIso();\n\treturn {\n\t\tdeletedAt: now,\n\t\tupdatedAt: now,\n\t\tupdatedBy: ctx.userId || fallbackActor || ''\n\t};\n}\n","import type { RequestContext } from '../context.js';\n\n/**\n * Why a solve did not produce a usable result. `ok` means the solve completed\n * (it may still carry Grasshopper runtime errors — see `errorCount`). Each\n * kind mirrors an HTTP status the compute route already distinguishes.\n */\nexport type SolveFailureKind =\n\t/** Solve completed; the response was returned to the client. */\n\t| 'ok'\n\t/** Scheduler deadline exceeded (HTTP 504). */\n\t| 'timeout'\n\t/** Client disconnected mid-solve; the request signal aborted (HTTP 499). */\n\t| 'client_abort'\n\t/** Rejected by the per-key rate limiter before solving (HTTP 429). */\n\t| 'rate_limited'\n\t/** Share-link solve cap reached before solving (HTTP 429). */\n\t| 'share_cap'\n\t/** Result exceeded the response size limit (HTTP 413). */\n\t| 'too_large'\n\t/** The compute server refused the request body as too large, before solving (HTTP 413). */\n\t| 'request_too_large'\n\t/**\n\t * Rejected by scheduler backpressure — the per-server queue was full, or the\n\t * solve sat queued past its wait deadline, so it never executed\n\t * (HTTP 503 + Retry-After). Distinct from `compute_error`: no compute ran.\n\t */\n\t| 'shed'\n\t/** Compute server unreachable or the solve threw for any other reason. */\n\t| 'compute_error';\n\n/**\n * One solve's timing and outcome, recorded once per attempt — including\n * attempts rejected before `scheduler.solve()` runs (rate limit, share cap).\n */\nexport interface SolveMetric {\n\t/** Definition the solve ran against. `local:<guid>` or a remote URL. */\n\tdefinitionUrl: string;\n\t/** Local definition id (the `local:` guid), or null for remote-URL solves. */\n\tdefinitionId: string | null;\n\t/** Exact version solved, or null for remote-URL solves and attempts rejected before the version resolved. */\n\tversionId: string | null;\n\t/** Channel solved, mirroring the compute request. */\n\tchannel: 'live' | 'draft';\n\t/** Org whose compute pool served the solve, or null for remote definitions. */\n\torgId: string | null;\n\t/**\n\t * Wall time around the Rhino.Compute solve call only — excludes definition\n\t * loading, auth, schema work, and result serialization. 0 if never started.\n\t */\n\tdurationMs: number;\n\t/** Must equal `failureKind === 'ok'`; readers should prefer `failureKind`. */\n\tok: boolean;\n\t/** Why the solve did not return a result; `'ok'` when it did. */\n\tfailureKind: SolveFailureKind;\n\t/**\n\t * Grasshopper runtime errors in the solve response. A solve can be `ok`\n\t * yet still report component-level errors. 0 when no response returned.\n\t */\n\terrorCount: number;\n\t/** Grasshopper runtime warnings in the solve response. */\n\twarningCount: number;\n}\n\n/**\n * Sink for per-solve timing telemetry, called once per attempt after the\n * solve resolves or rejects.\n *\n * MUST NOT throw — recording is best-effort and sits on the hot path of every\n * solve. Implementations catch and log their own failures.\n */\nexport interface ISolveMetricSink {\n\trecord(ctx: RequestContext, metric: SolveMetric): Promise<void>;\n}\n\n/** Default `ISolveMetricSink` — discards every metric. Used when `SelvaConfig.solveMetrics` is omitted. */\nexport class NoopSolveMetricSink implements ISolveMetricSink {\n\tasync record(_ctx: RequestContext, _metric: SolveMetric): Promise<void> {}\n}\n","// Configurable provider wiring — the reusable core of an app's composition\n// root.\n//\n// Provider IMPLEMENTATIONS are not bundled: the caller passes a\n// `ProviderRegistry` mapping choice names (the `SELVA_*_PROVIDER` env values)\n// to `fromEnv`-style factories. That keeps this package free of dependencies on\n// `@selvajs/local-provider` / `@selvajs/supabase-provider` — a consuming app\n// registers exactly the providers it ships.\n//\n// Two wiring modes:\n//\n// Default — providers picked from env vars (SELVA_AUTH_PROVIDER etc.) via the\n// registry. New deployments need only a .env file.\n//\n// Override — `configPath` points at an external `selva.config.js` (absolute\n// or CWD-relative), loaded dynamically at boot, replacing the env-driven\n// wiring entirely. It must be an actual `.js` file — there's no TS compiler\n// at runtime.\n\nimport { pathToFileURL } from 'node:url';\nimport { resolve as resolvePath } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport type {\n\tIAuthProvider,\n\tIDataProvider,\n\tIStorageProvider,\n\tISolveMetricSink,\n\tSelvaBranding,\n\tSelvaConfig,\n\tSelvaConfigFactory,\n\tSelvaFlags,\n\tTenancyMode\n} from '@selvajs/platform';\nimport { isFlagEnabled, NoopSolveMetricSink, NoopLogger, type ILogger } from '@selvajs/platform';\nimport { readBool, type EnvRecord } from '../compute/limits.js';\n\nexport type ProviderFactory<T> = (env: EnvRecord) => T;\n\n/** Keyed by the lowercased `SELVA_{AUTH,DATA,STORAGE}_PROVIDER` value. */\nexport interface ProviderRegistry {\n\tauth: Record<string, ProviderFactory<IAuthProvider>>;\n\tdata: Record<string, ProviderFactory<IDataProvider>>;\n\tstorage: Record<string, ProviderFactory<IStorageProvider>>;\n}\n\nexport interface CreateSelvaProvidersOptions {\n\tregistry: ProviderRegistry;\n\t/** Fallback choice per slot when the env var is unset. Default: `'local'`. */\n\tdefaults?: Partial<Record<'auth' | 'data' | 'storage', string>>;\n\t/**\n\t * Override module (absolute or CWD-relative); its default export is a\n\t * `SelvaConfig` or a factory.\n\t */\n\tconfigPath?: string;\n\t/**\n\t * Boot-summary sink, called once on first `resolve()` — for callers that want\n\t * the rendered string. Default: none, and the summary goes to `logger`\n\t * instead, so this library never writes to stdout unbidden.\n\t */\n\tonBoot?: (summary: string) => void;\n\t/**\n\t * Receives the boot summary as fields when `onBoot` is unset. Defaults to\n\t * `NoopLogger`.\n\t */\n\tlogger?: ILogger;\n}\n\nexport interface SelvaProviderRuntime {\n\t/**\n\t * Memoized wiring. The first call instantiates providers from env and throws\n\t * if a required secret is missing, or if `ENABLE_PLATFORM_PROJECTS` is on\n\t * over a grant store marked `unsupported` — never call it at build time.\n\t */\n\tresolve(): SelvaConfig;\n\t/** Defaults to `'single'` when the config omits it. */\n\ttenancy(): TenancyMode;\n\t/** Every field defaulted, so the UI never null-checks. */\n\tbranding(): Required<SelvaBranding>;\n\t/** Omitted flags resolve to false. */\n\tflag(name: keyof SelvaFlags): boolean;\n\t/** `NoopSolveMetricSink` when the config omits one. */\n\tsolveMetricSink(): ISolveMetricSink;\n}\n\n// Every SelvaFlags key, read from `SELVA_FLAG_<KEY>`. The `satisfies` plus the\n// exhaustiveness check below make adding a platform flag without listing it\n// here a compile error.\nconst FLAG_KEYS = [\n\t'ALLOW_CROSS_ORG_PUBLIC',\n\t'ALLOW_ORG_COMPUTE_OVERRIDE',\n\t'ALLOW_ORG_CREATION',\n\t'ENABLE_PLATFORM_PROJECTS',\n\t'ENABLE_SHARING'\n] as const satisfies readonly (keyof SelvaFlags)[];\n\ntype AllFlagsListed =\n\tExclude<keyof SelvaFlags, (typeof FLAG_KEYS)[number]> extends never ? true : never;\n\nconst _allFlagsListed: AllFlagsListed = true;\n\nfunction pick<T>(\n\tenv: EnvRecord,\n\tenvVar: string,\n\tslot: Record<string, ProviderFactory<T>>,\n\tfallback: string\n): T {\n\tconst choice = (env[envVar] ?? fallback).toLowerCase();\n\tconst factory = slot[choice];\n\tif (!factory) {\n\t\tthrow new Error(`Unknown ${envVar}=\"${choice}\". Expected: ${Object.keys(slot).join(' | ')}.`);\n\t}\n\treturn factory(env);\n}\n\nfunction pickTenancy(env: EnvRecord): TenancyMode {\n\tconst choice = (env.SELVA_TENANCY ?? 'single').toLowerCase();\n\tif (choice !== 'single' && choice !== 'multi') {\n\t\tthrow new Error(`Unknown SELVA_TENANCY=\"${choice}\". Expected: single | multi.`);\n\t}\n\treturn choice;\n}\n\n/**\n * Supabase's data provider carries a `solveMetrics` sink built from its own\n * client bundle — reuse it so timings persist without a second client. Backends\n * with no metrics table return undefined, and `solveMetricSink()` falls back to\n * `NoopSolveMetricSink`.\n */\nfunction pickSolveMetrics(data: IDataProvider): ISolveMetricSink | undefined {\n\tconst candidate = (data as { solveMetrics?: unknown }).solveMetrics;\n\tif (candidate && typeof (candidate as { record?: unknown }).record === 'function') {\n\t\treturn candidate as ISolveMetricSink;\n\t}\n\treturn undefined;\n}\n\nfunction buildDefaultFactory(options: CreateSelvaProvidersOptions): SelvaConfigFactory {\n\tconst { registry, defaults } = options;\n\treturn (env) => {\n\t\tconst data = pick(env, 'SELVA_DATA_PROVIDER', registry.data, defaults?.data ?? 'local');\n\t\treturn {\n\t\t\ttenancy: pickTenancy(env),\n\t\t\tflags: Object.fromEntries(\n\t\t\t\tFLAG_KEYS.map((key) => [key, readBool(env, `SELVA_FLAG_${key}`, false)])\n\t\t\t),\n\t\t\tbranding: {\n\t\t\t\tname: env.SELVA_BRAND_NAME,\n\t\t\t\tcopyrightName: env.SELVA_BRAND_COPYRIGHT_NAME,\n\t\t\t\ttagline: env.SELVA_BRAND_TAGLINE,\n\t\t\t\tdescription: env.SELVA_BRAND_DESCRIPTION\n\t\t\t},\n\t\t\tauth: pick(env, 'SELVA_AUTH_PROVIDER', registry.auth, defaults?.auth ?? 'local'),\n\t\t\tdata,\n\t\t\tstorage: pick(env, 'SELVA_STORAGE_PROVIDER', registry.storage, defaults?.storage ?? 'local'),\n\t\t\tsolveMetrics: pickSolveMetrics(data)\n\t\t};\n\t};\n}\n\nasync function loadConfigSource(\n\toptions: CreateSelvaProvidersOptions\n): Promise<SelvaConfig | SelvaConfigFactory> {\n\tif (!options.configPath) {\n\t\treturn buildDefaultFactory(options);\n\t}\n\tconst abs = resolvePath(process.cwd(), options.configPath);\n\tif (!existsSync(abs)) {\n\t\tthrow new Error(\n\t\t\t`Config override path ${options.configPath} resolved to ${abs} which does not exist.`\n\t\t);\n\t}\n\t// @vite-ignore: a bundler must not pre-resolve this specifier at build time.\n\t// pathToFileURL keeps Windows absolute paths valid as ESM specifiers.\n\tconst mod = (await import(/* @vite-ignore */ pathToFileURL(abs).href)) as {\n\t\tdefault: SelvaConfig | SelvaConfigFactory;\n\t};\n\treturn mod.default;\n}\n\n/**\n * Loading the config source (default factory, or the `configPath` module) is\n * cheap and secret-free. The factory is deliberately NOT invoked here: that\n * runs the registry's `fromEnv` factories, which validate required secrets, so\n * calling it at import time would make merely building the app require a full\n * runtime env. Providers are instantiated on the first `resolve()`.\n */\nexport async function createSelvaProviders(\n\tenv: EnvRecord,\n\toptions: CreateSelvaProvidersOptions\n): Promise<SelvaProviderRuntime> {\n\tconst raw = await loadConfigSource(options);\n\tconst logger = options.logger ?? new NoopLogger();\n\n\tlet config: SelvaConfig | undefined;\n\tlet solveMetricSink: ISolveMetricSink | undefined;\n\n\tfunction resolve(): SelvaConfig {\n\t\tif (config) return config;\n\t\tconst candidate = typeof raw === 'function' ? raw(env) : raw;\n\t\tif (\n\t\t\tisFlagEnabled(candidate, 'ENABLE_PLATFORM_PROJECTS') &&\n\t\t\tcandidate.data.platformProjectGrants.unsupported\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`ENABLE_PLATFORM_PROJECTS is on, but ${candidate.data.constructor.name} cannot store ` +\n\t\t\t\t\t'platform-project grants. Turn SELVA_FLAG_ENABLE_PLATFORM_PROJECTS off.'\n\t\t\t);\n\t\t}\n\t\tconfig = candidate;\n\n\t\t// Boot summary so operators can confirm what got wired without grepping\n\t\t// env vars. Auth exposes a `name` field; data/storage adapters don't, so\n\t\t// their names come from the constructor.\n\t\tconst wiring = {\n\t\t\tcomponent: 'selva',\n\t\t\tauth: config.auth.name,\n\t\t\tdata: config.data.constructor.name,\n\t\t\tstorage: config.storage.constructor.name,\n\t\t\ttenancy: config.tenancy ?? 'single',\n\t\t\t...(options.configPath ? { configPath: options.configPath } : {})\n\t\t};\n\n\t\tif (options.onBoot) {\n\t\t\toptions.onBoot(\n\t\t\t\t`[selva] providers wired: ` +\n\t\t\t\t\t`auth=${wiring.auth} ` +\n\t\t\t\t\t`data=${wiring.data} ` +\n\t\t\t\t\t`storage=${wiring.storage} ` +\n\t\t\t\t\t`tenancy=${wiring.tenancy}` +\n\t\t\t\t\t(options.configPath ? ` config=${options.configPath}` : '')\n\t\t\t);\n\t\t} else {\n\t\t\tlogger.info('Providers wired', wiring);\n\t\t}\n\n\t\treturn config;\n\t}\n\n\treturn {\n\t\tresolve,\n\t\ttenancy: () => resolve().tenancy ?? 'single',\n\t\tbranding: () => {\n\t\t\tconst brand = resolve().branding ?? {};\n\t\t\tconst name = brand.name?.trim() || 'Selva';\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tcopyrightName: brand.copyrightName?.trim() || name,\n\t\t\t\ttagline: brand.tagline?.trim() || '',\n\t\t\t\tdescription:\n\t\t\t\t\tbrand.description?.trim() ||\n\t\t\t\t\t`Build and deploy interactive web applications powered by Grasshopper definitions with ${name}.`\n\t\t\t};\n\t\t},\n\t\tflag: (name) => isFlagEnabled(resolve(), name),\n\t\tsolveMetricSink: () => {\n\t\t\tif (!solveMetricSink) {\n\t\t\t\tsolveMetricSink = resolve().solveMetrics ?? new NoopSolveMetricSink();\n\t\t\t}\n\t\t\treturn solveMetricSink;\n\t\t}\n\t};\n}\n","import { timingSafeEqual, createHmac } from 'node:crypto';\n\nconst DEFAULT_MAX_AGE_MS = 8 * 60 * 60 * 1000;\n\n/**\n * Token format: base64url(userId + ':' + expiry) + '.' + hmac(payload)\n *\n * The userId is embedded so verifyToken can look up the live user record\n * (and therefore always reflect the current permissions, not stale ones\n * baked into the token at login time).\n */\nexport function signHmacToken(\n\tsecret: string,\n\tuserId: string,\n\tmaxAgeMs = DEFAULT_MAX_AGE_MS\n): string {\n\tconst expiry = Date.now() + maxAgeMs;\n\tconst payload = Buffer.from(`${userId}:${expiry}`).toString('base64url');\n\tconst sig = createHmac('sha256', secret).update(payload).digest('base64url');\n\treturn `${payload}.${sig}`;\n}\n\nexport interface HmacTokenPayload {\n\tuserId: string;\n\tvalid: boolean;\n}\n\n/**\n * Verify an HMAC token. Returns the userId if valid and unexpired, or\n * { valid: false } if the signature is wrong or the token has expired.\n */\nexport function verifyHmacToken(token: string, secret: string): HmacTokenPayload {\n\tconst dot = token.lastIndexOf('.');\n\tif (dot === -1) return { userId: '', valid: false };\n\n\tconst payload = token.slice(0, dot);\n\tconst sig = token.slice(dot + 1);\n\tconst expectedSig = createHmac('sha256', secret).update(payload).digest('base64url');\n\n\tconst a = Buffer.from(sig);\n\tconst b = Buffer.from(expectedSig);\n\tif (a.length !== b.length || !timingSafeEqual(a, b)) return { userId: '', valid: false };\n\n\tconst decoded = Buffer.from(payload, 'base64url').toString();\n\tconst colon = decoded.lastIndexOf(':');\n\tif (colon === -1) return { userId: '', valid: false };\n\n\tconst userId = decoded.slice(0, colon);\n\tconst expiry = parseInt(decoded.slice(colon + 1), 10);\n\tif (!Number.isFinite(expiry) || Date.now() >= expiry) return { userId: '', valid: false };\n\n\treturn { userId, valid: true };\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { randomUUID } from 'node:crypto';\n\nconst fileQueues = new Map<string, Promise<unknown>>();\n\n/**\n * Runs a read-modify-write of `filePath` alone in this process, so two writers\n * can't both start from the same snapshot and lose one's change.\n */\nexport function withFileLock<T>(filePath: string, fn: () => Promise<T>): Promise<T> {\n\t// Chain onto the tail however the previous write settled, so one rejection\n\t// can't wedge the queue.\n\tconst next = (fileQueues.get(filePath) ?? Promise.resolve()).then(fn, fn);\n\tconst tail = next.catch(() => {});\n\tfileQueues.set(filePath, tail);\n\tvoid tail.then(() => {\n\t\tif (fileQueues.get(filePath) === tail) fileQueues.delete(filePath);\n\t});\n\treturn next;\n}\n\n/** Returns `fallback` if the file doesn't exist. Other errors propagate. */\nexport async function readJsonFile<T>(filePath: string, fallback: T): Promise<T> {\n\ttry {\n\t\tconst raw = await fs.readFile(filePath, 'utf-8');\n\t\treturn JSON.parse(raw) as T;\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === 'ENOENT') return fallback;\n\t\tthrow err;\n\t}\n}\n\nconst RENAME_RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);\n\n/**\n * `rename` over a file another handle has open fails on Windows with EPERM, EACCES or\n * EBUSY until that handle closes, so a write racing a read would fail. Readers here\n * close fast; retry briefly, as graceful-fs does. POSIX never hits these codes.\n */\nexport async function renameReplacing(from: string, to: string): Promise<void> {\n\tfor (let attempt = 0; ; attempt++) {\n\t\ttry {\n\t\t\treturn await fs.rename(from, to);\n\t\t} catch (err) {\n\t\t\tconst code = (err as NodeJS.ErrnoException).code;\n\t\t\tif (attempt >= 20 || !code || !RENAME_RETRY_CODES.has(code)) throw err;\n\t\t\tawait new Promise((r) => setTimeout(r, Math.min(10 * (attempt + 1), 100)));\n\t\t}\n\t}\n}\n\n/**\n * Writes to a sibling temp file, then renames into place, so a crash mid-write\n * can't corrupt the target. The temp name is random per call: a shared name would\n * let one writer's rename pull the file out from under another. A read-modify-write\n * caller still needs {@link withFileLock}.\n *\n * Owner-only permissions are not optional here: this helper is the sole writer\n * for `auth-users.json` (email addresses + PBKDF2 password hashes) and\n * `compute.config.json`. Under a default umask those land 0644, and any other\n * local user or co-tenant service on the host can copy the hashes and crack\n * them offline. The mode goes on the temp file, not the target — `rename`\n * keeps the temp file's bits, so a post-rename `chmod` would leave a readable\n * window. No-op on Windows.\n */\nexport async function writeJsonFile<T>(filePath: string, data: T): Promise<void> {\n\tawait fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });\n\tconst tmp = `${filePath}.${randomUUID()}.tmp`;\n\ttry {\n\t\tawait fs.writeFile(tmp, JSON.stringify(data, null, '\\t'), { encoding: 'utf-8', mode: 0o600 });\n\t\tawait renameReplacing(tmp, filePath);\n\t} catch (err) {\n\t\tawait fs.rm(tmp, { force: true }).catch(() => {});\n\t\tthrow err;\n\t}\n}\n\n/**\n * A JSON file read once and kept in memory, where the provider is the sole writer\n * in a single process. Callers mutate what `get` returns, then pass it to `write`.\n */\nexport class CachedJsonFile<T> {\n\tprivate cache: T | null = null;\n\tprivate loading: Promise<T> | null = null;\n\n\tconstructor(\n\t\treadonly filePath: string,\n\t\tprivate readonly fallback: () => T\n\t) {}\n\n\t/** Concurrent first callers share one read, so they mutate the same object. */\n\tasync get(): Promise<T> {\n\t\tif (this.cache) return this.cache;\n\t\tthis.loading ??= readJsonFile<T>(this.filePath, this.fallback())\n\t\t\t.then((data) => {\n\t\t\t\tthis.cache = data;\n\t\t\t\treturn data;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tthis.loading = null;\n\t\t\t});\n\t\treturn this.loading;\n\t}\n\n\t/**\n\t * Writes run one at a time and stringify when their turn comes, so the newest\n\t * state lands last. A failed write drops the cache: it holds a change the disk\n\t * never took.\n\t */\n\tasync write(data: T): Promise<void> {\n\t\tthis.cache = data;\n\t\ttry {\n\t\t\tawait withFileLock(this.filePath, () => writeJsonFile(this.filePath, data));\n\t\t} catch (err) {\n\t\t\tthis.cache = null;\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n","import * as crypto from 'node:crypto';\nimport { randomUUID } from 'node:crypto';\nimport { ProviderError } from '@selvajs/platform';\nimport { CachedJsonFile } from '../data/fsJson.js';\n\n/**\n * Identity-only on-disk shape. Per-user app state (permissions, profile,\n * starred definitions, recent runs) lives in `user-data.json`, owned by\n * `LocalDataProvider`. The split lets `LocalAuthProvider` pair with any data\n * provider, and any auth provider pair with `LocalDataProvider`, without one\n * stepping on the other.\n */\nexport interface StoredAuthUser {\n\tid: string;\n\temail: string;\n\t/**\n\t * \"pbkdf2:sha256:<iterations>:<salt>:<hash>\", binary values base64url encoded.\n\t * Null for OAuth-only users (allowlisted email, no password stored).\n\t */\n\tpasswordHash: string | null;\n\tcreatedAt: string; // ISO 8601\n\t/** ISO 8601, most recent successful login. */\n\tlastLoginAt?: string;\n\t/** True means the provider refuses to authenticate this user. */\n\tdisabled?: boolean;\n}\n\n/** Debounce window for lastLoginAt writes — skip if prior stamp is newer than this. */\nconst LAST_LOGIN_DEBOUNCE_MS = 60_000;\n\nexport interface AuthUsersFile {\n\tusers: StoredAuthUser[];\n}\n\n// ============================================================================\n// PBKDF2 password hashing\n// ============================================================================\nconst PBKDF2_ITERATIONS = 100_000;\nconst PBKDF2_KEYLEN = 32;\nconst PBKDF2_DIGEST = 'sha256';\n\nexport async function hashPassword(password: string): Promise<string> {\n\tconst salt = crypto.randomBytes(16).toString('base64url');\n\tconst hash = await new Promise<Buffer>((resolve, reject) =>\n\t\tcrypto.pbkdf2(password, salt, PBKDF2_ITERATIONS, PBKDF2_KEYLEN, PBKDF2_DIGEST, (err, key) =>\n\t\t\terr ? reject(err) : resolve(key)\n\t\t)\n\t);\n\treturn `pbkdf2:${PBKDF2_DIGEST}:${PBKDF2_ITERATIONS}:${salt}:${hash.toString('base64url')}`;\n}\n\nexport async function verifyPasswordHash(password: string, storedHash: string): Promise<boolean> {\n\tconst parts = storedHash.split(':');\n\tif (parts.length !== 5 || parts[0] !== 'pbkdf2') return false;\n\tconst [, digest, iterStr, salt, expectedHashB64] = parts;\n\tconst iterations = parseInt(iterStr, 10);\n\tif (!Number.isFinite(iterations) || iterations <= 0) return false;\n\n\tconst expected = Buffer.from(expectedHashB64, 'base64url');\n\tconst actual = await new Promise<Buffer>((resolve, reject) =>\n\t\tcrypto.pbkdf2(password, salt, iterations, PBKDF2_KEYLEN, digest, (err, key) =>\n\t\t\terr ? reject(err) : resolve(key)\n\t\t)\n\t);\n\n\tif (actual.length !== expected.length) return false;\n\treturn crypto.timingSafeEqual(actual, expected);\n}\n\n// ============================================================================\n// CRUD\n// ============================================================================\n// Fresh object per call — `readJsonFile` returns its fallback by reference\n// when the file is missing, so a shared singleton would let one test (or\n// one process write) mutate state visible to the next read.\nconst empty = (): AuthUsersFile => ({ users: [] });\n\nexport interface LocalAuthUserStore {\n\tfindByEmail(email: string): Promise<StoredAuthUser | null>;\n\tfindById(id: string): Promise<StoredAuthUser | null>;\n\tlistUsers(): Promise<Omit<StoredAuthUser, 'passwordHash'>[]>;\n\t/** password null = OAuth allowlist entry (no password stored) */\n\tcreateUser(email: string, password: string | null): Promise<StoredAuthUser>;\n\tsetDisabled(id: string, disabled: boolean): Promise<void>;\n\ttouchLastLogin(id: string): Promise<void>;\n\tdeleteUser(id: string): Promise<void>;\n}\n\nexport function createLocalAuthUserStore(usersFilePath: string): LocalAuthUserStore {\n\t// Load-once, write-through cache, same pattern as `LocalOrgStoreLoader`:\n\t// reading and parsing the whole file on every call is the hot-path cost,\n\t// since `auth-users.json` is read on every authenticated request. The\n\t// provider is the sole writer in single-process local mode, so the\n\t// in-memory copy stays authoritative — every mutation updates the cache and\n\t// persists via temp+rename. Concurrent first callers share one in-flight\n\t// load so writes stack on the same array.\n\tconst store = new CachedJsonFile<AuthUsersFile>(usersFilePath, empty);\n\tconst load = () => store.get();\n\tconst persist = (file: AuthUsersFile) => store.write(file);\n\n\treturn {\n\t\tasync findByEmail(email) {\n\t\t\tconst { users } = await load();\n\t\t\treturn users.find((u) => u.email.toLowerCase() === email.toLowerCase()) ?? null;\n\t\t},\n\n\t\tasync findById(id) {\n\t\t\tconst { users } = await load();\n\t\t\treturn users.find((u) => u.id === id) ?? null;\n\t\t},\n\n\t\tasync listUsers() {\n\t\t\tconst { users } = await load();\n\t\t\treturn users.map(({ passwordHash: _ph, ...rest }) => rest);\n\t\t},\n\n\t\tasync createUser(email, password) {\n\t\t\t// Hash first: nothing may await between the uniqueness check and the push, or\n\t\t\t// a double submit gets past the check twice.\n\t\t\tconst passwordHash = password !== null ? await hashPassword(password) : null;\n\t\t\tconst file = await load();\n\t\t\tif (file.users.some((u) => u.email.toLowerCase() === email.toLowerCase())) {\n\t\t\t\tthrow new ProviderError(`User with email \"${email}\" already exists`, 409);\n\t\t\t}\n\t\t\tconst user: StoredAuthUser = {\n\t\t\t\tid: randomUUID(),\n\t\t\t\temail,\n\t\t\t\tpasswordHash,\n\t\t\t\tcreatedAt: new Date().toISOString()\n\t\t\t};\n\t\t\tfile.users.push(user);\n\t\t\tawait persist(file);\n\t\t\treturn user;\n\t\t},\n\n\t\tasync setDisabled(id, disabled) {\n\t\t\tconst file = await load();\n\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\tif (!user) throw new ProviderError(`User \"${id}\" not found`, 404);\n\t\t\tuser.disabled = disabled;\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync touchLastLogin(id) {\n\t\t\tconst file = await load();\n\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\tif (!user) return;\n\t\t\tconst now = Date.now();\n\t\t\tif (user.lastLoginAt) {\n\t\t\t\tconst prev = Date.parse(user.lastLoginAt);\n\t\t\t\tif (Number.isFinite(prev) && now - prev < LAST_LOGIN_DEBOUNCE_MS) return;\n\t\t\t}\n\t\t\tuser.lastLoginAt = new Date(now).toISOString();\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync deleteUser(id) {\n\t\t\tconst file = await load();\n\t\t\tconst before = file.users.length;\n\t\t\tfile.users = file.users.filter((u) => u.id !== id);\n\t\t\tif (file.users.length === before) throw new ProviderError(`User \"${id}\" not found`, 404);\n\t\t\tawait persist(file);\n\t\t}\n\t};\n}\n","import {\n\tclampPageLimit,\n\tdecodeOffsetCursor,\n\tencodeOffsetCursor,\n\ttype ListOptions,\n\ttype DefinitionListOptions,\n\ttype Page\n} from '@selvajs/platform';\n\ntype AnyListOptions = ListOptions | DefinitionListOptions;\n\n/**\n * In-memory pagination for filesystem-backed adapters.\n * Cursor is an offset encoded as a string. Good enough for single-node local use.\n */\nexport function paginate<T>(items: T[], opts?: AnyListOptions): Page<T> {\n\tconst limit = clampPageLimit(opts?.limit);\n\tconst offset = decodeOffsetCursor(opts?.cursor);\n\tconst slice = items.slice(offset, offset + limit);\n\tconst nextOffset = offset + slice.length;\n\treturn {\n\t\titems: slice,\n\t\tnextCursor: nextOffset < items.length ? encodeOffsetCursor(nextOffset) : undefined\n\t};\n}\n\n/**\n * Sort a list in place per ListOptions. Mutates the input.\n * Pass `keyFn` to customize how the comparison value is derived (e.g. nested\n * fields, case-folded strings).\n */\nexport function applyOrder<T>(\n\titems: T[],\n\topts?: AnyListOptions,\n\tkeyFn: (item: T, field: string) => unknown = (item, field) =>\n\t\t(item as Record<string, unknown>)[field]\n): T[] {\n\tconst field = opts?.orderBy ?? 'createdAt';\n\tconst dir = opts?.orderDir ?? 'desc';\n\tconst mul = dir === 'asc' ? 1 : -1;\n\titems.sort((a, b) => {\n\t\tconst av = (keyFn(a, field) ?? '') as string | number;\n\t\tconst bv = (keyFn(b, field) ?? '') as string | number;\n\t\tif (av < bv) return -1 * mul;\n\t\tif (av > bv) return 1 * mul;\n\t\treturn 0;\n\t});\n\treturn items;\n}\n","import * as path from 'node:path';\nimport type {\n\tIAuthProvider,\n\tIPasswordAuth,\n\tAuthUser,\n\tLoginResult,\n\tUserManagementResult,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { ProviderError } from '@selvajs/platform';\nimport { previousKey } from '@selvajs/platform/config';\nimport { signHmacToken, verifyHmacToken } from './hmac.js';\nimport { verifyPasswordHash, createLocalAuthUserStore } from './users.js';\nimport type { LocalAuthUserStore, StoredAuthUser } from './users.js';\nimport { paginate } from '../data/pagination.js';\n\nconst SESSION_MAX_AGE_MS = 8 * 60 * 60 * 1000;\n\n// Mirrors `MIN_TOKEN_SECRET_LENGTH` (share/invite tokens) and the 32-byte\n// `SELVA_AT_REST_KEY` rule so a weak session secret can't reach prod. Duplicated\n// rather than imported — the local provider has no `@selvajs/server` dependency.\nconst MIN_HMAC_SECRET_LENGTH = 32;\n\n// The `.env.example` placeholder is 41 chars, so it clears the length guard\n// above. An operator who copies the file without rotating boots with a signing\n// key that is public in the repo — every session token forgeable. `selva\n// doctor` catches it, but nothing forces anyone to run doctor.\nexport const PLACEHOLDER_SECRET = 'replace-this-with-a-random-32-byte-hex-key';\n\nfunction toAuthUser(\n\tu: Pick<StoredAuthUser, 'id' | 'email' | 'createdAt' | 'lastLoginAt' | 'disabled'>\n): AuthUser {\n\treturn {\n\t\tid: u.id,\n\t\temail: u.email,\n\t\tcreatedAt: u.createdAt,\n\t\tlastLoginAt: u.lastLoginAt,\n\t\tdisabled: u.disabled\n\t};\n}\n\nexport interface LocalAuthProviderConfig {\n\t/** HMAC signing secret. Pass from env (SELVA_HMAC_KEY). */\n\thmacSecret: string;\n\t/** The secret before the last rotation. Sessions it signed stay valid until they expire. */\n\tpreviousHmacSecret?: string;\n\t/** Epoch ms after which `previousHmacSecret` is no longer accepted. */\n\tpreviousHmacSecretExpiresAt?: number;\n\t/** Absolute path to auth-users.json. Omit for stateless (no-DATA_PATH) mode. */\n\tusersFilePath?: string;\n}\n\nclass LocalPasswordAuth implements IPasswordAuth {\n\tconstructor(\n\t\tprivate readonly users: LocalAuthUserStore | undefined,\n\t\tprivate readonly mintToken: (user: AuthUser) => string\n\t) {}\n\n\tasync verifyLogin(email: string, password: string): Promise<LoginResult> {\n\t\tif (!this.users) return { kind: 'failed', reason: 'invalid_credentials' };\n\t\tconst user = await this.users.findByEmail(email);\n\t\tif (!user) return { kind: 'failed', reason: 'invalid_credentials' };\n\t\tif (user.disabled) return { kind: 'failed', reason: 'disabled' };\n\t\tif (!user.passwordHash || !(await verifyPasswordHash(password, user.passwordHash))) {\n\t\t\treturn { kind: 'failed', reason: 'invalid_credentials' };\n\t\t}\n\t\tawait this.users.touchLastLogin(user.id).catch(() => {});\n\t\tconst auth = toAuthUser(user);\n\t\treturn { kind: 'success', user: auth, sessionToken: this.mintToken(auth) };\n\t}\n\n\tasync createUserWithPassword(email: string, password: string): Promise<AuthUser> {\n\t\tif (!this.users) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t'createUserWithPassword requires a users.json backend (DATA_PATH)',\n\t\t\t\t500\n\t\t\t);\n\t\t}\n\t\t// Permissions and the user-data row are seeded separately, via\n\t\t// `IDataProvider.ensureUser` + `IPlatformPermissionStore.set`.\n\t\treturn toAuthUser(await this.users.createUser(email, password));\n\t}\n\n\tasync registerUser(email: string, password: string): Promise<AuthUser | null> {\n\t\tif (!this.users) return null;\n\t\treturn toAuthUser(await this.users.createUser(email, password));\n\t}\n}\n\nexport class LocalAuthProvider implements IAuthProvider {\n\tprivate readonly hmacSecret: string;\n\tprivate readonly previousHmacSecret?: string;\n\tprivate readonly previousHmacSecretExpiresAt?: number;\n\tprivate readonly users?: LocalAuthUserStore;\n\n\treadonly name = 'Local';\n\treadonly passwordAuth: IPasswordAuth;\n\n\tconstructor(config: LocalAuthProviderConfig) {\n\t\tthis.hmacSecret = config.hmacSecret;\n\t\tthis.previousHmacSecret = config.previousHmacSecret;\n\t\tthis.previousHmacSecretExpiresAt = config.previousHmacSecretExpiresAt;\n\t\tif (config.usersFilePath) {\n\t\t\tthis.users = createLocalAuthUserStore(config.usersFilePath);\n\t\t}\n\t\tthis.passwordAuth = new LocalPasswordAuth(this.users, (user) =>\n\t\t\tsignHmacToken(this.hmacSecret, user.id, SESSION_MAX_AGE_MS)\n\t\t);\n\t}\n\n\t/**\n\t * The underlying identity store, or undefined in stateless (no-DATA_PATH)\n\t * mode. Exposed so callers needing direct seed/read access (tests, advanced\n\t * wiring) share this provider's store — and its cache — instead of\n\t * constructing a second store on the same file, which would diverge from it.\n\t */\n\tget userStore(): LocalAuthUserStore | undefined {\n\t\treturn this.users;\n\t}\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalAuthProvider {\n\t\tconst hmacSecret = env.SELVA_HMAC_KEY;\n\t\tif (!hmacSecret) throw new Error('Missing required env var: SELVA_HMAC_KEY');\n\t\tif (hmacSecret === PLACEHOLDER_SECRET) {\n\t\t\tthrow new Error(\n\t\t\t\t'SELVA_HMAC_KEY is still the .env.example placeholder — every session token ' +\n\t\t\t\t\t'would be forgeable by anyone with the repo. Generate one with: openssl rand -hex 32'\n\t\t\t);\n\t\t}\n\t\tif (hmacSecret.length < MIN_HMAC_SECRET_LENGTH) {\n\t\t\tthrow new Error(\n\t\t\t\t`SELVA_HMAC_KEY must be at least ${MIN_HMAC_SECRET_LENGTH} characters ` +\n\t\t\t\t\t`(got ${hmacSecret.length}). Generate one with: openssl rand -base64 32`\n\t\t\t);\n\t\t}\n\t\tconst previous = previousKey(env, 'SELVA_HMAC_KEY');\n\t\treturn new LocalAuthProvider({\n\t\t\thmacSecret,\n\t\t\t...(previous.key ? { previousHmacSecret: previous.key } : {}),\n\t\t\t...(previous.state === 'active'\n\t\t\t\t? { previousHmacSecretExpiresAt: Date.parse(previous.expires) }\n\t\t\t\t: {}),\n\t\t\tusersFilePath: env.DATA_PATH ? path.join(env.DATA_PATH, 'auth-users.json') : undefined\n\t\t});\n\t}\n\n\t/**\n\t * Runs on every authenticated request, so it stays read-only: one cached\n\t * `findById`, no writes. `lastLoginAt` is stamped at login time in\n\t * `verifyLogin`, not here — the only consumers treat it as a\n\t * has-ever-signed-in flag (invited vs. active in admin/team lists), not a\n\t * per-request activity clock, so a write on every request would cost a\n\t * full file read+parse just to usually decide not to write.\n\t */\n\tasync verifyToken(token: string): Promise<AuthUser | null> {\n\t\tlet { valid, userId } = verifyHmacToken(token, this.hmacSecret);\n\t\tconst previousAccepted =\n\t\t\tthis.previousHmacSecret !== undefined &&\n\t\t\t(this.previousHmacSecretExpiresAt === undefined ||\n\t\t\t\tDate.now() < this.previousHmacSecretExpiresAt);\n\t\tif (!valid && previousAccepted && this.previousHmacSecret) {\n\t\t\t({ valid, userId } = verifyHmacToken(token, this.previousHmacSecret));\n\t\t}\n\t\tif (!valid) return null;\n\t\tif (!this.users) return null;\n\t\tconst u = await this.users.findById(userId);\n\t\tif (!u || u.disabled) return null;\n\t\treturn toAuthUser(u);\n\t}\n\n\tasync touchLastLogin(id: string): Promise<void> {\n\t\tif (!this.users) return;\n\t\tawait this.users.touchLastLogin(id);\n\t}\n\n\tasync getUser(id: string): Promise<AuthUser | null> {\n\t\tif (!this.users) return null;\n\t\tconst u = await this.users.findById(id);\n\t\treturn u ? toAuthUser(u) : null;\n\t}\n\n\tasync listUsers(opts?: ListOptions): Promise<Page<AuthUser> | null> {\n\t\tif (!this.users) return null;\n\t\tconst users = await this.users.listUsers();\n\t\treturn paginate(users.map(toAuthUser), opts);\n\t}\n\n\tasync deleteUser(id: string): Promise<UserManagementResult> {\n\t\t// Identity-only delete. The caller enforces the sole-instance_admin\n\t\t// invariant via `IPlatformPermissionStore.countInstanceAdminsExcluding`\n\t\t// before calling this, and removes the user-data row via\n\t\t// `LocalDataProvider`'s cascade hook.\n\t\tif (!this.users) return 'not_supported';\n\t\tconst target = await this.users.findById(id);\n\t\tif (!target) return 'not_found';\n\t\ttry {\n\t\t\tawait this.users.deleteUser(id);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync disableUser(id: string): Promise<UserManagementResult> {\n\t\t// Identity-only disable. Same sole-instance_admin invariant as `deleteUser`, enforced by the caller.\n\t\tif (!this.users) return 'not_supported';\n\t\tconst target = await this.users.findById(id);\n\t\tif (!target) return 'not_found';\n\t\ttry {\n\t\t\tawait this.users.setDisabled(id, true);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tIInviteStore,\n\tIEventSink,\n\tInvite,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { NoopEventSink, actorOf } from '@selvajs/platform';\nimport { paginate, applyOrder } from './pagination.js';\nimport { readJsonFile, writeJsonFile, withFileLock } from './fsJson.js';\n\ninterface InvitesFile {\n\tinvites: Invite[];\n}\n// Factory, not a shared constant: `readJsonFile` returns its fallback by\n// reference on a missing file, and `create` mutates it via `.push`. A shared\n// object would leak those mutations across requests.\nconst empty = (): InvitesFile => ({ invites: [] });\n\n/**\n * No per-call scoping by ctx.userId — the route layer gates admin actions.\n * `getByTokenHash` is the sole unauthenticated read; it hides expired and\n * already-accepted invites so a reused link surfaces a clean error.\n */\nexport class LocalInviteStore implements IInviteStore {\n\tprivate readonly filePath: string;\n\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tevents: IEventSink = new NoopEventSink()\n\t): LocalInviteStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalInviteStore(env.DATA_PATH, events);\n\t}\n\n\tconstructor(\n\t\tdataPath: string,\n\t\tprivate readonly events: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.filePath = path.join(dataPath, 'invites.json');\n\t}\n\n\tprivate async load(): Promise<InvitesFile> {\n\t\treturn readJsonFile<InvitesFile>(this.filePath, empty());\n\t}\n\n\tprivate async save(file: InvitesFile): Promise<void> {\n\t\tawait writeJsonFile(this.filePath, file);\n\t}\n\n\tprivate locked<T>(fn: () => Promise<T>): Promise<T> {\n\t\treturn withFileLock(this.filePath, fn);\n\t}\n\n\tasync create(ctx: RequestContext, invite: Invite): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tfile.invites.push(invite);\n\t\t\tawait this.save(file);\n\t\t});\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.created',\n\t\t\tinviteId: invite.id,\n\t\t\torgId: invite.orgId,\n\t\t\temail: invite.email,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync getByTokenHash(_ctx: RequestContext, tokenHash: string): Promise<Invite | null> {\n\t\tconst { invites } = await this.load();\n\t\tconst invite = invites.find((i) => i.tokenHash === tokenHash);\n\t\tif (!invite) return null;\n\t\tif (invite.acceptedAt) return null;\n\t\tif (Date.parse(invite.expiresAt) <= Date.now()) return null;\n\t\treturn invite;\n\t}\n\n\tasync listByOrg(_ctx: RequestContext, orgId: string, opts?: ListOptions): Promise<Page<Invite>> {\n\t\tconst { invites } = await this.load();\n\t\tconst filtered = invites.filter((i) => i.orgId === orgId);\n\t\treturn paginate(applyOrder(filtered, opts), opts);\n\t}\n\n\tasync markAccepted(ctx: RequestContext, id: string, userId: string): Promise<boolean> {\n\t\tconst invite = await this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst target = file.invites.find((i) => i.id === id);\n\t\t\tif (!target || target.acceptedAt) return null;\n\t\t\tif (Date.parse(target.expiresAt) <= Date.now()) return null;\n\t\t\ttarget.acceptedAt = new Date().toISOString();\n\t\t\ttarget.acceptedByUserId = userId;\n\t\t\tawait this.save(file);\n\t\t\treturn target;\n\t\t});\n\t\tif (!invite) return false;\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.accepted',\n\t\t\tinviteId: invite.id,\n\t\t\torgId: invite.orgId,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t\treturn true;\n\t}\n\n\tasync reopen(_ctx: RequestContext, id: string, userId: string): Promise<boolean> {\n\t\treturn this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst target = file.invites.find((i) => i.id === id);\n\t\t\tif (!target?.acceptedAt || target.acceptedByUserId !== userId) return false;\n\t\t\tdelete target.acceptedAt;\n\t\t\tdelete target.acceptedByUserId;\n\t\t\tawait this.save(file);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst target = await this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst found = file.invites.find((i) => i.id === id && !i.acceptedAt);\n\t\t\tif (!found) return null;\n\t\t\tfile.invites = file.invites.filter((i) => i.id !== id || i.acceptedAt);\n\t\t\tawait this.save(file);\n\t\t\treturn found;\n\t\t});\n\t\tif (!target) return;\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.revoked',\n\t\t\tinviteId: id,\n\t\t\torgId: target.orgId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync revokePendingByEmail(ctx: RequestContext, orgId: string, email: string): Promise<string[]> {\n\t\t// Emails are stored lowercase at mint time; normalize the needle too so an\n\t\t// offboarding call with the address as the admin typed it still matches.\n\t\tconst needle = email.trim().toLowerCase();\n\t\tconst doomed = await this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst matched = file.invites.filter(\n\t\t\t\t(i) => i.orgId === orgId && !i.acceptedAt && i.email.toLowerCase() === needle\n\t\t\t);\n\t\t\tif (matched.length === 0) return matched;\n\t\t\tconst ids = new Set(matched.map((i) => i.id));\n\t\t\tfile.invites = file.invites.filter((i) => !ids.has(i.id));\n\t\t\tawait this.save(file);\n\t\t\treturn matched;\n\t\t});\n\t\tfor (const invite of doomed) {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'invite.revoked',\n\t\t\t\tinviteId: invite.id,\n\t\t\t\torgId: invite.orgId,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\t\treturn doomed.map((i) => i.id);\n\t}\n\n\tasync deleteByOrg(_ctx: RequestContext, orgId: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst before = file.invites.length;\n\t\t\tfile.invites = file.invites.filter((i) => i.orgId !== orgId);\n\t\t\tif (file.invites.length === before) return;\n\t\t\tawait this.save(file);\n\t\t});\n\t}\n\n\t/** Invites addressed to or minted by the user, and their name on any they accepted. */\n\tasync eraseUser(userId: string, email: string | undefined): Promise<void> {\n\t\tconst needle = email?.trim().toLowerCase();\n\t\tawait this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tfile.invites = file.invites\n\t\t\t\t.filter((i) => i.invitedBy !== userId && i.email.toLowerCase() !== needle)\n\t\t\t\t.map((i) => (i.acceptedByUserId === userId ? { ...i, acceptedByUserId: undefined } : i));\n\t\t\tawait this.save(file);\n\t\t});\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tApiToken,\n\tApiTokenRevokeReason,\n\tApiTokenSummary,\n\tIApiTokenStore,\n\tIEventSink,\n\tListOptions,\n\tPage,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopEventSink, actorOf } from '@selvajs/platform';\nimport { paginate, applyOrder } from './pagination.js';\nimport { readJsonFile, writeJsonFile, withFileLock } from './fsJson.js';\n\ninterface ApiTokensFile {\n\ttokens: ApiToken[];\n}\n// Factory, not a shared constant: `readJsonFile` returns the fallback by\n// reference and `create` pushes into it.\nconst empty = (): ApiTokensFile => ({ tokens: [] });\n\nfunction isLive(t: ApiToken, now: number): boolean {\n\treturn t.revokedAt === null && Date.parse(t.expiresAt) > now;\n}\n\nfunction summarize({ tokenHash: _hash, ...rest }: ApiToken): ApiTokenSummary {\n\treturn rest;\n}\n\n/** No per-call scoping by ctx: the route layer gates who may mint, list and revoke. */\nexport class LocalApiTokenStore implements IApiTokenStore {\n\tprivate readonly filePath: string;\n\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tevents: IEventSink = new NoopEventSink()\n\t): LocalApiTokenStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalApiTokenStore(env.DATA_PATH, events);\n\t}\n\n\tconstructor(\n\t\tdataPath: string,\n\t\tprivate readonly events: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.filePath = path.join(dataPath, 'api-tokens.json');\n\t}\n\n\tprivate load(): Promise<ApiTokensFile> {\n\t\treturn readJsonFile<ApiTokensFile>(this.filePath, empty());\n\t}\n\n\tprivate save(file: ApiTokensFile): Promise<void> {\n\t\treturn writeJsonFile(this.filePath, file);\n\t}\n\n\tprivate locked<T>(fn: () => Promise<T>): Promise<T> {\n\t\treturn withFileLock(this.filePath, fn);\n\t}\n\n\tasync create(ctx: RequestContext, token: ApiToken): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tfile.tokens.push(token);\n\t\t\tawait this.save(file);\n\t\t});\n\t\tawait this.events.emit({\n\t\t\ttype: 'api_token.created',\n\t\t\tapiTokenId: token.id,\n\t\t\torgId: token.orgId,\n\t\t\tuserId: token.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync getByTokenHash(_ctx: RequestContext, tokenHash: string): Promise<ApiToken | null> {\n\t\tconst { tokens } = await this.load();\n\t\tconst token = tokens.find((t) => t.tokenHash === tokenHash);\n\t\treturn token && isLive(token, Date.now()) ? token : null;\n\t}\n\n\tasync get(_ctx: RequestContext, id: string): Promise<ApiTokenSummary | null> {\n\t\tconst { tokens } = await this.load();\n\t\tconst token = tokens.find((t) => t.id === id);\n\t\treturn token ? summarize(token) : null;\n\t}\n\n\tasync listByOrg(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions & { userId?: string }\n\t): Promise<Page<ApiTokenSummary>> {\n\t\tconst { tokens } = await this.load();\n\t\tconst filtered = tokens\n\t\t\t.filter((t) => t.orgId === orgId && (!opts?.userId || t.userId === opts.userId))\n\t\t\t.map(summarize);\n\t\treturn paginate(applyOrder(filtered, opts), opts);\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string, reason: ApiTokenRevokeReason): Promise<void> {\n\t\tconst token = await this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst found = file.tokens.find((t) => t.id === id);\n\t\t\tif (!found || found.revokedAt !== null) return null;\n\t\t\tfound.revokedAt = new Date().toISOString();\n\t\t\tawait this.save(file);\n\t\t\treturn found;\n\t\t});\n\t\tif (token) await this.emitRevoked(ctx, token, reason);\n\t}\n\n\tasync revokeAllForUser(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\topts: { orgId?: string; reason: ApiTokenRevokeReason }\n\t): Promise<string[]> {\n\t\tconst doomed = await this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst matching = file.tokens.filter(\n\t\t\t\t(t) =>\n\t\t\t\t\tt.userId === userId && t.revokedAt === null && (!opts.orgId || t.orgId === opts.orgId)\n\t\t\t);\n\t\t\tif (matching.length === 0) return [];\n\t\t\tconst at = new Date().toISOString();\n\t\t\tfor (const t of matching) t.revokedAt = at;\n\t\t\tawait this.save(file);\n\t\t\treturn matching;\n\t\t});\n\t\tfor (const t of doomed) await this.emitRevoked(ctx, t, opts.reason);\n\t\treturn doomed.map((t) => t.id);\n\t}\n\n\ttouchLastUsed(_ctx: RequestContext, id: string, at: string): Promise<void> {\n\t\treturn this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst token = file.tokens.find((t) => t.id === id);\n\t\t\tif (!token) return;\n\t\t\ttoken.lastUsedAt = at;\n\t\t\tawait this.save(file);\n\t\t});\n\t}\n\n\teraseUser(_ctx: RequestContext, userId: string): Promise<void> {\n\t\treturn this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst before = JSON.stringify(file.tokens);\n\t\t\tfile.tokens = file.tokens\n\t\t\t\t.filter((t) => t.userId !== userId)\n\t\t\t\t.map((t) => (t.createdBy === userId ? { ...t, createdBy: null } : t));\n\t\t\tif (JSON.stringify(file.tokens) !== before) await this.save(file);\n\t\t});\n\t}\n\n\tdeleteByOrg(_ctx: RequestContext, orgId: string): Promise<void> {\n\t\treturn this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst before = file.tokens.length;\n\t\t\tfile.tokens = file.tokens.filter((t) => t.orgId !== orgId);\n\t\t\tif (file.tokens.length !== before) await this.save(file);\n\t\t});\n\t}\n\n\tprivate emitRevoked(\n\t\tctx: RequestContext,\n\t\ttoken: ApiToken,\n\t\treason: ApiTokenRevokeReason\n\t): Promise<void> {\n\t\treturn this.events.emit({\n\t\t\ttype: 'api_token.revoked',\n\t\t\tapiTokenId: token.id,\n\t\t\torgId: token.orgId,\n\t\t\treason,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n","import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';\nimport { parseKey32 } from './key32.js';\nimport { previousKey } from '../config/previous-key.js';\nimport type { EnvRecord } from '../config/resolve.js';\n\nconst ALGO = 'aes-256-gcm';\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst PREFIX_V1 = 'enc:v1:';\nconst PREFIX_V2 = 'enc:v2:';\nconst PREFIX_V3 = 'enc:v3:';\n// Every version prefix has this length.\nconst PREFIX_LENGTH = PREFIX_V1.length;\n\n/** The record a secret belongs to, and the URL the secret is sent to. */\nexport interface SecretBinding {\n\tid: string;\n\turl: string;\n}\n\nexport function isEncryptedSecret(value: string): boolean {\n\treturn isLegacyEnvelope(value) || value.startsWith(PREFIX_V3);\n}\n\n/**\n * An `enc:v1:` or `enc:v2:` envelope: sealed without a {@link SecretBinding}, so it\n * still opens after its record's URL changes. Stores re-seal these.\n */\nexport function isLegacyEnvelope(value: string): boolean {\n\treturn value.startsWith(PREFIX_V1) || value.startsWith(PREFIX_V2);\n}\n\n/**\n * An `enc:v<n>:` envelope this build cannot open: a newer Selva sealed it, and this\n * one runs after a downgrade. It is ciphertext, so it must never be reported or\n * used as a plaintext key.\n */\nexport function isUnknownEnvelope(value: string): boolean {\n\treturn /^enc:v\\d+:/.test(value) && !isEncryptedSecret(value);\n}\n\n// JSON, so no two id/url pairs encode alike: `[\"a:b\",\"c\"]` is not `[\"a\",\"b:c\"]`.\nfunction bindingAad({ id, url }: SecretBinding): Buffer {\n\treturn Buffer.from(JSON.stringify([id, url]), 'utf8');\n}\n\n/**\n * AES-256-GCM envelope for at-rest secrets (e.g. compute API keys):\n * `enc:v<n>:<base64(iv|tag|ciphertext)>`. What `aad` is picks the version, and\n * the version says what GCM authenticates besides the ciphertext:\n * - a {@link SecretBinding} gives `v3`: the record's id and URL. Ciphertext copied\n * onto another record, or a record pointed at another host, fails to decrypt\n * instead of handing the plaintext to that host.\n * - a string gives `v2`: that string, which stores set to the record's id.\n * - nothing gives `v1`: nothing.\n *\n * Defends against backup leaks, accidental file/DB sharing, and read-only\n * storage access — not against an attacker who also has the master key\n * (`SELVA_AT_REST_KEY` env var, process memory). This is encryption at rest,\n * not a secret manager.\n *\n * Pure `node:crypto`, no fs or DB coupling, so the local and Supabase\n * compute-server stores share this one implementation.\n */\nexport function encryptSecret(\n\tplaintext: string,\n\tkey: Buffer,\n\taad?: string | SecretBinding\n): string {\n\tif (key.length !== 32) {\n\t\tthrow new Error(`Secret key must be 32 bytes; got ${key.length}`);\n\t}\n\tif (isEncryptedSecret(plaintext)) {\n\t\tthrow new Error('Refusing to encrypt a value that is already encrypted');\n\t}\n\tconst [prefix, aadBytes] =\n\t\taad === undefined\n\t\t\t? [PREFIX_V1, undefined]\n\t\t\t: typeof aad === 'string'\n\t\t\t\t? [PREFIX_V2, Buffer.from(aad, 'utf8')]\n\t\t\t\t: [PREFIX_V3, bindingAad(aad)];\n\tconst iv = randomBytes(IV_BYTES);\n\tconst cipher = createCipheriv(ALGO, key, iv);\n\tif (aadBytes) cipher.setAAD(aadBytes);\n\tconst ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n\tconst tag = cipher.getAuthTag();\n\treturn prefix + Buffer.concat([iv, tag, ciphertext]).toString('base64');\n}\n\nfunction aadToOpen(envelope: string, aad: string | SecretBinding | undefined): Buffer | undefined {\n\tif (envelope.startsWith(PREFIX_V1)) return undefined;\n\tif (envelope.startsWith(PREFIX_V2)) {\n\t\tif (aad === undefined) throw new Error('This secret is bound to a record: pass its id');\n\t\treturn Buffer.from(typeof aad === 'string' ? aad : aad.id, 'utf8');\n\t}\n\tif (aad === undefined || typeof aad === 'string') {\n\t\tthrow new Error('This secret is bound to a record and its URL: pass both');\n\t}\n\treturn bindingAad(aad);\n}\n\n/**\n * `aad` is ignored for `v1`. `v2` takes the string it was sealed with, or a\n * binding's `id`; `v3` needs the binding.\n */\nexport function decryptSecret(envelope: string, key: Buffer, aad?: string | SecretBinding): string {\n\tif (key.length !== 32) {\n\t\tthrow new Error(`Secret key must be 32 bytes; got ${key.length}`);\n\t}\n\tif (!isEncryptedSecret(envelope)) {\n\t\tthrow new Error('Value is not an encrypted secret envelope');\n\t}\n\tconst aadBytes = aadToOpen(envelope, aad);\n\tconst buf = Buffer.from(envelope.slice(PREFIX_LENGTH), 'base64');\n\tif (buf.length < IV_BYTES + TAG_BYTES) {\n\t\tthrow new Error('Encrypted secret is shorter than its IV and tag');\n\t}\n\tconst iv = buf.subarray(0, IV_BYTES);\n\tconst tag = buf.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);\n\tconst ciphertext = buf.subarray(IV_BYTES + TAG_BYTES);\n\t// Pinned: without it Node accepts a truncated tag, down to 4 bytes.\n\tconst decipher = createDecipheriv(ALGO, key, iv, { authTagLength: TAG_BYTES });\n\tdecipher.setAuthTag(tag);\n\tif (aadBytes) decipher.setAAD(aadBytes);\n\treturn Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');\n}\n\nconst GENERATE_HINT =\n\t\"Generate one with: node -e \\\"console.log(require('crypto').randomBytes(32).toString('hex'))\\\"\";\n\n/**\n * Decodes a `SELVA_AT_REST_KEY` env var into a 32-byte buffer (64-char hex or\n * base64, with or without padding). Throws on anything else so a\n * misconfigured key fails loudly at boot instead of silently producing\n * ciphertext nothing can decrypt.\n */\nexport function decodeSecretKey(raw: string): Buffer {\n\tconst key = parseKey32(raw);\n\tif (key) return key;\n\tthrow new Error(\n\t\t`SELVA_AT_REST_KEY must be 32 bytes encoded as 64-char hex or base64. ${GENERATE_HINT}`\n\t);\n}\n\n/**\n * `SELVA_AT_REST_KEY`, plus `SELVA_AT_REST_KEY_PREVIOUS` while it is within its\n * deadline. Throws when the current key is missing or malformed.\n */\nexport function readAtRestKeys(env: EnvRecord): { current: Buffer; previous?: Buffer } {\n\tif (!env.SELVA_AT_REST_KEY) {\n\t\tthrow new Error(\n\t\t\t`Missing required env var: SELVA_AT_REST_KEY (32-byte hex or base64). ${GENERATE_HINT}`\n\t\t);\n\t}\n\tconst current = decodeSecretKey(env.SELVA_AT_REST_KEY);\n\tconst previous = previousKey(env, 'SELVA_AT_REST_KEY').key;\n\treturn previous ? { current, previous: decodeSecretKey(previous) } : { current };\n}\n\n/**\n * Result of a compute-server store's `verifySecrets()`. One `failures` entry\n * per server whose `apiKey` couldn't be loaded:\n * - `plaintext_on_disk` — the field exists but isn't an `enc:` envelope:\n * a hand-edit, a legacy row from before encryption, or a migration\n * regression. Security-relevant.\n * - `key_mismatch` — envelope is valid but GCM auth-tag verification fails\n * under the current `SELVA_AT_REST_KEY`: the key was rotated, or the data\n * came from another deployment.\n * - `unknown_envelope` — an `enc:v<n>:` envelope from a newer Selva than the\n * one running ({@link isUnknownEnvelope}): the app was downgraded.\n */\nexport type SecretVerificationFailureReason =\n\t'key_mismatch' | 'plaintext_on_disk' | 'unknown_envelope';\n\nexport interface SecretVerificationFailure {\n\tserverId: string;\n\tserverLabel: string;\n\treason: SecretVerificationFailureReason;\n\t/** Underlying error message for `key_mismatch`. Absent otherwise. */\n\tcause?: string;\n}\n\nexport interface SecretVerificationReport {\n\tok: boolean;\n\tfailures: SecretVerificationFailure[];\n\t/** True if at least one row holds an unencrypted apiKey at rest. */\n\tplaintextFound: boolean;\n\t/** Rows only SELVA_AT_REST_KEY_PREVIOUS opens. Drop the previous key once this is 0. */\n\tonPreviousKey?: number;\n\t/**\n\t * Rows in a {@link isLegacyEnvelope legacy envelope}, which still opens after the\n\t * server's URL changes. `reencryptSecrets` re-seals them. Absent when there are none.\n\t */\n\tlegacyEnvelopes?: number;\n}\n\n/**\n * {@link decryptSecret} under each key in turn, current first. AES-GCM\n * authenticates, so a wrong key fails rather than returning garbage, and trying\n * the next one is safe. `keyIndex` above 0 means the caller should re-encrypt\n * under `keys[0]`.\n */\nexport function decryptWithKeys(\n\tenvelope: string,\n\tkeys: readonly Buffer[],\n\taad?: string | SecretBinding\n): { plaintext: string; keyIndex: number } {\n\tlet lastError: unknown;\n\tfor (const [keyIndex, key] of keys.entries()) {\n\t\ttry {\n\t\t\treturn { plaintext: decryptSecret(envelope, key, aad), keyIndex };\n\t\t} catch (err) {\n\t\t\tlastError = err;\n\t\t}\n\t}\n\tthrow lastError ?? new Error('No key to decrypt with');\n}\n","import * as path from 'node:path';\nimport {\n\tisOrgServer,\n\tisPlatformServer,\n\tscopeConfigToOrg,\n\ttype IComputeServerStore,\n\ttype ComputeConfig,\n\ttype ComputeServerConfig,\n\ttype GetConfigOptions,\n\ttype PlatformComputeServer,\n\ttype RequestContext,\n\ttype SecretVerificationFailure,\n\ttype SecretVerificationReport,\n\ttype ILogger\n} from '@selvajs/platform';\nimport { NoopLogger, ProviderError } from '@selvajs/platform';\nimport {\n\tdecryptWithKeys,\n\tencryptSecret,\n\tisEncryptedSecret,\n\tisLegacyEnvelope,\n\tisUnknownEnvelope,\n\treadAtRestKeys,\n\ttype SecretBinding\n} from '@selvajs/platform/computeServer';\nimport { readJsonFile, withFileLock, writeJsonFile } from './fsJson.js';\n\n// Re-exported from `@selvajs/platform` (`computeServer/secrets`) — kept here so\n// the local provider's public surface (index.ts) stays backward-compatible.\nexport type {\n\tSecretVerificationFailure,\n\tSecretVerificationFailureReason,\n\tSecretVerificationReport\n} from '@selvajs/platform';\n\n/**\n * On-disk shape of compute.config.json: all servers (platform + org-private)\n * in one array, the global `defaultServerId`, and the per-org `orgDefaults`\n * map. `apiKey` is always stored as an `enc:` envelope (AES-256-GCM) bound to\n * the server's id and URL; the store decrypts on read so callers see plaintext.\n */\ninterface OnDiskShape {\n\tservers: ComputeServerConfig[];\n\tdefaultServerId?: string;\n\torgDefaults?: Record<string, string>;\n}\n\n// `readJsonFile` returns its fallback BY REFERENCE when the file is missing,\n// so a shared module-level constant would let mutations bleed across calls.\nconst empty = (): OnDiskShape => ({ servers: [], orgDefaults: {} });\n\n// `getServerApiKey` looks a key up by id alone, so an org reusing another\n// scope's id would get that scope's key sent to its own URL.\nfunction assertIdsFree(\n\tincoming: readonly ComputeServerConfig[],\n\totherScopes: readonly ComputeServerConfig[]\n): void {\n\tconst taken = new Set(otherScopes.map((s) => s.id));\n\tif (incoming.some((s) => taken.has(s.id))) {\n\t\tthrow new ProviderError('A compute server id is already in use', 409);\n\t}\n}\n\nconst bindingOf = (s: ComputeServerConfig): SecretBinding => ({ id: s.id, url: s.serverUrl });\n\n/**\n * Reads/writes compute.config.json, re-read on every call so edits take\n * effect without a restart. Mutation methods are scope-targeted\n * (`savePlatformServers`, `saveOrgServers`, `setOrgDefault`) — each leaves\n * rows in the other scopes untouched.\n */\nexport class LocalComputeServerStore implements IComputeServerStore {\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tlogger?: ILogger\n\t): LocalComputeServerStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\tconst keys = readAtRestKeys(env);\n\t\treturn new LocalComputeServerStore(\n\t\t\tpath.join(env.DATA_PATH, 'compute.config.json'),\n\t\t\tkeys.current,\n\t\t\tlogger,\n\t\t\tkeys.previous\n\t\t);\n\t}\n\n\tprivate readonly logger: ILogger;\n\t/** Current key first; the previous one still opens rows sealed before a rotation. */\n\tprivate readonly keys: Buffer[];\n\n\tconstructor(\n\t\tprivate readonly configFilePath: string,\n\t\tprivate readonly secretKey: Buffer,\n\t\tlogger?: ILogger,\n\t\tpreviousKey?: Buffer\n\t) {\n\t\tthis.logger = logger ?? new NoopLogger();\n\t\tthis.keys = previousKey ? [secretKey, previousKey] : [secretKey];\n\t}\n\n\tprivate async readAll(): Promise<OnDiskShape> {\n\t\tconst raw = await readJsonFile<OnDiskShape>(this.configFilePath, empty());\n\t\treturn {\n\t\t\tservers: raw.servers ?? [],\n\t\t\tdefaultServerId: raw.defaultServerId,\n\t\t\torgDefaults: raw.orgDefaults ?? {}\n\t\t};\n\t}\n\n\t/**\n\t * Tolerant per-row decrypt: a row whose key cannot be opened comes back with\n\t * `apiKey: undefined` and a logged warning, rather than failing the whole read.\n\t * The page keeps rendering, and a solve against that server fails later when\n\t * Rhino.Compute rejects the missing key. That covers ciphertext that does not\n\t * authenticate under the current `SELVA_AT_REST_KEY`, and an envelope from a\n\t * newer Selva. `verifySecrets()` is the strict counterpart for boot time.\n\t *\n\t * Plaintext is the exception. The store never writes it (every write goes\n\t * through `encryptApiKeys`), so seeing it means someone hand-edited the file\n\t * with a real secret exposed: a read that would use the key throws.\n\t * `plaintext: 'unreadable'` returns the row keyless instead, for the save\n\t * path: a throw there would block the save that replaces the key.\n\t */\n\tprivate decryptApiKeys(\n\t\tservers: ComputeServerConfig[],\n\t\t{ plaintext = 'throw' }: { plaintext?: 'throw' | 'unreadable' } = {}\n\t): ComputeServerConfig[] {\n\t\treturn servers.map((s) => {\n\t\t\tif (!s.apiKey) return s;\n\t\t\tconst fields = { component: 'selva', serverLabel: s.label, serverId: s.id };\n\t\t\tif (isUnknownEnvelope(s.apiKey)) {\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t`Could not read apiKey: it is sealed as ${s.apiKey.slice(0, 6)}, a format this Selva version does not know. ` +\n\t\t\t\t\t\t'A newer version wrote it. This server is returned without an apiKey and solves against it will fail. ' +\n\t\t\t\t\t\t'Upgrade Selva again, or re-enter the key via /admin/compute.',\n\t\t\t\t\tfields\n\t\t\t\t);\n\t\t\t\treturn { ...s, apiKey: undefined };\n\t\t\t}\n\t\t\tif (!isEncryptedSecret(s.apiKey)) {\n\t\t\t\tconst message =\n\t\t\t\t\t`compute.config.json contains an unencrypted apiKey for server \"${s.label}\" (${s.id}). ` +\n\t\t\t\t\t'Re-enter the key via /admin/compute so it is stored encrypted.';\n\t\t\t\tif (plaintext === 'throw') throw new Error(message);\n\t\t\t\tthis.logger.error(message, fields);\n\t\t\t\treturn { ...s, apiKey: undefined };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn { ...s, apiKey: decryptWithKeys(s.apiKey, this.keys, bindingOf(s)).plaintext };\n\t\t\t} catch (cause) {\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t'Could not decrypt apiKey: the stored ciphertext does not match the current SELVA_AT_REST_KEY. ' +\n\t\t\t\t\t\t'This server is returned without an apiKey and solves against it will fail. ' +\n\t\t\t\t\t\t'Re-enter the key via /admin/compute, or restore the original SELVA_AT_REST_KEY.',\n\t\t\t\t\t{\n\t\t\t\t\t\t...fields,\n\t\t\t\t\t\terr: cause instanceof Error ? (cause.stack ?? cause.message) : String(cause)\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\treturn { ...s, apiKey: undefined };\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Boot-time integrity check: attempts to decrypt every server's `apiKey`\n\t * and returns a report instead of throwing — the caller decides what to do\n\t * (refuse boot, log and degrade, etc). Call from `hooks.server.ts` so a key\n\t * mismatch fails loudly at deploy time, not as a blank page when a user\n\t * first hits a route that loads compute config.\n\t */\n\tasync verifySecrets(): Promise<SecretVerificationReport> {\n\t\tconst all = await this.readAll();\n\t\tconst failures: SecretVerificationFailure[] = [];\n\t\tlet plaintextFound = false;\n\t\tlet onPreviousKey = 0;\n\t\tlet legacyEnvelopes = 0;\n\n\t\tfor (const s of all.servers) {\n\t\t\tif (!s.apiKey) continue;\n\t\t\tif (isUnknownEnvelope(s.apiKey)) {\n\t\t\t\tfailures.push({ serverId: s.id, serverLabel: s.label, reason: 'unknown_envelope' });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isEncryptedSecret(s.apiKey)) {\n\t\t\t\tplaintextFound = true;\n\t\t\t\tfailures.push({\n\t\t\t\t\tserverId: s.id,\n\t\t\t\t\tserverLabel: s.label,\n\t\t\t\t\treason: 'plaintext_on_disk'\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isLegacyEnvelope(s.apiKey)) legacyEnvelopes += 1;\n\t\t\ttry {\n\t\t\t\tif (decryptWithKeys(s.apiKey, this.keys, bindingOf(s)).keyIndex > 0) onPreviousKey += 1;\n\t\t\t} catch (cause) {\n\t\t\t\tfailures.push({\n\t\t\t\t\tserverId: s.id,\n\t\t\t\t\tserverLabel: s.label,\n\t\t\t\t\treason: 'key_mismatch',\n\t\t\t\t\tcause: cause instanceof Error ? cause.message : String(cause)\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tok: failures.length === 0,\n\t\t\tfailures,\n\t\t\tplaintextFound,\n\t\t\t...(this.keys.length > 1 ? { onPreviousKey } : {}),\n\t\t\t...(legacyEnvelopes > 0 ? { legacyEnvelopes } : {})\n\t\t};\n\t}\n\n\t/**\n\t * Re-seal every row that only the previous key opens, or that sits in a legacy\n\t * envelope, under the current key and the row's binding. Under the file lock,\n\t * so it can't interleave with an admin save. Returns how many rows it re-sealed.\n\t */\n\tasync reencryptSecrets(): Promise<number> {\n\t\treturn withFileLock(this.configFilePath, async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tlet changed = 0;\n\t\t\tconst servers = all.servers.map((s) => {\n\t\t\t\tif (!s.apiKey || !isEncryptedSecret(s.apiKey)) return s;\n\t\t\t\ttry {\n\t\t\t\t\tconst { plaintext, keyIndex } = decryptWithKeys(s.apiKey, this.keys, bindingOf(s));\n\t\t\t\t\tif (keyIndex === 0 && !isLegacyEnvelope(s.apiKey)) return s;\n\t\t\t\t\tchanged += 1;\n\t\t\t\t\treturn { ...s, apiKey: encryptSecret(plaintext, this.secretKey, bindingOf(s)) };\n\t\t\t\t} catch {\n\t\t\t\t\treturn s;\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (changed > 0) await writeJsonFile<OnDiskShape>(this.configFilePath, { ...all, servers });\n\t\t\treturn changed;\n\t\t});\n\t}\n\n\tprivate encryptApiKeys(servers: ComputeServerConfig[]): ComputeServerConfig[] {\n\t\treturn servers.map((s) => {\n\t\t\tif (!s.apiKey) return s;\n\t\t\treturn { ...s, apiKey: encryptSecret(s.apiKey, this.secretKey, bindingOf(s)) };\n\t\t});\n\t}\n\n\tasync getConfig(_ctx: RequestContext, opts: GetConfigOptions = {}): Promise<ComputeConfig> {\n\t\tconst all = await this.readAll();\n\t\t// Keys are read through here only to merge a save, which must be able to\n\t\t// replace a plaintext one.\n\t\tconst servers = opts.includeApiKeys\n\t\t\t? this.decryptApiKeys(all.servers, { plaintext: 'unreadable' })\n\t\t\t: all.servers.map((s) => ({ ...s, apiKey: undefined }));\n\t\tconst config: ComputeConfig = {\n\t\t\t// `hasApiKey` reads the stored (still-encrypted) value, so presence is\n\t\t\t// reported without decrypting anything.\n\t\t\tservers: servers.map((s, i) => ({ ...s, hasApiKey: !!all.servers[i].apiKey })),\n\t\t\tdefaultServerId: all.defaultServerId,\n\t\t\torgDefaults: all.orgDefaults\n\t\t};\n\t\treturn opts.scopeToOrgId ? scopeConfigToOrg(config, opts.scopeToOrgId) : config;\n\t}\n\n\t/**\n\t * One server's decrypted key. The local store reads the whole file anyway, so\n\t * this exists for interface parity with Supabase (where it saves a table scan\n\t * plus N decrypts) — and it still avoids decrypting the other servers' keys.\n\t */\n\tasync getServerApiKey(_ctx: RequestContext, serverId: string): Promise<string | undefined> {\n\t\tconst all = await this.readAll();\n\t\tconst server = all.servers.find((s) => s.id === serverId);\n\t\tif (!server?.apiKey) return undefined;\n\t\treturn this.decryptApiKeys([server])[0].apiKey;\n\t}\n\n\tasync savePlatformServers(\n\t\t_ctx: RequestContext,\n\t\tservers: ComputeServerConfig[],\n\t\tdefaultServerId: string | undefined\n\t): Promise<void> {\n\t\tawait withFileLock(this.configFilePath, async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst orgRows = all.servers.filter(isOrgServer);\n\t\t\tconst incoming = servers.filter(isPlatformServer);\n\t\t\tassertIdsFree(incoming, orgRows);\n\t\t\tconst platformRows = this.encryptApiKeys(incoming);\n\n\t\t\tawait writeJsonFile<OnDiskShape>(this.configFilePath, {\n\t\t\t\tservers: [...platformRows, ...orgRows],\n\t\t\t\tdefaultServerId,\n\t\t\t\torgDefaults: all.orgDefaults\n\t\t\t});\n\t\t});\n\t}\n\n\tasync saveOrgServers(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\tservers: ComputeServerConfig[],\n\t\tdefaultServerId?: string | null\n\t): Promise<void> {\n\t\tawait withFileLock(this.configFilePath, async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst platformRows = all.servers.filter(isPlatformServer);\n\t\t\tconst otherOrgRows = all.servers.filter((s) => isOrgServer(s) && s.ownerOrgId !== orgId);\n\t\t\tconst incoming = servers.filter(isOrgServer).map((s) => ({ ...s, ownerOrgId: orgId }));\n\t\t\tassertIdsFree(incoming, [...platformRows, ...otherOrgRows]);\n\t\t\tconst thisOrgRows = this.encryptApiKeys(incoming);\n\n\t\t\tconst orgDefaults = { ...(all.orgDefaults ?? {}) };\n\t\t\tif (defaultServerId === null) {\n\t\t\t\tdelete orgDefaults[orgId];\n\t\t\t} else if (typeof defaultServerId === 'string') {\n\t\t\t\torgDefaults[orgId] = defaultServerId;\n\t\t\t}\n\n\t\t\tawait writeJsonFile<OnDiskShape>(this.configFilePath, {\n\t\t\t\tservers: [...platformRows, ...otherOrgRows, ...thisOrgRows],\n\t\t\t\tdefaultServerId: all.defaultServerId,\n\t\t\t\torgDefaults\n\t\t\t});\n\t\t});\n\t}\n\n\tasync setOrgDefault(_ctx: RequestContext, orgId: string, serverId: string | null): Promise<void> {\n\t\tawait withFileLock(this.configFilePath, async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst orgDefaults = { ...(all.orgDefaults ?? {}) };\n\t\t\tif (serverId === null) {\n\t\t\t\tdelete orgDefaults[orgId];\n\t\t\t} else {\n\t\t\t\torgDefaults[orgId] = serverId;\n\t\t\t}\n\t\t\tawait writeJsonFile<OnDiskShape>(this.configFilePath, { ...all, orgDefaults });\n\t\t});\n\t}\n\n\tasync deleteByOrg(_ctx: RequestContext, orgId: string): Promise<void> {\n\t\tawait withFileLock(this.configFilePath, async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst remaining = all.servers.filter((s) => !(isOrgServer(s) && s.ownerOrgId === orgId));\n\n\t\t\tconst cleaned: ComputeServerConfig[] = remaining.map((s) => {\n\t\t\t\tif (!isPlatformServer(s)) return s;\n\t\t\t\tif (s.sharedWith === 'all') return s;\n\t\t\t\tif (!s.sharedWith.includes(orgId)) return s;\n\t\t\t\tconst next: PlatformComputeServer = {\n\t\t\t\t\t...s,\n\t\t\t\t\tsharedWith: s.sharedWith.filter((id) => id !== orgId)\n\t\t\t\t};\n\t\t\t\treturn next;\n\t\t\t});\n\n\t\t\tconst orgDefaults = { ...(all.orgDefaults ?? {}) };\n\t\t\tconst hadDefault = orgId in orgDefaults;\n\t\t\tdelete orgDefaults[orgId];\n\n\t\t\tconst changed =\n\t\t\t\tcleaned.length !== all.servers.length ||\n\t\t\t\thadDefault ||\n\t\t\t\tcleaned.some((c, i) => c !== all.servers[i]);\n\t\t\tif (!changed) return;\n\n\t\t\tawait writeJsonFile<OnDiskShape>(this.configFilePath, {\n\t\t\t\tservers: cleaned,\n\t\t\t\tdefaultServerId: all.defaultServerId,\n\t\t\t\torgDefaults\n\t\t\t});\n\t\t});\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tIPlatformProjectGrantStore,\n\tPlatformProjectGrant,\n\tRequestContext\n} from '@selvajs/platform';\nimport { ERASED_ACTOR_ID, ProviderError } from '@selvajs/platform';\nimport { readJsonFile, withFileLock, writeJsonFile } from './fsJson.js';\n\ninterface OnDiskShape {\n\tgrants: PlatformProjectGrant[];\n}\n\nconst empty = (): OnDiskShape => ({ grants: [] });\n\nexport class LocalPlatformProjectGrantStore implements IPlatformProjectGrantStore {\n\tprivate readonly filePath: string;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalPlatformProjectGrantStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalPlatformProjectGrantStore(\n\t\t\tpath.join(env.DATA_PATH, 'platform-project-grants.json')\n\t\t);\n\t}\n\n\tconstructor(filePath: string) {\n\t\tthis.filePath = filePath;\n\t}\n\n\tprivate async read(): Promise<OnDiskShape> {\n\t\treturn readJsonFile<OnDiskShape>(this.filePath, empty());\n\t}\n\n\tprivate async write(data: OnDiskShape): Promise<void> {\n\t\tawait writeJsonFile(this.filePath, data);\n\t}\n\n\tprivate locked<T>(fn: () => Promise<T>): Promise<T> {\n\t\treturn withFileLock(this.filePath, fn);\n\t}\n\n\tasync listByProject(_ctx: RequestContext, projectId: string): Promise<PlatformProjectGrant[]> {\n\t\tconst { grants } = await this.read();\n\t\treturn grants.filter((g) => g.projectId === projectId);\n\t}\n\n\tasync listByProjects(\n\t\t_ctx: RequestContext,\n\t\tprojectIds: readonly string[]\n\t): Promise<Map<string, PlatformProjectGrant[]>> {\n\t\tconst { grants } = await this.read();\n\t\tconst result = new Map(projectIds.map((id) => [id, [] as PlatformProjectGrant[]]));\n\t\tfor (const g of grants) result.get(g.projectId)?.push(g);\n\t\treturn result;\n\t}\n\n\tasync create(_ctx: RequestContext, grant: PlatformProjectGrant): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst data = await this.read();\n\t\t\tif (data.grants.some((g) => g.id === grant.id)) {\n\t\t\t\tthrow new ProviderError(`Grant '${grant.id}' already exists`, 409);\n\t\t\t}\n\t\t\tconst duplicate = data.grants.find(\n\t\t\t\t(g) =>\n\t\t\t\t\tg.projectId === grant.projectId &&\n\t\t\t\t\tg.granteeType === grant.granteeType &&\n\t\t\t\t\tg.granteeId === grant.granteeId\n\t\t\t);\n\t\t\tif (duplicate) {\n\t\t\t\tthrow new ProviderError(\n\t\t\t\t\t`A grant for this ${grant.granteeType} already exists on this project`,\n\t\t\t\t\t409\n\t\t\t\t);\n\t\t\t}\n\t\t\tdata.grants.push(grant);\n\t\t\tawait this.write(data);\n\t\t});\n\t}\n\n\tasync delete(_ctx: RequestContext, id: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst data = await this.read();\n\t\t\tconst idx = data.grants.findIndex((g) => g.id === id);\n\t\t\tif (idx === -1) throw new ProviderError(`Grant '${id}' not found`, 404);\n\t\t\tdata.grants.splice(idx, 1);\n\t\t\tawait this.write(data);\n\t\t});\n\t}\n\n\tasync deleteByProject(_ctx: RequestContext, projectId: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst data = await this.read();\n\t\t\tconst before = data.grants.length;\n\t\t\tdata.grants = data.grants.filter((g) => g.projectId !== projectId);\n\t\t\tif (data.grants.length !== before) await this.write(data);\n\t\t});\n\t}\n\n\tasync deleteByGranteeOrg(_ctx: RequestContext, orgId: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst data = await this.read();\n\t\t\tconst before = data.grants.length;\n\t\t\tdata.grants = data.grants.filter((g) => !(g.granteeType === 'org' && g.granteeId === orgId));\n\t\t\tif (data.grants.length !== before) await this.write(data);\n\t\t});\n\t}\n\n\t/** A user grant is the user's own, so it goes with them. */\n\tasync eraseUser(userId: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst data = await this.read();\n\t\t\tdata.grants = data.grants\n\t\t\t\t.filter((g) => !(g.granteeType === 'user' && g.granteeId === userId))\n\t\t\t\t.map((g) => (g.createdBy === userId ? { ...g, createdBy: ERASED_ACTOR_ID } : g));\n\t\t\tawait this.write(data);\n\t\t});\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tIOrgStore,\n\tIInviteStore,\n\tIApiTokenStore,\n\tIComputeServerStore,\n\tIDefinitionStore,\n\tIPlatformProjectGrantStore,\n\tIEventSink,\n\tOrganization,\n\tOrgRole,\n\tOrgPermission,\n\tOrgMember,\n\tProject,\n\tProjectMember,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport {\n\tDEFAULT_ORG_PERMISSIONS,\n\tERASED_ACTOR_ID,\n\tProviderError,\n\tauditUpdate,\n\tauditSoftDelete,\n\tactorOf,\n\tNoopEventSink\n} from '@selvajs/platform';\nimport { paginate, applyOrder } from './pagination.js';\nimport { CachedJsonFile } from './fsJson.js';\nimport { LocalInviteStore } from './LocalInviteStore.js';\nimport { LocalApiTokenStore } from './LocalApiTokenStore.js';\nimport { LocalComputeServerStore } from './LocalComputeServerStore.js';\nimport { LocalPlatformProjectGrantStore } from './LocalPlatformProjectGrantStore.js';\n\n/** Shape of the on-disk local-org.json file. */\nexport interface LocalOrgStoreData {\n\torgs: Organization[];\n\tprojects: Project[];\n\torgMembers: OrgMember[];\n\tprojectMembers: ProjectMember[];\n}\n\n/** Data-access-layer filter: row is live (not soft-deleted). */\nfunction isLive<T extends { deletedAt?: string | null }>(row: T): boolean {\n\treturn row.deletedAt == null;\n}\n\n/**\n * Shared by LocalOrgStore and LocalProjectStore — one instance so all\n * reads/writes go through one cache and one atomic write path.\n *\n */\nexport class LocalOrgStoreLoader {\n\treadonly storePath: string;\n\tprivate readonly file: CachedJsonFile<LocalOrgStoreData>;\n\n\tconstructor(dataPath: string) {\n\t\tthis.storePath = path.join(dataPath, 'local-org.json');\n\t\tthis.file = new CachedJsonFile(this.storePath, () => ({\n\t\t\torgs: [],\n\t\t\tprojects: [],\n\t\t\torgMembers: [],\n\t\t\tprojectMembers: []\n\t\t}));\n\t}\n\n\tget(): Promise<LocalOrgStoreData> {\n\t\treturn this.file.get();\n\t}\n\n\twrite(store: LocalOrgStoreData): Promise<void> {\n\t\treturn this.file.write(store);\n\t}\n}\n\nexport interface LocalOrgStoreOptions {\n\tloader: LocalOrgStoreLoader;\n\t/**\n\t * Sibling stores for the `deleteOrg` cascade — invites, API tokens, compute\n\t * config, and grants live in separate JSON files the loader can't reach. Required, not\n\t * optional: an unwired cascade silently leaks operational data.\n\t */\n\tinvites: IInviteStore;\n\tapiTokens: IApiTokenStore;\n\tcomputeServer: IComputeServerStore;\n\tgrants: IPlatformProjectGrantStore;\n\tevents?: IEventSink;\n}\n\nexport class LocalOrgStore implements IOrgStore {\n\tprivate readonly loader: LocalOrgStoreLoader;\n\tprivate definitions?: IDefinitionStore;\n\tprivate readonly events: IEventSink;\n\tprivate readonly invites: IInviteStore;\n\tprivate readonly apiTokens: IApiTokenStore;\n\tprivate readonly computeServer: IComputeServerStore;\n\tprivate readonly grants: IPlatformProjectGrantStore;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalOrgStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalOrgStore({\n\t\t\tloader: new LocalOrgStoreLoader(env.DATA_PATH),\n\t\t\tinvites: LocalInviteStore.fromEnv(env),\n\t\t\tapiTokens: LocalApiTokenStore.fromEnv(env),\n\t\t\tcomputeServer: LocalComputeServerStore.fromEnv(env),\n\t\t\tgrants: LocalPlatformProjectGrantStore.fromEnv(env)\n\t\t});\n\t}\n\n\tconstructor(opts: LocalOrgStoreOptions) {\n\t\tthis.loader = opts.loader;\n\t\tthis.invites = opts.invites;\n\t\tthis.apiTokens = opts.apiTokens;\n\t\tthis.computeServer = opts.computeServer;\n\t\tthis.grants = opts.grants;\n\t\tthis.events = opts.events ?? new NoopEventSink();\n\t}\n\n\t/** A setter rather than an option: the definition store is built after this one. */\n\tsetDefinitionProvider(definitions: IDefinitionStore): void {\n\t\tthis.definitions = definitions;\n\t}\n\n\t/** Removes the user's membership rows, soft-deleted ones too, and their name elsewhere. */\n\tasync eraseUser(userId: string): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst erased = <T extends { updatedBy?: string }>(row: T): T =>\n\t\t\trow.updatedBy === userId ? { ...row, updatedBy: ERASED_ACTOR_ID } : row;\n\t\tconst erasedOwner = <T extends { ownerId: string; createdBy: string; updatedBy: string }>(\n\t\t\trow: T\n\t\t): T =>\n\t\t\terased({\n\t\t\t\t...row,\n\t\t\t\townerId: row.ownerId === userId ? ERASED_ACTOR_ID : row.ownerId,\n\t\t\t\tcreatedBy: row.createdBy === userId ? ERASED_ACTOR_ID : row.createdBy\n\t\t\t});\n\t\tstore.orgs = store.orgs.map(erasedOwner);\n\t\tstore.projects = store.projects.map(erasedOwner);\n\t\tstore.orgMembers = store.orgMembers.filter((m) => m.userId !== userId).map(erased);\n\t\tstore.projectMembers = store.projectMembers.filter((m) => m.userId !== userId).map(erased);\n\t\tawait this.loader.write(store);\n\t}\n\n\tasync listOrgs(_ctx: RequestContext, opts?: ListOptions): Promise<Page<Organization>> {\n\t\tconst { orgs } = await this.loader.get();\n\t\treturn paginate(applyOrder(orgs.filter(isLive), opts), opts);\n\t}\n\n\tasync getOrg(_ctx: RequestContext, id: string): Promise<Organization | null> {\n\t\tconst { orgs } = await this.loader.get();\n\t\tconst o = orgs.find((o) => o.id === id);\n\t\treturn o && isLive(o) ? o : null;\n\t}\n\n\tasync getOrgBySlug(_ctx: RequestContext, slug: string): Promise<Organization | null> {\n\t\tconst { orgs } = await this.loader.get();\n\t\tconst o = orgs.find((o) => o.slug === slug);\n\t\treturn o && isLive(o) ? o : null;\n\t}\n\n\tasync createOrg(ctx: RequestContext, org: Organization): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tif (store.orgs.some((o) => o.id === org.id && isLive(o))) {\n\t\t\tthrow new ProviderError(`Org '${org.id}' already exists`, 409);\n\t\t}\n\t\tif (store.orgs.some((o) => o.slug === org.slug && isLive(o))) {\n\t\t\tthrow new ProviderError(`Org slug '${org.slug}' already in use`, 409);\n\t\t}\n\t\tstore.orgs.push({ ...org, deletedAt: null });\n\t\tconst now = new Date().toISOString();\n\t\tstore.orgMembers.push({\n\t\t\torgId: org.id,\n\t\t\tuserId: org.ownerId,\n\t\t\trole: 'owner',\n\t\t\tpermissions: [...DEFAULT_ORG_PERMISSIONS.owner],\n\t\t\tjoinedAt: now,\n\t\t\t...auditUpdate(ctx, org.ownerId),\n\t\t\tdeletedAt: null\n\t\t});\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({ type: 'org.created', orgId: org.id, ...actorOf(ctx) });\n\t}\n\n\tasync updateOrg(\n\t\tctx: RequestContext,\n\t\tid: string,\n\t\tpatch: Partial<Pick<Organization, 'name' | 'slug' | 'assets'>>\n\t): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst idx = store.orgs.findIndex((o) => o.id === id && isLive(o));\n\t\tif (idx === -1) throw new ProviderError(`Org '${id}' not found`, 404);\n\t\tif (patch.slug && patch.slug !== store.orgs[idx].slug) {\n\t\t\tif (store.orgs.some((o) => o.id !== id && o.slug === patch.slug && isLive(o))) {\n\t\t\t\tthrow new ProviderError(`Org slug '${patch.slug}' already in use`, 409);\n\t\t\t}\n\t\t}\n\t\tstore.orgs[idx] = {\n\t\t\t...store.orgs[idx],\n\t\t\t...patch,\n\t\t\t...auditUpdate(ctx, store.orgs[idx].updatedBy ?? store.orgs[idx].ownerId)\n\t\t};\n\t\tawait this.loader.write(store);\n\t}\n\n\tasync deleteOrg(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst idx = store.orgs.findIndex((o) => o.id === id && isLive(o));\n\t\tif (idx === -1) throw new ProviderError(`Org '${id}' not found`, 404);\n\t\tconst stamp = auditSoftDelete(ctx, store.orgs[idx].updatedBy ?? store.orgs[idx].ownerId);\n\t\tstore.orgs[idx] = { ...store.orgs[idx], ...stamp };\n\t\tstore.orgMembers = store.orgMembers.map((m) =>\n\t\t\tm.orgId === id && isLive(m) ? { ...m, ...stamp } : m\n\t\t);\n\t\tconst orgProjectIds = new Set(\n\t\t\tstore.projects.filter((p) => p.orgId === id && isLive(p)).map((p) => p.id)\n\t\t);\n\t\tstore.projects = store.projects.map((p) =>\n\t\t\tp.orgId === id && isLive(p) ? { ...p, ...stamp } : p\n\t\t);\n\t\tstore.projectMembers = store.projectMembers.map((m) =>\n\t\t\torgProjectIds.has(m.projectId) && isLive(m) ? { ...m, ...stamp } : m\n\t\t);\n\t\tawait this.loader.write(store);\n\t\t// Invites and compute config are operational, not user data, so they\n\t\t// hard-delete rather than soft-delete — no audit trail to preserve.\n\t\tawait this.invites.deleteByOrg(ctx, id);\n\t\tawait this.apiTokens.deleteByOrg(ctx, id);\n\t\tawait this.computeServer.deleteByOrg(ctx, id);\n\t\tif (this.definitions) {\n\t\t\tfor (const projectId of orgProjectIds) {\n\t\t\t\tawait this.definitions.deleteByProject(ctx, projectId);\n\t\t\t}\n\t\t}\n\t\t// User grants survive — they're identity-scoped, not org-scoped.\n\t\tfor (const projectId of orgProjectIds) {\n\t\t\tawait this.grants.deleteByProject(ctx, projectId);\n\t\t}\n\t\tawait this.grants.deleteByGranteeOrg(ctx, id);\n\t\tawait this.events.emit({ type: 'org.deleted', orgId: id, ...actorOf(ctx) });\n\t}\n\n\tasync listOrgMembers(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<OrgMember>> {\n\t\tconst { orgMembers } = await this.loader.get();\n\t\treturn paginate(\n\t\t\torgMembers.filter((m) => m.orgId === orgId && isLive(m)),\n\t\t\topts\n\t\t);\n\t}\n\n\tasync getOrgMember(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string\n\t): Promise<OrgMember | null> {\n\t\tconst { orgMembers } = await this.loader.get();\n\t\tconst m = orgMembers.find((m) => m.orgId === orgId && m.userId === userId);\n\t\treturn m && isLive(m) ? m : null;\n\t}\n\n\tasync countOrgMembers(\n\t\t_ctx: RequestContext,\n\t\torgIds: readonly string[]\n\t): Promise<Map<string, number>> {\n\t\tconst { orgMembers } = await this.loader.get();\n\t\tconst counts = new Map<string, number>(orgIds.map((id) => [id, 0]));\n\t\tfor (const m of orgMembers) {\n\t\t\tconst n = counts.get(m.orgId);\n\t\t\tif (n !== undefined && isLive(m)) counts.set(m.orgId, n + 1);\n\t\t}\n\t\treturn counts;\n\t}\n\n\tasync getOrgMembersFor(\n\t\t_ctx: RequestContext,\n\t\torgIds: readonly string[],\n\t\tuserId: string\n\t): Promise<Map<string, OrgMember | null>> {\n\t\tconst { orgMembers } = await this.loader.get();\n\t\tconst byOrgId = new Map(\n\t\t\torgMembers.filter((m) => m.userId === userId && isLive(m)).map((m) => [m.orgId, m])\n\t\t);\n\t\treturn new Map(orgIds.map((id) => [id, byOrgId.get(id) ?? null]));\n\t}\n\n\tasync findUserMembership(\n\t\t_ctx: RequestContext,\n\t\tuserId: string\n\t): Promise<{ org: Organization; member: OrgMember } | null> {\n\t\t// Picks the first live membership; ordering follows insertion order in\n\t\t// the JSON file, stable across reads.\n\t\tconst store = await this.loader.get();\n\t\tconst member = store.orgMembers.find((m) => m.userId === userId && isLive(m));\n\t\tif (!member) return null;\n\t\tconst org = store.orgs.find((o) => o.id === member.orgId);\n\t\t// A membership pointing at a soft-deleted org counts as gone, same as the\n\t\t// SQL adapter gets via FK + RLS on `orgs.deleted_at`.\n\t\tif (!org || !isLive(org)) return null;\n\t\treturn { org, member };\n\t}\n\n\tasync addOrgMember(ctx: RequestContext, member: OrgMember): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\t// Reactivate a prior soft-deleted row rather than piling rows up.\n\t\tconst existing = store.orgMembers.find(\n\t\t\t(m) => m.orgId === member.orgId && m.userId === member.userId\n\t\t);\n\t\tif (existing) {\n\t\t\tObject.assign(existing, member, {\n\t\t\t\t...auditUpdate(ctx, member.userId),\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t} else {\n\t\t\tstore.orgMembers.push({ ...member, deletedAt: null });\n\t\t}\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.added',\n\t\t\torgId: member.orgId,\n\t\t\tuserId: member.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateOrgMemberRole(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string,\n\t\trole: OrgRole\n\t): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst m = store.orgMembers.find((m) => m.orgId === orgId && m.userId === userId && isLive(m));\n\t\tif (!m) throw new ProviderError(`Org member '${userId}' not found`, 404);\n\t\tm.role = role;\n\t\t// Resets permissions to the role's defaults. To keep a custom set, call\n\t\t// updateOrgMemberPermissions after this.\n\t\tm.permissions = [...DEFAULT_ORG_PERMISSIONS[role]];\n\t\tObject.assign(m, auditUpdate(ctx, m.updatedBy));\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.role_changed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\trole,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateOrgMemberPermissions(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string,\n\t\tpermissions: readonly OrgPermission[]\n\t): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst m = store.orgMembers.find((m) => m.orgId === orgId && m.userId === userId && isLive(m));\n\t\tif (!m) throw new ProviderError(`Org member '${userId}' not found`, 404);\n\t\tm.permissions = [...permissions];\n\t\tObject.assign(m, auditUpdate(ctx, m.updatedBy));\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.permissions_changed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\tpermissions: [...permissions],\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync removeOrgMember(ctx: RequestContext, orgId: string, userId: string): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst m = store.orgMembers.find((m) => m.orgId === orgId && m.userId === userId && isLive(m));\n\t\tif (!m) throw new ProviderError(`Org member '${userId}' not found`, 404);\n\t\tconst stamp = auditSoftDelete(ctx, m.updatedBy);\n\t\tObject.assign(m, stamp);\n\n\t\t// Losing org membership ends every project membership in that org, so\n\t\t// \"members ⊂ org members\" stays true without reads having to re-check it.\n\t\tconst projectIdsInOrg = new Set(\n\t\t\tstore.projects.filter((p) => p.orgId === orgId).map((p) => p.id)\n\t\t);\n\t\tstore.projectMembers = store.projectMembers.map((pm) =>\n\t\t\tpm.userId === userId && projectIdsInOrg.has(pm.projectId) && isLive(pm)\n\t\t\t\t? { ...pm, ...stamp }\n\t\t\t\t: pm\n\t\t);\n\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.removed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n","import type {\n\tIProjectStore,\n\tIPlatformProjectGrantStore,\n\tIDefinitionStore,\n\tIEventSink,\n\tProject,\n\tProjectRole,\n\tProjectMember,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport {\n\tProviderError,\n\tauditUpdate,\n\tauditSoftDelete,\n\tactorOf,\n\tNoopEventSink\n} from '@selvajs/platform';\nimport { paginate, applyOrder } from './pagination.js';\nimport type { LocalOrgStoreLoader } from './LocalOrgStore.js';\n\n/** Data-access-layer filter — never let a soft-deleted row surface to callers. */\nfunction isLive<T extends { deletedAt?: string | null }>(row: T): boolean {\n\treturn row.deletedAt == null;\n}\n\nexport interface LocalProjectStoreOptions {\n\tloader: LocalOrgStoreLoader;\n\t/**\n\t * Sibling store for the `deleteProject` cascade — grants live in a separate\n\t * JSON file the loader can't reach. Required, not optional: an unwired\n\t * cascade leaks grants on platform projects after deletion.\n\t */\n\tgrants: IPlatformProjectGrantStore;\n\tevents?: IEventSink;\n}\n\nexport class LocalProjectStore implements IProjectStore {\n\tprivate readonly loader: LocalOrgStoreLoader;\n\tprivate readonly events: IEventSink;\n\tprivate readonly grants: IPlatformProjectGrantStore;\n\tprivate definitions?: IDefinitionStore;\n\n\tconstructor(opts: LocalProjectStoreOptions) {\n\t\tthis.loader = opts.loader;\n\t\tthis.grants = opts.grants;\n\t\tthis.events = opts.events ?? new NoopEventSink();\n\t}\n\n\t/**\n\t * Wires the definition store for the `deleteProject` cascade. A setter, not\n\t * a constructor param, because the composition root builds this store\n\t * before the definition store (whose `setProjectProvider` depends on this\n\t * one). Unwired, deleted projects keep leaking their definitions into the\n\t * library/public listings.\n\t */\n\tsetDefinitionProvider(definitions: IDefinitionStore): void {\n\t\tthis.definitions = definitions;\n\t}\n\n\tasync listProjects(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<Project>> {\n\t\tconst { projects } = await this.loader.get();\n\t\treturn paginate(\n\t\t\tapplyOrder(\n\t\t\t\tprojects.filter((p) => p.orgId === orgId && isLive(p)),\n\t\t\t\topts\n\t\t\t),\n\t\t\topts\n\t\t);\n\t}\n\n\tasync getProject(_ctx: RequestContext, id: string): Promise<Project | null> {\n\t\tconst { projects } = await this.loader.get();\n\t\tconst p = projects.find((p) => p.id === id);\n\t\treturn p && isLive(p) ? p : null;\n\t}\n\n\tasync getProjectBySlug(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\tslug: string\n\t): Promise<Project | null> {\n\t\tconst { projects } = await this.loader.get();\n\t\tconst p = projects.find((p) => p.orgId === orgId && p.slug === slug);\n\t\treturn p && isLive(p) ? p : null;\n\t}\n\n\tasync createProject(ctx: RequestContext, project: Project): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tif (!store.orgs.some((o) => o.id === project.orgId && isLive(o))) {\n\t\t\tthrow new ProviderError(`Org '${project.orgId}' not found`, 404);\n\t\t}\n\t\tif (store.projects.some((p) => p.id === project.id && isLive(p))) {\n\t\t\tthrow new ProviderError(`Project '${project.id}' already exists`, 409);\n\t\t}\n\t\tconst nameKey = project.name.toLowerCase();\n\t\tif (\n\t\t\tstore.projects.some(\n\t\t\t\t(p) => p.orgId === project.orgId && isLive(p) && p.name.toLowerCase() === nameKey\n\t\t\t)\n\t\t) {\n\t\t\tthrow new ProviderError('projects_org_name_unique: project name already in use', 409);\n\t\t}\n\t\tif (\n\t\t\tstore.projects.some((p) => p.orgId === project.orgId && isLive(p) && p.slug === project.slug)\n\t\t) {\n\t\t\tthrow new ProviderError('projects_org_id_slug_key: project slug already in use', 409);\n\t\t}\n\t\tstore.projects.push({ ...project, deletedAt: null });\n\t\tstore.projectMembers.push({\n\t\t\tprojectId: project.id,\n\t\t\tuserId: project.ownerId,\n\t\t\trole: 'owner',\n\t\t\tjoinedAt: project.createdAt,\n\t\t\tupdatedAt: project.createdAt,\n\t\t\tupdatedBy: project.ownerId,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project.created',\n\t\t\tprojectId: project.id,\n\t\t\torgId: project.orgId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateProject(\n\t\tctx: RequestContext,\n\t\tid: string,\n\t\tpatch: Partial<\n\t\t\tPick<Project, 'name' | 'slug' | 'description' | 'visibility' | 'autoJoinOnUpload'>\n\t\t>\n\t): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst idx = store.projects.findIndex((p) => p.id === id && isLive(p));\n\t\tif (idx === -1) throw new ProviderError(`Project '${id}' not found`, 404);\n\n\t\tconst current = store.projects[idx];\n\n\t\tif (patch.name && patch.name.toLowerCase() !== current.name.toLowerCase()) {\n\t\t\tconst nameKey = patch.name.toLowerCase();\n\t\t\tif (\n\t\t\t\tstore.projects.some(\n\t\t\t\t\t(p) =>\n\t\t\t\t\t\tp.orgId === current.orgId &&\n\t\t\t\t\t\tp.id !== id &&\n\t\t\t\t\t\tisLive(p) &&\n\t\t\t\t\t\tp.name.toLowerCase() === nameKey\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow new ProviderError('projects_org_name_unique: project name already in use', 409);\n\t\t\t}\n\t\t}\n\n\t\tif (patch.slug && patch.slug !== current.slug) {\n\t\t\tif (\n\t\t\t\tstore.projects.some(\n\t\t\t\t\t(p) => p.orgId === current.orgId && p.slug === patch.slug && p.id !== id && isLive(p)\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow new ProviderError('projects_org_id_slug_key: project slug already in use', 409);\n\t\t\t}\n\t\t}\n\n\t\tstore.projects[idx] = {\n\t\t\t...current,\n\t\t\t...patch,\n\t\t\t...auditUpdate(ctx, current.updatedBy ?? current.ownerId)\n\t\t};\n\t\tawait this.loader.write(store);\n\t}\n\n\tasync deleteProject(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst idx = store.projects.findIndex((p) => p.id === id && isLive(p));\n\t\tif (idx === -1) throw new ProviderError(`Project '${id}' not found`, 404);\n\t\tconst stamp = auditSoftDelete(\n\t\t\tctx,\n\t\t\tstore.projects[idx].updatedBy ?? store.projects[idx].ownerId\n\t\t);\n\t\tstore.projects[idx] = { ...store.projects[idx], ...stamp };\n\t\tstore.projectMembers = store.projectMembers.map((m) =>\n\t\t\tm.projectId === id && isLive(m) ? { ...m, ...stamp } : m\n\t\t);\n\t\tawait this.loader.write(store);\n\t\t// A deleted project must stop serving its definitions — they surface in\n\t\t// library/public listings keyed on the definition row, independent of\n\t\t// the project. Supabase does the same cascade.\n\t\tawait this.definitions?.deleteByProject(ctx, id);\n\t\t// Grants have no soft-delete column, so this hard-deletes them.\n\t\tawait this.grants.deleteByProject(ctx, id);\n\t\tawait this.events.emit({ type: 'project.deleted', projectId: id, ...actorOf(ctx) });\n\t}\n\n\tasync reactivateProject(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tslug: string\n\t): Promise<Project | null> {\n\t\tconst store = await this.loader.get();\n\t\tconst idx = store.projects.findIndex((p) => p.orgId === orgId && p.slug === slug && !isLive(p));\n\t\tif (idx === -1) return null;\n\n\t\tconst now = new Date().toISOString();\n\t\tstore.projects[idx] = { ...store.projects[idx], deletedAt: null, updatedAt: now };\n\n\t\tconst ownerId = store.projects[idx].ownerId;\n\t\tconst pmIdx = store.projectMembers.findIndex(\n\t\t\t(m) => m.projectId === store.projects[idx].id && m.userId === ownerId && !isLive(m)\n\t\t);\n\t\tif (pmIdx !== -1) {\n\t\t\tstore.projectMembers[pmIdx] = {\n\t\t\t\t...store.projectMembers[pmIdx],\n\t\t\t\tdeletedAt: null,\n\t\t\t\tupdatedAt: now\n\t\t\t};\n\t\t}\n\n\t\tawait this.loader.write(store);\n\t\tconst project = { ...store.projects[idx] };\n\t\tawait this.events.emit({\n\t\t\ttype: 'project.created',\n\t\t\tprojectId: project.id,\n\t\t\torgId: project.orgId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t\treturn project;\n\t}\n\n\tasync listProjectMembers(\n\t\t_ctx: RequestContext,\n\t\tprojectId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<ProjectMember>> {\n\t\tconst { projectMembers } = await this.loader.get();\n\t\treturn paginate(\n\t\t\tprojectMembers.filter((m) => m.projectId === projectId && isLive(m)),\n\t\t\topts\n\t\t);\n\t}\n\n\tasync getProjectMember(\n\t\t_ctx: RequestContext,\n\t\tprojectId: string,\n\t\tuserId: string\n\t): Promise<ProjectMember | null> {\n\t\tconst { projectMembers } = await this.loader.get();\n\t\tconst m = projectMembers.find((m) => m.projectId === projectId && m.userId === userId);\n\t\treturn m && isLive(m) ? m : null;\n\t}\n\n\tasync getProjectMembersFor(\n\t\t_ctx: RequestContext,\n\t\tprojectIds: readonly string[],\n\t\tuserId: string\n\t): Promise<Map<string, ProjectMember | null>> {\n\t\tconst { projectMembers } = await this.loader.get();\n\t\tconst byProjectId = new Map(\n\t\t\tprojectMembers.filter((m) => m.userId === userId && isLive(m)).map((m) => [m.projectId, m])\n\t\t);\n\t\treturn new Map(projectIds.map((id) => [id, byProjectId.get(id) ?? null]));\n\t}\n\n\tasync countProjectMembers(\n\t\t_ctx: RequestContext,\n\t\tprojectIds: readonly string[]\n\t): Promise<Map<string, number>> {\n\t\tconst { projectMembers } = await this.loader.get();\n\t\tconst counts = new Map<string, number>(projectIds.map((id) => [id, 0]));\n\t\tfor (const m of projectMembers) {\n\t\t\tconst n = counts.get(m.projectId);\n\t\t\tif (n !== undefined && isLive(m)) counts.set(m.projectId, n + 1);\n\t\t}\n\t\treturn counts;\n\t}\n\n\tasync addProjectMember(ctx: RequestContext, member: ProjectMember): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\t// Reactivate a prior soft-deleted row rather than piling rows up.\n\t\tconst existing = store.projectMembers.find(\n\t\t\t(m) => m.projectId === member.projectId && m.userId === member.userId\n\t\t);\n\t\tif (existing) {\n\t\t\tObject.assign(existing, member, {\n\t\t\t\t...auditUpdate(ctx, member.userId),\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t} else {\n\t\t\tconst stamp = auditUpdate(ctx, member.userId);\n\t\t\tstore.projectMembers.push({\n\t\t\t\t...member,\n\t\t\t\tupdatedAt: member.updatedAt ?? stamp.updatedAt,\n\t\t\t\tupdatedBy: member.updatedBy ?? stamp.updatedBy,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t}\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.added',\n\t\t\tprojectId: member.projectId,\n\t\t\tuserId: member.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateProjectMemberRole(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\tuserId: string,\n\t\trole: ProjectRole\n\t): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst m = store.projectMembers.find(\n\t\t\t(m) => m.projectId === projectId && m.userId === userId && isLive(m)\n\t\t);\n\t\tif (!m) throw new ProviderError(`Project member '${userId}' not found`, 404);\n\t\tm.role = role;\n\t\tObject.assign(m, auditUpdate(ctx, m.updatedBy));\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.role_changed',\n\t\t\tprojectId,\n\t\t\tuserId,\n\t\t\trole,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync removeProjectMember(ctx: RequestContext, projectId: string, userId: string): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst m = store.projectMembers.find(\n\t\t\t(m) => m.projectId === projectId && m.userId === userId && isLive(m)\n\t\t);\n\t\tif (!m) return;\n\t\tObject.assign(m, auditSoftDelete(ctx, m.updatedBy));\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.removed',\n\t\t\tprojectId,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tIDefinitionStore,\n\tIProjectStore,\n\tIEventSink,\n\tDefinitionRecord,\n\tDefinitionRecordPatch,\n\tDefinitionVersion,\n\tRequestContext,\n\tDefinitionListOptions,\n\tListOptions,\n\tPage,\n\tUISchema,\n\tDocumentInventory,\n\tInventorySummary\n} from '@selvajs/platform';\nimport {\n\tERASED_ACTOR_ID,\n\tProviderError,\n\tauditUpdate,\n\tauditSoftDelete,\n\tactorOf,\n\tNoopEventSink\n} from '@selvajs/platform';\nimport { paginate, applyOrder } from './pagination.js';\nimport { CachedJsonFile } from './fsJson.js';\n\ninterface DefinitionsConfig {\n\tdefinitions: Record<string, DefinitionRecord>;\n\tdefinitionVersions: Record<string, DefinitionVersion>;\n}\n\n// `readJsonFile` returns its fallback by reference when the file is missing,\n// so a shared singleton here would let one read's mutations pollute the next.\nconst empty = (): DefinitionsConfig => ({ definitions: {}, definitionVersions: {} });\n\nexport class LocalDefinitionStore implements IDefinitionStore {\n\tprivate readonly file: CachedJsonFile<DefinitionsConfig>;\n\tprivate readonly events: IEventSink;\n\tprivate projectProvider?: IProjectStore;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalDefinitionStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalDefinitionStore(env.DATA_PATH);\n\t}\n\n\tconstructor(\n\t\tdefinitionsPath: string,\n\t\tprojectProvider?: IProjectStore,\n\t\tevents: IEventSink = new NoopEventSink()\n\t) {\n\t\t// Constructed once per provider, and the share-link store gets this instance\n\t\t// (see LocalDataProvider.fromEnv), so there is one cache over the file.\n\t\tthis.file = new CachedJsonFile(path.join(definitionsPath, 'definitions-config.json'), empty);\n\t\tthis.projectProvider = projectProvider;\n\t\tthis.events = events;\n\t}\n\n\tsetProjectProvider(projectProvider: IProjectStore): void {\n\t\tthis.projectProvider = projectProvider;\n\t}\n\n\tprivate readConfig(): Promise<DefinitionsConfig> {\n\t\treturn this.file.get();\n\t}\n\n\t/**\n\t * Does not stop a prototype lookup: `definitions['__proto__']` returns\n\t * `Object.prototype`, whose `deletedAt` is undefined, so it passes as live\n\t * and the caller's `Object.assign` writes onto the prototype. Callers reach\n\t * this only behind `GuidSchema`, which rejects non-UUID keys — keep it that\n\t * way for any new entry point.\n\t */\n\tprivate live(record: DefinitionRecord | undefined | null): record is DefinitionRecord {\n\t\treturn Boolean(record && record.deletedAt == null);\n\t}\n\n\tprivate writeConfig(config: DefinitionsConfig): Promise<void> {\n\t\treturn this.file.write(config);\n\t}\n\n\t/** Definitions outlive their uploader, so only the name on them goes. */\n\tasync eraseUser(userId: string): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tfor (const record of Object.values(config.definitions)) {\n\t\t\tif (record.ownerId === userId) record.ownerId = ERASED_ACTOR_ID;\n\t\t\tif (record.createdBy === userId) record.createdBy = ERASED_ACTOR_ID;\n\t\t\tif (record.updatedBy === userId) record.updatedBy = ERASED_ACTOR_ID;\n\t\t}\n\t\tfor (const version of Object.values(config.definitionVersions)) {\n\t\t\tif (version.uploadedBy === userId) version.uploadedBy = ERASED_ACTOR_ID;\n\t\t}\n\t\tawait this.writeConfig(config);\n\t}\n\n\tprivate sortedRecords(\n\t\trecords: DefinitionRecord[],\n\t\topts?: DefinitionListOptions\n\t): DefinitionRecord[] {\n\t\tconst defaulted: DefinitionListOptions = {\n\t\t\t...opts,\n\t\t\torderBy: opts?.orderBy ?? 'name',\n\t\t\torderDir: opts?.orderDir ?? 'asc'\n\t\t};\n\t\treturn applyOrder([...records], defaulted, (r, field) => {\n\t\t\tif (field === 'name') return r.displayName.toLowerCase();\n\t\t\tif (field === 'solveCount') return r.solveCount ?? 0;\n\t\t\treturn (r as unknown as Record<string, unknown>)[field];\n\t\t});\n\t}\n\n\tprivate visibleRecords(\n\t\trecords: DefinitionRecord[],\n\t\topts?: DefinitionListOptions\n\t): DefinitionRecord[] {\n\t\tlet filtered = records.filter((r) => r?.displayName && this.live(r));\n\t\tif (opts?.projectIds) {\n\t\t\tconst allowedProjects = new Set(opts.projectIds);\n\t\t\tfiltered = filtered.filter((r) => allowedProjects.has(r.projectId));\n\t\t}\n\t\tif (opts?.sourceDocumentId) {\n\t\t\tfiltered = filtered.filter((r) => r.sourceDocumentId === opts.sourceDocumentId);\n\t\t}\n\t\tif (opts?.statuses?.length) {\n\t\t\tconst allowed = new Set(opts.statuses);\n\t\t\treturn filtered.filter((r) => allowed.has(r.status));\n\t\t}\n\t\treturn filtered.filter((r) => {\n\t\t\tif (r.status === 'pending' && !opts?.includePending) return false;\n\t\t\tif (r.status === 'archived' && !opts?.includeArchived) return false;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync list(_ctx: RequestContext, opts?: DefinitionListOptions): Promise<Page<DefinitionRecord>> {\n\t\tconst config = await this.readConfig();\n\t\tconst records = this.visibleRecords(Object.values(config.definitions), opts);\n\t\treturn paginate(this.sortedRecords(records, opts), opts);\n\t}\n\n\tasync listByProject(\n\t\t_ctx: RequestContext,\n\t\tprojectId: string,\n\t\topts?: DefinitionListOptions\n\t): Promise<Page<DefinitionRecord>> {\n\t\tconst config = await this.readConfig();\n\t\tconst records = this.visibleRecords(\n\t\t\tObject.values(config.definitions).filter((r) => r?.projectId === projectId),\n\t\t\topts\n\t\t);\n\t\treturn paginate(this.sortedRecords(records, opts), opts);\n\t}\n\n\tasync listPublic(\n\t\tctx: RequestContext,\n\t\topts?: DefinitionListOptions & { orgId?: string }\n\t): Promise<Page<DefinitionRecord>> {\n\t\tif (!this.projectProvider) {\n\t\t\t// Before setProjectProvider is called, behave as if the default\n\t\t\t// project is public — matches the local bootstrap. Dead code after wiring.\n\t\t\treturn this.list(ctx, opts);\n\t\t}\n\n\t\tconst config = await this.readConfig();\n\t\tconst records = Object.values(config.definitions).filter((r): r is DefinitionRecord =>\n\t\t\tBoolean(r?.displayName && this.live(r))\n\t\t);\n\n\t\tconst projectIds = Array.from(new Set(records.map((r) => r.projectId)));\n\t\tconst projects = await Promise.all(\n\t\t\tprojectIds.map((id) => this.projectProvider!.getProject(ctx, id))\n\t\t);\n\t\tconst publicProjectIds = new Set(\n\t\t\tprojects\n\t\t\t\t.filter(\n\t\t\t\t\t(p): p is NonNullable<typeof p> =>\n\t\t\t\t\t\tp !== null && p.visibility === 'public' && (!opts?.orgId || p.orgId === opts.orgId)\n\t\t\t\t)\n\t\t\t\t.map((p) => p.id)\n\t\t);\n\n\t\tconst publicRecords = this.visibleRecords(\n\t\t\trecords.filter((r) => publicProjectIds.has(r.projectId)),\n\t\t\topts\n\t\t);\n\t\treturn paginate(this.sortedRecords(publicRecords, opts), opts);\n\t}\n\n\tasync get(_ctx: RequestContext, guid: string): Promise<DefinitionRecord | null> {\n\t\tconst config = await this.readConfig();\n\t\tconst r = config.definitions[guid];\n\t\treturn this.live(r) ? r : null;\n\t}\n\n\tasync getDefinitionsFor(\n\t\t_ctx: RequestContext,\n\t\tguids: readonly string[]\n\t): Promise<Map<string, DefinitionRecord>> {\n\t\tconst config = await this.readConfig();\n\t\tconst found = new Map<string, DefinitionRecord>();\n\t\tfor (const guid of guids) {\n\t\t\tconst r = config.definitions[guid];\n\t\t\tif (this.live(r)) found.set(guid, r);\n\t\t}\n\t\treturn found;\n\t}\n\n\tasync create(ctx: RequestContext, record: DefinitionRecord): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst actor = ctx.userId || record.ownerId;\n\t\tconfig.definitions[record.guid] = {\n\t\t\t...record,\n\t\t\tcreatedBy: record.createdBy || actor,\n\t\t\tupdatedBy: record.updatedBy || actor,\n\t\t\tliveVersionId: record.liveVersionId ?? null,\n\t\t\tdraftVersionId: record.draftVersionId ?? null,\n\t\t\tdeletedAt: null\n\t\t};\n\t\tawait this.writeConfig(config);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition.created',\n\t\t\tdefinitionId: record.guid,\n\t\t\tprojectId: record.projectId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync update(ctx: RequestContext, guid: string, patch: DefinitionRecordPatch): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst existing = config.definitions[guid];\n\t\tif (!this.live(existing)) throw new ProviderError(`Definition '${guid}' not found`, 404);\n\n\t\tconst clearable = (v: unknown) => (v === null ? undefined : v);\n\t\tconfig.definitions[guid] = {\n\t\t\t...existing,\n\t\t\t...(patch.displayName !== undefined && { displayName: patch.displayName }),\n\t\t\t...(patch.description !== undefined && {\n\t\t\t\tdescription: clearable(patch.description) as string | undefined\n\t\t\t}),\n\t\t\t...(patch.category !== undefined && {\n\t\t\t\tcategory: clearable(patch.category) as string | undefined\n\t\t\t}),\n\t\t\t...(patch.tags !== undefined && { tags: clearable(patch.tags) as string[] | undefined }),\n\t\t\t...(patch.coverImage !== undefined && {\n\t\t\t\tcoverImage: clearable(patch.coverImage) as string | undefined\n\t\t\t}),\n\t\t\t...(patch.projectId !== undefined && { projectId: patch.projectId }),\n\t\t\t...(patch.computeServerId !== undefined && {\n\t\t\t\tcomputeServerId: clearable(patch.computeServerId) as string | undefined\n\t\t\t}),\n\t\t\t...(patch.solveCacheLimit !== undefined && {\n\t\t\t\tsolveCacheLimit: clearable(patch.solveCacheLimit) as number | undefined\n\t\t\t}),\n\t\t\t...(patch.status !== undefined && { status: patch.status }),\n\t\t\t...(patch.ownerId !== undefined && { ownerId: patch.ownerId }),\n\t\t\t...(patch.sourceDocumentId !== undefined && {\n\t\t\t\tsourceDocumentId: clearable(patch.sourceDocumentId) as string | undefined\n\t\t\t}),\n\t\t\t...auditUpdate(ctx, existing.updatedBy ?? existing.ownerId)\n\t\t};\n\t\tawait this.writeConfig(config);\n\t}\n\n\tasync delete(ctx: RequestContext, guid: string): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst existing = config.definitions[guid];\n\t\tif (!this.live(existing)) return;\n\t\tObject.assign(existing, auditSoftDelete(ctx, existing.updatedBy ?? existing.ownerId));\n\t\tawait this.writeConfig(config);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition.deleted',\n\t\t\tdefinitionId: guid,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync deleteByProject(ctx: RequestContext, projectId: string): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\t// One read-modify-write pass over the cached config so the whole cascade\n\t\t// lands in a single `writeConfig`. Collect the affected guids first, then\n\t\t// emit one `definition.deleted` per tombstoned record after the write.\n\t\tconst affected: DefinitionRecord[] = [];\n\t\tfor (const record of Object.values(config.definitions)) {\n\t\t\tif (record.projectId === projectId && this.live(record)) {\n\t\t\t\tObject.assign(record, auditSoftDelete(ctx, record.updatedBy ?? record.ownerId));\n\t\t\t\taffected.push(record);\n\t\t\t}\n\t\t}\n\t\tif (affected.length === 0) return;\n\t\tawait this.writeConfig(config);\n\t\tfor (const record of affected) {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'definition.deleted',\n\t\t\t\tdefinitionId: record.guid,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\t}\n\n\tasync incrementSolveCount(_ctx: RequestContext, guid: string): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst existing = config.definitions[guid];\n\t\tif (!this.live(existing)) return;\n\t\texisting.solveCount = (existing.solveCount ?? 0) + 1;\n\t\texisting.updatedAt = new Date().toISOString();\n\t\tawait this.writeConfig(config);\n\t}\n\n\tasync reserveNextVersionNumber(_ctx: RequestContext, guid: string): Promise<number> {\n\t\tconst config = await this.readConfig();\n\t\tconst existing = config.definitions[guid];\n\t\tif (!this.live(existing)) throw new ProviderError(`Definition '${guid}' not found`, 404);\n\t\t// No `await` between the read and the increment, so nothing can interleave\n\t\t// on Node's single thread — concurrent uploads can't race this. Never reads\n\t\t// the version list once `nextVersionNumber` exists: the counter alone\n\t\t// advances, so a deleted latest version's number is never handed out again.\n\t\tconst current = existing.nextVersionNumber ?? this.highestVersionNumber(config, guid) + 1;\n\t\texisting.nextVersionNumber = current + 1;\n\t\texisting.updatedAt = new Date().toISOString();\n\t\tawait this.writeConfig(config);\n\t\treturn current;\n\t}\n\n\t/**\n\t * Highest `versionNumber` currently on disk for a definition (0 if none). Only\n\t * used as the seed when a legacy record predates `nextVersionNumber`; new\n\t * records carry the counter and never take this path.\n\t */\n\tprivate highestVersionNumber(\n\t\tconfig: { definitionVersions: Record<string, DefinitionVersion> },\n\t\tdefinitionId: string\n\t): number {\n\t\tlet max = 0;\n\t\tfor (const v of Object.values(config.definitionVersions)) {\n\t\t\tif (v.definitionId === definitionId && v.versionNumber > max) max = v.versionNumber;\n\t\t}\n\t\treturn max;\n\t}\n\n\t// ============================================================================\n\t// Versions\n\t// ============================================================================\n\n\tasync createVersion(ctx: RequestContext, version: DefinitionVersion): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst parent = config.definitions[version.definitionId];\n\t\tif (!this.live(parent)) {\n\t\t\tthrow new ProviderError(`Definition '${version.definitionId}' not found`, 404);\n\t\t}\n\t\tif (config.definitionVersions[version.id]) {\n\t\t\tthrow new ProviderError(`Version '${version.id}' already exists`, 409);\n\t\t}\n\t\tconfig.definitionVersions[version.id] = { ...version };\n\t\tawait this.writeConfig(config);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition_version.created',\n\t\t\tversionId: version.id,\n\t\t\tdefinitionId: version.definitionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync listVersions(\n\t\t_ctx: RequestContext,\n\t\tdefinitionId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<DefinitionVersion>> {\n\t\tconst config = await this.readConfig();\n\t\tconst parent = config.definitions[definitionId];\n\t\tif (!this.live(parent)) return paginate([], opts);\n\t\t// `schema` and `inventory` are stripped to match the interface contract (and Supabase,\n\t\t// which leaves those columns out of the list projection): listed rows are metadata only,\n\t\t// and callers who need them go through `getVersion`.\n\t\tconst rows = Object.values(config.definitionVersions)\n\t\t\t.filter((v) => v.definitionId === definitionId)\n\t\t\t.sort((a, b) => b.versionNumber - a.versionNumber)\n\t\t\t.map(({ schema: _schema, inventory: _inventory, ...rest }) => rest);\n\t\treturn paginate(rows, opts);\n\t}\n\n\tasync listVersionsFor(\n\t\t_ctx: RequestContext,\n\t\tdefinitionIds: readonly string[]\n\t): Promise<Map<string, DefinitionVersion[]>> {\n\t\tconst config = await this.readConfig();\n\t\tconst byDefinition = new Map<string, DefinitionVersion[]>(definitionIds.map((id) => [id, []]));\n\t\tfor (const { schema: _schema, inventory: _inventory, ...version } of Object.values(\n\t\t\tconfig.definitionVersions\n\t\t)) {\n\t\t\tif (this.live(config.definitions[version.definitionId])) {\n\t\t\t\tbyDefinition.get(version.definitionId)?.push(version);\n\t\t\t}\n\t\t}\n\t\tfor (const versions of byDefinition.values()) {\n\t\t\tversions.sort((a, b) => b.versionNumber - a.versionNumber);\n\t\t}\n\t\treturn byDefinition;\n\t}\n\n\tasync getVersion(_ctx: RequestContext, versionId: string): Promise<DefinitionVersion | null> {\n\t\tconst config = await this.readConfig();\n\t\treturn config.definitionVersions[versionId] ?? null;\n\t}\n\n\tasync setVersionSchema(_ctx: RequestContext, versionId: string, schema: UISchema): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version) return;\n\t\tversion.schema = schema;\n\t\tversion.schemaExtractedAt = new Date().toISOString();\n\t\tawait this.writeConfig(config);\n\t}\n\n\tasync setVersionInventory(\n\t\t_ctx: RequestContext,\n\t\tversionId: string,\n\t\tinventory: DocumentInventory,\n\t\tsummary: InventorySummary\n\t): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version) return;\n\t\tversion.inventory = inventory;\n\t\tversion.inventorySummary = summary;\n\t\tawait this.writeConfig(config);\n\t}\n\n\tasync deleteVersion(ctx: RequestContext, versionId: string): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version) return;\n\t\tconst parent = config.definitions[version.definitionId];\n\t\t// Cannot delete a version while it's serving live or draft — caller must\n\t\t// repoint first.\n\t\tif (parent && (parent.liveVersionId === versionId || parent.draftVersionId === versionId)) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Version '${versionId}' is referenced by liveVersionId or draftVersionId`,\n\t\t\t\t409\n\t\t\t);\n\t\t}\n\t\tdelete config.definitionVersions[versionId];\n\t\tawait this.writeConfig(config);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition_version.deleted',\n\t\t\tversionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync setLiveVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tawait this.repoint('live', ctx, definitionId, versionId);\n\t}\n\n\tasync setDraftVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tawait this.repoint('draft', ctx, definitionId, versionId);\n\t}\n\n\tasync attachInitialVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\t// Single read-modify-write pass: both pointers + status updated together.\n\t\t// `writeConfig` is one fs operation, so the 'pending' → 'draft'\n\t\t// transition is atomic from any subsequent reader's perspective.\n\t\tconst config = await this.readConfig();\n\t\tconst record = config.definitions[definitionId];\n\t\tif (!this.live(record)) throw new ProviderError(`Definition '${definitionId}' not found`, 404);\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version || version.definitionId !== definitionId) {\n\t\t\tthrow new ProviderError(`Version '${versionId}' not found for this definition`, 404);\n\t\t}\n\t\trecord.liveVersionId = versionId;\n\t\trecord.draftVersionId = versionId;\n\t\trecord.status = 'draft';\n\t\tObject.assign(record, auditUpdate(ctx, record.updatedBy ?? record.ownerId));\n\t\tawait this.writeConfig(config);\n\t\t// No `definition.published` event — see interface doc. The parent's\n\t\t// `definition.created` + `definition_version.created` (emitted earlier\n\t\t// in this transaction) cover the bootstrap.\n\t}\n\n\tprivate async repoint(\n\t\tchannel: 'live' | 'draft',\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst record = config.definitions[definitionId];\n\t\tif (!this.live(record)) throw new ProviderError(`Definition '${definitionId}' not found`, 404);\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version || version.definitionId !== definitionId) {\n\t\t\tthrow new ProviderError(`Version '${versionId}' not found for this definition`, 404);\n\t\t}\n\t\tif (channel === 'live') record.liveVersionId = versionId;\n\t\telse record.draftVersionId = versionId;\n\t\tObject.assign(record, auditUpdate(ctx, record.updatedBy ?? record.ownerId));\n\t\tawait this.writeConfig(config);\n\t\t// Only `live` advancement is the published-event trigger. Draft\n\t\t// repointing is silent — it's the editor's working pointer, not a\n\t\t// publication signal.\n\t\tif (channel === 'live') {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'definition.published',\n\t\t\t\tdefinitionId,\n\t\t\t\tversionId,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tIShareLinkStore,\n\tIDefinitionStore,\n\tIProjectStore,\n\tIEventSink,\n\tOrgShareLink,\n\tShareLink,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { ProviderError, SYSTEM_CONTEXT, actorOf, NoopEventSink } from '@selvajs/platform';\nimport { paginate } from './pagination.js';\nimport { readJsonFile, withFileLock, writeJsonFile } from './fsJson.js';\n\ninterface OnDiskShape {\n\tlinks: Record<string, ShareLink>;\n}\n\nconst empty = (): OnDiskShape => ({ links: {} });\n\nexport interface LocalShareLinkStoreOptions {\n\t/** Absolute path to the JSON file backing this store. */\n\tfilePath: string;\n\tevents?: IEventSink;\n}\n\n/**\n * Writes queue on `withFileLock`, so `tryIncrementSolveCount` checks the cap and\n * counts as one step, but only within this process: two processes sharing\n * `share-links.json` can both admit the last solve under the cap.\n */\nexport class LocalShareLinkStore implements IShareLinkStore {\n\tprivate definitionProvider?: IDefinitionStore;\n\tprivate projectProvider?: IProjectStore;\n\tprivate readonly events: IEventSink;\n\tprivate readonly configFilePath: string;\n\n\t// Callers must still call `setDefinitionProvider` before token resolution or\n\t// solve counting, or the soft-delete cascade check silently no-ops.\n\t// LocalDataProvider wires this when it builds the store.\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalShareLinkStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalShareLinkStore({\n\t\t\tfilePath: path.join(env.DATA_PATH, 'share-links.json')\n\t\t});\n\t}\n\n\tconstructor(opts: LocalShareLinkStoreOptions) {\n\t\tthis.configFilePath = opts.filePath;\n\t\tthis.events = opts.events ?? new NoopEventSink();\n\t}\n\n\t/**\n\t * Wires the definition store so token resolution and solve counting can check\n\t * the parent definition's `deletedAt`, as Supabase does in SQL. Optional: if\n\t * unset, this falls back to the local-only revoke check, and the selva\n\t * app's route layer does the parent lookup as a safety net either way.\n\t */\n\tsetDefinitionProvider(definitions: IDefinitionStore): void {\n\t\tthis.definitionProvider = definitions;\n\t}\n\n\t/**\n\t * Wires the project store so `listByOrg` can complete the definition→project\n\t * hop that gives a link its org. Unset, the roster reads empty rather than\n\t * unfiltered — a share-link list that silently spans tenants is worse than\n\t * no list.\n\t */\n\tsetProjectProvider(projects: IProjectStore): void {\n\t\tthis.projectProvider = projects;\n\t}\n\n\tprivate async readAll(): Promise<OnDiskShape> {\n\t\treturn readJsonFile<OnDiskShape>(this.configFilePath, empty());\n\t}\n\n\tprivate async writeAll(data: OnDiskShape): Promise<void> {\n\t\tawait writeJsonFile(this.configFilePath, data);\n\t}\n\n\tprivate locked<T>(fn: () => Promise<T>): Promise<T> {\n\t\treturn withFileLock(this.configFilePath, fn);\n\t}\n\n\t// Revoked or expired counts as dead. Both providers filter both fields; a\n\t// link that reads live under one and dead under the other is the bug this\n\t// prevents.\n\tprivate isLive(l: ShareLink | undefined | null): l is ShareLink {\n\t\tif (!l || l.revokedAt != null) return false;\n\t\treturn l.expiresAt == null || Date.parse(l.expiresAt) > Date.now();\n\t}\n\n\tasync create(ctx: RequestContext, link: ShareLink): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tif (all.links[link.id]) {\n\t\t\t\tthrow new ProviderError(`Share link '${link.id}' already exists`, 409);\n\t\t\t}\n\t\t\tall.links[link.id] = { ...link, revokedAt: null };\n\t\t\tawait this.writeAll(all);\n\t\t});\n\t\tawait this.events.emit({\n\t\t\ttype: 'share_link.minted',\n\t\t\tlinkId: link.id,\n\t\t\tdefinitionId: link.definitionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync listByDefinition(\n\t\t_ctx: RequestContext,\n\t\tdefinitionId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<ShareLink>> {\n\t\tconst all = await this.readAll();\n\t\tconst rows = Object.values(all.links)\n\t\t\t.filter((l) => l.definitionId === definitionId && this.isLive(l))\n\t\t\t.sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n\t\treturn paginate(rows, opts);\n\t}\n\n\tasync listByOrg(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<OrgShareLink>> {\n\t\t// No org column on a link — the org is two hops up, through the parent\n\t\t// definition to its project. Supabase does this as a SQL join; here it is\n\t\t// a lookup, same as the soft-delete cascade in `getByTokenHash`.\n\t\tif (!this.definitionProvider || !this.projectProvider) return paginate([], opts);\n\n\t\tconst all = await this.readAll();\n\t\tconst live = Object.values(all.links).filter((l) => this.isLive(l));\n\t\tif (live.length === 0) return paginate([], opts);\n\n\t\tconst definitions = new Map(\n\t\t\tawait Promise.all(\n\t\t\t\t[...new Set(live.map((l) => l.definitionId))].map(\n\t\t\t\t\tasync (id) => [id, await this.definitionProvider!.get(SYSTEM_CONTEXT, id)] as const\n\t\t\t\t)\n\t\t\t)\n\t\t);\n\n\t\t// One page covers any realistic org; the roster is a per-tenant view.\n\t\tconst projects = await this.projectProvider.listProjects(ctx, orgId, { limit: 1000 });\n\t\tconst projectById = new Map(projects.items.map((p) => [p.id, p]));\n\n\t\tconst rows: OrgShareLink[] = [];\n\t\tfor (const link of live) {\n\t\t\tconst definition = definitions.get(link.definitionId);\n\t\t\t// A link whose definition is soft-deleted is unresolvable, so listing it\n\t\t\t// would offer a revoke that changes nothing.\n\t\t\tif (!definition) continue;\n\t\t\tconst project = projectById.get(definition.projectId);\n\t\t\tif (!project) continue;\n\t\t\tconst { tokenHash: _tokenHash, ...rest } = link;\n\t\t\trows.push({\n\t\t\t\t...rest,\n\t\t\t\tdefinitionName: definition.displayName,\n\t\t\t\tprojectId: project.id,\n\t\t\t\tprojectName: project.name\n\t\t\t});\n\t\t}\n\t\trows.sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n\t\treturn paginate(rows, opts);\n\t}\n\n\tasync getById(_ctx: RequestContext, id: string): Promise<ShareLink | null> {\n\t\tconst all = await this.readAll();\n\t\treturn all.links[id] ?? null;\n\t}\n\n\tasync getByTokenHash(_ctx: RequestContext, tokenHash: string): Promise<ShareLink | null> {\n\t\tconst all = await this.readAll();\n\t\tconst found = Object.values(all.links).find((l) => l.tokenHash === tokenHash);\n\t\tif (!this.isLive(found)) return null;\n\t\treturn (await this.parentIsLive(found)) ? found : null;\n\t}\n\n\t// Token resolution and solve counting must not see links whose parent\n\t// definition is soft-deleted — Supabase enforces this in SQL, here via lookup.\n\tprivate async parentIsLive(link: ShareLink): Promise<boolean> {\n\t\tif (!this.definitionProvider) return true;\n\t\treturn (await this.definitionProvider.get(SYSTEM_CONTEXT, link.definitionId)) !== null;\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst revoked = await this.locked(async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst l = all.links[id];\n\t\t\tif (!l) throw new ProviderError(`Share link '${id}' not found`, 404);\n\t\t\tif (!this.isLive(l)) return false; // idempotent\n\t\t\tl.revokedAt = new Date().toISOString();\n\t\t\tawait this.writeAll(all);\n\t\t\treturn true;\n\t\t});\n\t\tif (!revoked) return;\n\t\tawait this.events.emit({ type: 'share_link.revoked', linkId: id, ...actorOf(ctx) });\n\t}\n\n\tasync tryIncrementSolveCount(_ctx: RequestContext, id: string): Promise<number | null> {\n\t\treturn this.locked(async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst l = all.links[id];\n\t\t\tif (!l || !this.isLive(l)) return null;\n\t\t\tif (l.maxSolves != null && l.solveCount >= l.maxSolves) return null;\n\t\t\tif (!(await this.parentIsLive(l))) return null;\n\t\t\tl.solveCount += 1;\n\t\t\tawait this.writeAll(all);\n\t\t\treturn l.solveCount;\n\t\t});\n\t}\n\n\t/** A link goes with the user who minted it, as Supabase's `created_by` cascade does. */\n\tasync eraseUser(userId: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tfor (const [id, link] of Object.entries(all.links)) {\n\t\t\t\tif (link.createdBy === userId) delete all.links[id];\n\t\t\t}\n\t\t\tawait this.writeAll(all);\n\t\t});\n\t}\n}\n","import { ProviderError } from '@selvajs/platform';\nimport type { PlatformPermission, RecentRun } from '@selvajs/platform';\nimport { MAX_RECENT_RUNS } from '@selvajs/platform/userProfile';\nimport { CachedJsonFile } from './fsJson.js';\n\n/**\n * Per-user state keyed by the auth provider's user ID. Mirrors\n * `public.user_profiles` in the Supabase schema. **Never holds identity**\n * (email, password hash, createdAt) — that lives with the auth provider.\n *\n * `hooks.server.ts` calls `IDataProvider.ensureUser` once per authenticated\n * request (the local equivalent of Supabase's `handle_new_auth_user`\n * trigger), so every read here after that is guaranteed to find a row.\n */\nexport interface StoredUserData {\n\tuserId: string;\n\tdisplayName?: string;\n\tplatformPermissions: PlatformPermission[];\n\tstarredDefinitions: string[];\n\trecentRuns: RecentRun[];\n}\n\nexport interface UserDataFile {\n\tusers: StoredUserData[];\n}\n\nconst empty = (): UserDataFile => ({ users: [] });\n\nfunction emptyRow(userId: string): StoredUserData {\n\treturn {\n\t\tuserId,\n\t\tplatformPermissions: [],\n\t\tstarredDefinitions: [],\n\t\trecentRuns: []\n\t};\n}\n\nexport interface LocalUserDataStore {\n\t/** Idempotent: adds an empty row if missing, no-op if present. */\n\tensure(userId: string): Promise<void>;\n\tfindById(userId: string): Promise<StoredUserData | null>;\n\tlistAll(): Promise<StoredUserData[]>;\n\tupdatePermissions(userId: string, permissions: PlatformPermission[]): Promise<void>;\n\t/**\n\t * Write `permissions`, but only while the §2 sole-`instance_admin`\n\t * invariant still holds — the count and the write happen without an\n\t * `await` between them, so two concurrent demotions cannot both observe\n\t * the other as \"another admin exists\".\n\t *\n\t * Returns `'last_admin'` when the write would drop the final admin,\n\t * `'not_found'` for an absent row. Callers must not pre-check the count\n\t * themselves: a decision made before this call is exactly the race.\n\t */\n\tupdatePermissionsGuarded(\n\t\tuserId: string,\n\t\tpermissions: PlatformPermission[]\n\t): Promise<'ok' | 'last_admin' | 'not_found'>;\n\t/** Grants only if no user holds `instance_admin` yet. True if this call claimed it. */\n\tclaimFirstInstanceAdminGuarded(\n\t\tuserId: string,\n\t\tpermissions: PlatformPermission[]\n\t): Promise<boolean>;\n\tupdateDisplayName(userId: string, displayName: string | undefined): Promise<void>;\n\tstarDefinition(userId: string, definitionId: string): Promise<void>;\n\tunstarDefinition(userId: string, definitionId: string): Promise<void>;\n\trecordRun(userId: string, run: RecentRun): Promise<void>;\n\tdeleteUser(userId: string): Promise<void>;\n}\n\nexport function createLocalUserDataStore(filePath: string): LocalUserDataStore {\n\t// Load-once, write-through cache, same pattern as `LocalOrgStoreLoader`.\n\t// The provider is the sole writer in single-process local mode, so the\n\t// in-memory copy is authoritative — but only if every consumer shares one\n\t// instance. LocalDataProvider injects a single instance across the\n\t// profile, permission, and data-provider views; don't call this factory\n\t// more than once per process.\n\tconst store = new CachedJsonFile<UserDataFile>(filePath, empty);\n\tconst load = () => store.get();\n\tconst persist = (file: UserDataFile) => store.write(file);\n\n\t// Serializes permission writes that must not interleave. Single-process\n\t// only, like the cache above — it makes the local provider's own\n\t// concurrency safe, not a multi-process deployment's. That is the same\n\t// dev-scale boundary the load-once cache already draws.\n\tlet permissionLock: Promise<unknown> = Promise.resolve();\n\n\tfunction withPermissionLock<T>(fn: () => Promise<T>): Promise<T> {\n\t\t// Chain onto the tail regardless of how the previous holder settled, so\n\t\t// one rejection cannot wedge the queue for the process's lifetime.\n\t\tconst next = permissionLock.then(fn, fn);\n\t\tpermissionLock = next.catch(() => {});\n\t\treturn next;\n\t}\n\n\tasync function findOrThrow(userId: string): Promise<{ file: UserDataFile; row: StoredUserData }> {\n\t\tconst file = await load();\n\t\tconst row = file.users.find((u) => u.userId === userId);\n\t\tif (!row) throw new ProviderError(`User-data row \"${userId}\" not found`, 404);\n\t\treturn { file, row };\n\t}\n\n\treturn {\n\t\tasync ensure(userId) {\n\t\t\tconst file = await load();\n\t\t\tif (file.users.some((u) => u.userId === userId)) return;\n\t\t\tfile.users.push(emptyRow(userId));\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync findById(userId) {\n\t\t\tconst { users } = await load();\n\t\t\treturn users.find((u) => u.userId === userId) ?? null;\n\t\t},\n\n\t\tasync listAll() {\n\t\t\tconst { users } = await load();\n\t\t\treturn users;\n\t\t},\n\n\t\tasync updatePermissions(userId, permissions) {\n\t\t\tconst { file, row } = await findOrThrow(userId);\n\t\t\trow.platformPermissions = permissions;\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync updatePermissionsGuarded(userId, permissions) {\n\t\t\t// Serialized against every other guarded write: `load()` may yield,\n\t\t\t// and the admin count read before that yield is stale by the time\n\t\t\t// the write lands. Queueing keeps count-and-write indivisible.\n\t\t\treturn withPermissionLock(async () => {\n\t\t\t\tconst file = await load();\n\t\t\t\tconst row = file.users.find((u) => u.userId === userId);\n\t\t\t\tif (!row) return 'not_found';\n\n\t\t\t\tconst wasAdmin = row.platformPermissions.includes('instance_admin');\n\t\t\t\tconst willBeAdmin = permissions.includes('instance_admin');\n\t\t\t\tif (wasAdmin && !willBeAdmin) {\n\t\t\t\t\tconst others = file.users.filter(\n\t\t\t\t\t\t(u) => u.userId !== userId && u.platformPermissions.includes('instance_admin')\n\t\t\t\t\t).length;\n\t\t\t\t\tif (others === 0) return 'last_admin';\n\t\t\t\t}\n\n\t\t\t\trow.platformPermissions = permissions;\n\t\t\t\tawait persist(file);\n\t\t\t\treturn 'ok';\n\t\t\t});\n\t\t},\n\n\t\tasync claimFirstInstanceAdminGuarded(userId, permissions) {\n\t\t\t// Shares the lock with `updatePermissionsGuarded` deliberately: the\n\t\t\t// two decide the same question from opposite ends (\"is there still an\n\t\t\t// admin\" / \"is there one yet\"), so they must not interleave with each\n\t\t\t// other any more than with themselves.\n\t\t\treturn withPermissionLock(async () => {\n\t\t\t\tconst file = await load();\n\t\t\t\tif (file.users.some((u) => u.platformPermissions.includes('instance_admin'))) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tconst row = file.users.find((u) => u.userId === userId);\n\t\t\t\tif (!row) return false;\n\n\t\t\t\trow.platformPermissions = permissions;\n\t\t\t\tawait persist(file);\n\t\t\t\treturn true;\n\t\t\t});\n\t\t},\n\n\t\tasync updateDisplayName(userId, displayName) {\n\t\t\tconst { file, row } = await findOrThrow(userId);\n\t\t\tif (displayName === undefined) {\n\t\t\t\tdelete row.displayName;\n\t\t\t} else {\n\t\t\t\trow.displayName = displayName;\n\t\t\t}\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync starDefinition(userId, definitionId) {\n\t\t\tconst { file, row } = await findOrThrow(userId);\n\t\t\tif (!row.starredDefinitions.includes(definitionId)) {\n\t\t\t\trow.starredDefinitions.push(definitionId);\n\t\t\t\tawait persist(file);\n\t\t\t}\n\t\t},\n\n\t\tasync unstarDefinition(userId, definitionId) {\n\t\t\tconst { file, row } = await findOrThrow(userId);\n\t\t\trow.starredDefinitions = row.starredDefinitions.filter((d) => d !== definitionId);\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync recordRun(userId, run) {\n\t\t\tconst { file, row } = await findOrThrow(userId);\n\t\t\t// Remove older entry for same definition, then prepend newest.\n\t\t\trow.recentRuns = [\n\t\t\t\trun,\n\t\t\t\t...row.recentRuns.filter((r) => r.definitionId !== run.definitionId)\n\t\t\t].slice(0, MAX_RECENT_RUNS);\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync deleteUser(userId) {\n\t\t\tconst file = await load();\n\t\t\tconst before = file.users.length;\n\t\t\tfile.users = file.users.filter((u) => u.userId !== userId);\n\t\t\tif (file.users.length === before) {\n\t\t\t\tthrow new ProviderError(`User-data row \"${userId}\" not found`, 404);\n\t\t\t}\n\t\t\tawait persist(file);\n\t\t}\n\t};\n}\n","import * as path from 'node:path';\nimport type {\n\tIUserProfileStore,\n\tRecentRun,\n\tRequestContext,\n\tUserManagementResult,\n\tUserProfile\n} from '@selvajs/platform';\nimport { ProviderError } from '@selvajs/platform';\nimport { assertCanAccessProfile } from '@selvajs/platform/userProfile';\nimport {\n\tcreateLocalUserDataStore,\n\ttype LocalUserDataStore,\n\ttype StoredUserData\n} from '../data/userData.js';\n\nfunction toProfile(u: StoredUserData): UserProfile {\n\treturn {\n\t\tuserId: u.userId,\n\t\tdisplayName: u.displayName,\n\t\tstarredDefinitions: u.starredDefinitions ?? [],\n\t\trecentRuns: u.recentRuns ?? []\n\t};\n}\n\n/**\n * Filesystem-backed user-profile store. Reads and writes `user-data.json`,\n * shared with `LocalPlatformPermissionStore`. Keys exclusively by user ID;\n * identity (email, password hash) lives separately on the auth provider.\n * `IDataProvider.ensureUser` (called from `hooks.server.ts`) seeds an empty\n * row for every authed user.\n */\nexport class LocalUserProfileProvider implements IUserProfileStore {\n\tprivate readonly data: LocalUserDataStore;\n\n\t/**\n\t * Accepts a file path (constructs its own store — for `fromEnv` and\n\t * standalone conformance tests) or a shared `LocalUserDataStore`.\n\t * `LocalDataProvider` injects one store shared with the permission store\n\t * and the data provider so all three see the same load-once write-through\n\t * cache over `user-data.json` (§3a) — separate stores on the same file\n\t * would diverge.\n\t */\n\tconstructor(userData: string | LocalUserDataStore) {\n\t\tthis.data = typeof userData === 'string' ? createLocalUserDataStore(userData) : userData;\n\t}\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalUserProfileProvider {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalUserProfileProvider(path.join(env.DATA_PATH, 'user-data.json'));\n\t}\n\n\tasync getProfile(ctx: RequestContext, userId: string): Promise<UserProfile | null> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\tconst u = await this.data.findById(userId);\n\t\treturn u ? toProfile(u) : null;\n\t}\n\n\tasync getProfiles(_ctx: RequestContext, userIds: readonly string[]): Promise<UserProfile[]> {\n\t\t// Unscoped by design: used for display-name lookups across the UI.\n\t\t// Adapters needing per-caller restriction should override.\n\t\tconst all = await this.data.listAll();\n\t\tconst wanted = new Set(userIds);\n\t\treturn all.filter((u) => wanted.has(u.userId)).map(toProfile);\n\t}\n\n\tasync updateProfile(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tpatch: { displayName?: string }\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\ttry {\n\t\t\tif (patch.displayName !== undefined) {\n\t\t\t\tawait this.data.updateDisplayName(userId, patch.displayName);\n\t\t\t}\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync starDefinition(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tdefinitionId: string\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\ttry {\n\t\t\tawait this.data.starDefinition(userId, definitionId);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync unstarDefinition(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tdefinitionId: string\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\ttry {\n\t\t\tawait this.data.unstarDefinition(userId, definitionId);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync recordRun(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\trun: RecentRun\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\ttry {\n\t\t\tawait this.data.recordRun(userId, run);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\n/** Scoped to the user themselves; `instance_admin` and `system: true` callers bypass. */\n","import * as path from 'node:path';\nimport type {\n\tIPlatformPermissionStore,\n\tPlatformPermission,\n\tRequestContext,\n\tUserManagementResult\n} from '@selvajs/platform';\nimport { ProviderError } from '@selvajs/platform';\nimport {\n\tassertCanManagePermissions,\n\tassertCanReadPermissions,\n\tassertCanReadPermissionsBatch\n} from '@selvajs/platform/permissions';\nimport { createLocalUserDataStore, type LocalUserDataStore } from '../data/userData.js';\n\n/**\n * Filesystem-backed platform-permission store. Reads/writes the\n * `platformPermissions` field on `user-data.json`, owned by\n * `LocalDataProvider` and separate from `auth-users.json` (owned by\n * `LocalAuthProvider`) — the data layer only ever keys by user ID, never by\n * how identity is stored, so it pairs with any auth provider.\n *\n * Rows are seeded by `IDataProvider.ensureUser` (called per authed request\n * from `hooks.server.ts`); before that call `set` returns `not_found`.\n *\n * `set` enforces the §2 sole-`instance_admin` invariant (refuses to drop the\n * last admin) through `updatePermissionsGuarded`, which counts and writes\n * without yielding — a caller must never pre-check the count and then call\n * `set`, since the gap between the two is the race the guard exists to close.\n * That protects this process only; two processes sharing one `user-data.json`\n * is outside what the load-once cache supports either.\n *\n * It has no visibility into \"disabled\" state, which lives on\n * the auth provider's record — **every row here counts as enabled**. A\n * disabled admin would therefore still satisfy the \"another admin exists\"\n * check and let the last enabled one be demoted, so whoever disables a user\n * must revoke `instance_admin` through `set` first. That sequencing lives in\n * the disable route (`POST /api/admin/users/[id]/disable`), which holds both\n * this store and the auth provider; `LocalAuthProvider` deliberately has no\n * reference to the permission store.\n */\nexport class LocalPlatformPermissionStore implements IPlatformPermissionStore {\n\tprivate readonly data: LocalUserDataStore;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalPlatformPermissionStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalPlatformPermissionStore(path.join(env.DATA_PATH, 'user-data.json'));\n\t}\n\n\t/**\n\t * Accepts a file path (constructs its own store) or a shared\n\t * `LocalUserDataStore` — `LocalDataProvider` injects one shared store so\n\t * the permission, profile, and data-provider views of `user-data.json`\n\t * share a single load-once write-through cache (§3a).\n\t */\n\tconstructor(userData: string | LocalUserDataStore) {\n\t\tthis.data = typeof userData === 'string' ? createLocalUserDataStore(userData) : userData;\n\t}\n\n\tasync getFor(ctx: RequestContext, userId: string): Promise<PlatformPermission[]> {\n\t\tassertCanReadPermissions(ctx, userId);\n\t\tconst row = await this.data.findById(userId);\n\t\treturn row?.platformPermissions ?? [];\n\t}\n\n\tasync getForBatch(\n\t\tctx: RequestContext,\n\t\tuserIds: readonly string[]\n\t): Promise<Map<string, PlatformPermission[]>> {\n\t\tassertCanReadPermissionsBatch(ctx);\n\t\tconst all = await this.data.listAll();\n\t\tconst wanted = new Set(userIds);\n\t\tconst out = new Map<string, PlatformPermission[]>();\n\t\tfor (const u of all) {\n\t\t\tif (wanted.has(u.userId)) out.set(u.userId, u.platformPermissions ?? []);\n\t\t}\n\t\treturn out;\n\t}\n\n\tasync set(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tpermissions: readonly PlatformPermission[]\n\t): Promise<UserManagementResult> {\n\t\tassertCanManagePermissions(ctx);\n\t\t// The count and the write have to be indivisible — checking here and\n\t\t// writing after would let two concurrent demotions each see the other\n\t\t// as the surviving admin. `updatePermissionsGuarded` owns both.\n\t\ttry {\n\t\t\treturn await this.data.updatePermissionsGuarded(userId, [...permissions]);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync claimFirstInstanceAdmin(\n\t\t_ctx: RequestContext,\n\t\tuserId: string,\n\t\tpermissions: readonly PlatformPermission[]\n\t): Promise<boolean> {\n\t\t// No `assertCanManagePermissions`: by definition nobody holds `instance_admin` when this\n\t\t// succeeds. The guard is the store's own no-admin-yet condition, which is\n\t\t// why the check cannot be hoisted into the caller.\n\t\treturn this.data.claimFirstInstanceAdminGuarded(userId, [...permissions]);\n\t}\n\n\tasync hasInstanceAdmin(_ctx: RequestContext): Promise<boolean> {\n\t\t// Read-only existence probe, always allowed — used for first-run checks.\n\t\tconst all = await this.data.listAll();\n\t\treturn all.some((u) => u.platformPermissions.includes('instance_admin'));\n\t}\n\n\tasync countInstanceAdminsExcluding(_ctx: RequestContext, excludeUserId: string): Promise<number> {\n\t\treturn this.countOtherAdmins(excludeUserId);\n\t}\n\n\tprivate async countOtherAdmins(excludeUserId: string): Promise<number> {\n\t\tconst all = await this.data.listAll();\n\t\treturn all.filter(\n\t\t\t(u) => u.userId !== excludeUserId && u.platformPermissions.includes('instance_admin')\n\t\t).length;\n\t}\n}\n","import type {\n\tIDataProvider,\n\tIOrgStore,\n\tIProjectStore,\n\tIDefinitionStore,\n\tIComputeServerStore,\n\tIInviteStore,\n\tIApiTokenStore,\n\tIShareLinkStore,\n\tIUserProfileStore,\n\tIPlatformPermissionStore,\n\tIPlatformProjectGrantStore,\n\tIEventSink,\n\tRequestContext,\n\tUserErasureOptions\n} from '@selvajs/platform';\nimport { NoopEventSink } from '@selvajs/platform';\nimport * as path from 'node:path';\nimport { LocalOrgStore, LocalOrgStoreLoader } from './LocalOrgStore.js';\nimport { LocalProjectStore } from './LocalProjectStore.js';\nimport { LocalDefinitionStore } from './LocalDefinitionStore.js';\nimport { LocalComputeServerStore } from './LocalComputeServerStore.js';\nimport { LocalInviteStore } from './LocalInviteStore.js';\nimport { LocalApiTokenStore } from './LocalApiTokenStore.js';\nimport { LocalShareLinkStore } from './LocalShareLinkStore.js';\nimport { LocalPlatformProjectGrantStore } from './LocalPlatformProjectGrantStore.js';\nimport { LocalUserProfileProvider } from '../userProfile/LocalUserProfileProvider.js';\nimport { LocalPlatformPermissionStore } from '../permissions/LocalPlatformPermissionStore.js';\nimport { createLocalUserDataStore, type LocalUserDataStore } from './userData.js';\n\n/** The concrete stores, for the erasure steps the platform interfaces don't have. */\ninterface ErasableStores {\n\torgs: LocalOrgStore;\n\tdefinitions: LocalDefinitionStore;\n\tinvites: LocalInviteStore;\n\tshareLinks: LocalShareLinkStore;\n\tplatformProjectGrants: LocalPlatformProjectGrantStore;\n}\n\n/**\n * Composition root for every local-provider data store. One\n * `LocalOrgStoreLoader` is shared across org + project stores so they see the\n * same cache and atomic write path; one `LocalUserDataStore` is shared across\n * the permissions, profile, and `ensureUser`/`onUserDeleted` paths so they\n * all read and write the same `user-data.json` row (the local equivalent of\n * Supabase's `handle_new_auth_user` trigger).\n */\nexport class LocalDataProvider implements IDataProvider {\n\treadonly orgs: IOrgStore;\n\treadonly projects: IProjectStore;\n\treadonly definitions: IDefinitionStore;\n\treadonly computeServer: IComputeServerStore;\n\treadonly invites: IInviteStore;\n\treadonly apiTokens: IApiTokenStore;\n\treadonly shareLinks: IShareLinkStore;\n\treadonly userProfile: IUserProfileStore;\n\treadonly permissions: IPlatformPermissionStore;\n\treadonly platformProjectGrants: IPlatformProjectGrantStore;\n\treadonly events?: IEventSink;\n\n\tprivate readonly userData: LocalUserDataStore;\n\tprivate readonly erasable: ErasableStores;\n\n\tprivate constructor(\n\t\tstores: Omit<\n\t\t\tIDataProvider,\n\t\t\t| 'ensureUser'\n\t\t\t| 'onUserDeleted'\n\t\t\t| 'apiTokens'\n\t\t\t| 'orgs'\n\t\t\t| 'definitions'\n\t\t\t| 'invites'\n\t\t\t| 'shareLinks'\n\t\t\t| 'platformProjectGrants'\n\t\t> &\n\t\t\tErasableStores & { apiTokens: IApiTokenStore },\n\t\tuserData: LocalUserDataStore\n\t) {\n\t\tthis.erasable = stores;\n\t\tthis.events = stores.events;\n\t\tthis.orgs = stores.orgs;\n\t\tthis.projects = stores.projects;\n\t\tthis.definitions = stores.definitions;\n\t\tthis.computeServer = stores.computeServer;\n\t\tthis.invites = stores.invites;\n\t\tthis.apiTokens = stores.apiTokens;\n\t\tthis.shareLinks = stores.shareLinks;\n\t\tthis.userProfile = stores.userProfile;\n\t\tthis.permissions = stores.permissions;\n\t\tthis.platformProjectGrants = stores.platformProjectGrants;\n\t\tthis.userData = userData;\n\t}\n\n\t/**\n\t * Idempotently seeds a user's `user-data.json` row. Called on every authed\n\t * request from `hooks.server.ts` — the local equivalent of Supabase's\n\t * `handle_new_auth_user` trigger. `ctx` is unused; registration runs as a\n\t * system operation regardless of the calling user, kept for interface\n\t * symmetry with adapters that need it.\n\t */\n\tasync ensureUser(_ctx: RequestContext, userId: string): Promise<void> {\n\t\tawait this.userData.ensure(userId);\n\t}\n\n\t/**\n\t * Cascade hook run after the auth provider deletes a user: removes the\n\t * `user-data.json` row, every membership and everything else that names them\n\t * (Supabase gets most of this from FK constraints). Rows they made stay, under\n\t * `ERASED_ACTOR_ID`. Tolerates missing rows.\n\t */\n\tasync onUserDeleted(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\topts?: UserErasureOptions\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait this.userData.deleteUser(userId);\n\t\t} catch {\n\t\t\t// Already absent — nothing to clean up.\n\t\t}\n\t\tawait this.apiTokens.eraseUser(ctx, userId);\n\t\tawait this.erasable.orgs.eraseUser(userId);\n\t\tawait this.erasable.definitions.eraseUser(userId);\n\t\tawait this.erasable.invites.eraseUser(userId, opts?.email);\n\t\tawait this.erasable.shareLinks.eraseUser(userId);\n\t\tawait this.erasable.platformProjectGrants.eraseUser(userId);\n\t}\n\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tevents: IEventSink = new NoopEventSink()\n\t): LocalDataProvider {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\tconst dataPath = env.DATA_PATH;\n\t\tconst userDataFilePath = path.join(dataPath, 'user-data.json');\n\n\t\tconst loader = new LocalOrgStoreLoader(dataPath);\n\t\tconst platformProjectGrants = LocalPlatformProjectGrantStore.fromEnv(env);\n\t\tconst invites = LocalInviteStore.fromEnv(env, events);\n\t\tconst apiTokens = LocalApiTokenStore.fromEnv(env, events);\n\t\tconst computeServer = LocalComputeServerStore.fromEnv(env);\n\t\tconst projects = new LocalProjectStore({ loader, grants: platformProjectGrants, events });\n\t\tconst definitions = new LocalDefinitionStore(dataPath, undefined, events);\n\t\tconst shareLinks = new LocalShareLinkStore({\n\t\t\tfilePath: path.join(dataPath, 'share-links.json'),\n\t\t\tevents\n\t\t});\n\t\tconst orgs = new LocalOrgStore({\n\t\t\tloader,\n\t\t\tinvites,\n\t\t\tapiTokens,\n\t\t\tcomputeServer,\n\t\t\tgrants: platformProjectGrants,\n\t\t\tevents\n\t\t});\n\n\t\t// Wire cross-store deps that aren't constructor-injected:\n\t\t// - definitions needs the project store for listPublic's visibility check\n\t\t// - shareLinks needs the definition store to enforce the soft-delete\n\t\t// cascade on resolution, and both stores to walk link→definition→project\n\t\t// for the org roster (Supabase does both via JOIN)\n\t\t// - projects needs the definition store to cascade soft-delete to a\n\t\t// deleted project's definitions (Supabase does this inline)\n\t\tdefinitions.setProjectProvider(projects);\n\t\tshareLinks.setDefinitionProvider(definitions);\n\t\tshareLinks.setProjectProvider(projects);\n\t\tprojects.setDefinitionProvider(definitions);\n\t\torgs.setDefinitionProvider(definitions);\n\n\t\tconst userData = createLocalUserDataStore(userDataFilePath);\n\n\t\treturn new LocalDataProvider(\n\t\t\t{\n\t\t\t\torgs,\n\t\t\t\tprojects,\n\t\t\t\tdefinitions,\n\t\t\t\tcomputeServer,\n\t\t\t\tinvites,\n\t\t\t\tapiTokens,\n\t\t\t\tshareLinks,\n\t\t\t\tuserProfile: new LocalUserProfileProvider(userData),\n\t\t\t\tpermissions: new LocalPlatformPermissionStore(userData),\n\t\t\t\tplatformProjectGrants,\n\t\t\t\tevents\n\t\t\t},\n\t\t\tuserData\n\t\t);\n\t}\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport { ProviderError } from '@selvajs/platform';\nimport { transcodeImageIfNeeded } from '@selvajs/platform/storage';\nimport { renameReplacing } from '../data/fsJson.js';\nimport type { IStorageProvider } from '@selvajs/platform/storage';\n\n/**\n * Filesystem implementation of `IStorageProvider`. Files live under\n * `DATA_PATH/{path}`. `put()` transcodes images to WebP via the shared\n * `transcodeImageIfNeeded` helper — the same one the Supabase adapter uses,\n * so both providers produce identical bytes for the same upload.\n */\nexport class LocalStorageProvider implements IStorageProvider {\n\tprivate readonly basePath: string;\n\tprivate readonly publicUrlBase: string;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalStorageProvider {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalStorageProvider(env.DATA_PATH, '/api/files');\n\t}\n\n\tconstructor(basePath: string, publicUrlBase = '/api/files') {\n\t\tthis.basePath = basePath;\n\t\tthis.publicUrlBase = publicUrlBase;\n\t}\n\n\t/**\n\t * Resolves a caller-provided path under basePath; rejects anything that\n\t * would escape the root. Last line of defense against traversal — this\n\t * adapter is reached by any `IStorageProvider` caller, not just ones that\n\t * already validated the key.\n\t */\n\tprivate resolvePath(storagePath: string): string {\n\t\tconst base = path.resolve(this.basePath);\n\t\tconst full = path.resolve(base, storagePath);\n\t\tif (full !== base && !full.startsWith(base + path.sep)) {\n\t\t\tthrow new ProviderError(`Path escapes base: ${storagePath}`, 400);\n\t\t}\n\t\t// The storage root is `DATA_PATH`, which also holds the stores' JSON files,\n\t\t// `auth-users.json` among them. No asset lives directly in the root.\n\t\tif (path.dirname(full) === base && full.endsWith('.json')) {\n\t\t\tthrow new ProviderError(`Path is a data file, not an asset: ${storagePath}`, 400);\n\t\t}\n\t\treturn full;\n\t}\n\n\tasync get(storagePath: string): Promise<Uint8Array | null> {\n\t\ttry {\n\t\t\tconst buffer = await fs.readFile(this.resolvePath(storagePath));\n\t\t\treturn new Uint8Array(buffer);\n\t\t} catch (err) {\n\t\t\tif ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync put(storagePath: string, data: Uint8Array, contentType?: string): Promise<string> {\n\t\t// Rewrites images to .webp; non-images pass through untouched.\n\t\tconst transcoded = await transcodeImageIfNeeded(data, contentType, storagePath);\n\t\tconst fullPath = this.resolvePath(transcoded.path);\n\t\tawait fs.mkdir(path.dirname(fullPath), { recursive: true });\n\t\t// Temp and rename: an in-place overwrite truncates first, so a concurrent `get`\n\t\t// would come back short.\n\t\tconst tmp = `${fullPath}.${randomUUID()}.tmp`;\n\t\ttry {\n\t\t\tawait fs.writeFile(tmp, Buffer.from(transcoded.data));\n\t\t\tawait renameReplacing(tmp, fullPath);\n\t\t} catch (err) {\n\t\t\tawait fs.rm(tmp, { force: true }).catch(() => {});\n\t\t\tthrow err;\n\t\t}\n\t\treturn transcoded.path;\n\t}\n\n\tasync delete(storagePath: string): Promise<void> {\n\t\ttry {\n\t\t\tawait fs.unlink(this.resolvePath(storagePath));\n\t\t} catch (err) {\n\t\t\tif ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n\t\t}\n\t}\n\n\tasync deletePrefix(prefix: string): Promise<void> {\n\t\tconst fullPath = this.resolvePath(prefix);\n\t\t// The root is `DATA_PATH`, so this would take every store with it.\n\t\tif (fullPath === path.resolve(this.basePath)) {\n\t\t\tthrow new ProviderError(`Refusing to delete the whole store: ${JSON.stringify(prefix)}`, 400);\n\t\t}\n\t\tawait fs.rm(fullPath, { recursive: true, force: true });\n\t}\n\n\tgetPublicUrl(storagePath: string): string {\n\t\t// No CDN locally — every asset goes through the `/api/files` proxy, which\n\t\t// classifies the path (`classifyAssetPath`) and applies auth per visibility.\n\t\treturn `${this.publicUrlBase}/${storagePath}`;\n\t}\n}\n","import type { SupabaseClient } from '@supabase/supabase-js';\nimport { createClient } from '@supabase/supabase-js';\nimport { transcodeImageIfNeeded, classifyAssetPath } from '@selvajs/platform/storage';\nimport type { IStorageProvider } from '@selvajs/platform/storage';\nimport { ProviderError, trimTrailing } from '@selvajs/platform';\n\n/**\n * Storage backend for Selva on Supabase Storage. Routes each path to one of\n * two buckets: `publicBucket` (CDN-readable, `getPublicUrl` returns the\n * direct CDN URL) or `privateBucket` (`getPublicUrl` returns\n * `${privateUrlPrefix}/{path}` — the consuming app must route that prefix\n * through an auth check and `get()`).\n */\nexport interface SupabaseStorageProviderConfig {\n\t/** Supabase project URL (e.g. http://127.0.0.1:54321 for local stack). */\n\tsupabaseUrl: string;\n\t/**\n\t * Service-role key. The provider runs server-side and must bypass RLS\n\t * for server-internal actions (admin uploads, janitor cleanup) — never\n\t * used from the browser.\n\t */\n\tserviceRoleKey: string;\n\t/** Bucket for CDN-readable objects. Default: \"selva-public\". */\n\tpublicBucket?: string;\n\t/** Bucket for authenticated-only objects. Default: \"selva-private\". */\n\tprivateBucket?: string;\n\t/** URL prefix for authenticated file downloads, used by `getPublicUrl`. Default: \"/api/files\". */\n\tprivateUrlPrefix?: string;\n}\n\nconst LIST_PAGE_SIZE = 1000;\n\n/**\n * Supabase Storage refuses to upload a `..` key but answers a read of one with\n * not-found. Refusing here gives every method the local store's 400.\n */\nfunction assertNoClimb(storagePath: string): void {\n\tif (storagePath.split('/').includes('..')) {\n\t\tthrow new ProviderError(`Path escapes the store: ${JSON.stringify(storagePath)}`, 400);\n\t}\n}\n\nexport class SupabaseStorageProvider implements IStorageProvider {\n\tprivate readonly client: SupabaseClient;\n\tprivate readonly publicBucket: string;\n\tprivate readonly privateBucket: string;\n\tprivate readonly publicBaseUrl: string;\n\tprivate readonly privateUrlPrefix: string;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): SupabaseStorageProvider {\n\t\tconst supabaseUrl = env.SUPABASE_URL;\n\t\tconst serviceRoleKey = env.SUPABASE_SERVICE_ROLE_KEY;\n\t\tif (!supabaseUrl) throw new Error('Missing required env var: SUPABASE_URL');\n\t\tif (!serviceRoleKey) throw new Error('Missing required env var: SUPABASE_SERVICE_ROLE_KEY');\n\t\treturn new SupabaseStorageProvider({\n\t\t\tsupabaseUrl,\n\t\t\tserviceRoleKey,\n\t\t\tpublicBucket: env.SUPABASE_PUBLIC_BUCKET,\n\t\t\tprivateBucket: env.SUPABASE_PRIVATE_BUCKET\n\t\t});\n\t}\n\n\tconstructor(config: SupabaseStorageProviderConfig) {\n\t\tthis.client = createClient(config.supabaseUrl, config.serviceRoleKey, {\n\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t});\n\t\tthis.publicBucket = config.publicBucket ?? 'selva-public';\n\t\tthis.privateBucket = config.privateBucket ?? 'selva-private';\n\t\tthis.publicBaseUrl = `${config.supabaseUrl.replace(/\\/$/, '')}/storage/v1/object/public/${this.publicBucket}`;\n\t\tthis.privateUrlPrefix = (config.privateUrlPrefix ?? '/api/files').replace(/\\/$/, '');\n\t}\n\n\t/**\n\t * `.gh`/`.ghx` source files are always private, regardless of what\n\t * `classifyAssetPath` says — confidentiality by extension means a\n\t * path-scheme rename can't silently move sources into the public bucket.\n\t * Everything else routes by asset class, and only a `public` class reaches\n\t * the public bucket: an unclassified path stays private.\n\t */\n\tprivate bucketFor(storagePath: string): string {\n\t\tif (/\\.(gh|ghx)$/i.test(storagePath)) return this.privateBucket;\n\t\tconst cls = classifyAssetPath(storagePath);\n\t\treturn cls?.class.visibility === 'public' ? this.publicBucket : this.privateBucket;\n\t}\n\n\tasync get(storagePath: string): Promise<Uint8Array | null> {\n\t\tassertNoClimb(storagePath);\n\t\tconst bucket = this.bucketFor(storagePath);\n\t\tconst { data, error } = await this.client.storage.from(bucket).download(storagePath);\n\t\tif (error) {\n\t\t\t// storage-js has no stable status code for 404 — match the message instead.\n\t\t\tconst msg = (error as { message?: string }).message ?? '';\n\t\t\tif (/not found/i.test(msg) || /no such key/i.test(msg)) return null;\n\t\t\tthrow error;\n\t\t}\n\t\tconst buffer = await data.arrayBuffer();\n\t\treturn new Uint8Array(buffer);\n\t}\n\n\tasync put(storagePath: string, data: Uint8Array, contentType?: string): Promise<string> {\n\t\tassertNoClimb(storagePath);\n\t\tconst transcoded = await transcodeImageIfNeeded(data, contentType, storagePath);\n\t\tconst bucket = this.bucketFor(transcoded.path);\n\t\tconst { error } = await this.client.storage\n\t\t\t.from(bucket)\n\t\t\t.upload(transcoded.path, transcoded.data, {\n\t\t\t\tcontentType: transcoded.contentType,\n\t\t\t\t// `put` upserts, so a changed object needs a new URL: `withCacheBust` is\n\t\t\t\t// how callers get one. A year is safe only because of that.\n\t\t\t\tcacheControl: '31536000',\n\t\t\t\tupsert: true\n\t\t\t});\n\t\tif (error) throw error;\n\t\treturn transcoded.path;\n\t}\n\n\tasync delete(storagePath: string): Promise<void> {\n\t\tassertNoClimb(storagePath);\n\t\tconst bucket = this.bucketFor(storagePath);\n\t\tconst { error } = await this.client.storage.from(bucket).remove([storagePath]);\n\t\tif (error) throw error;\n\t}\n\n\tasync deletePrefix(prefix: string): Promise<void> {\n\t\tassertNoClimb(prefix);\n\t\tif (trimTrailing(prefix, '/') === '') {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Refusing to delete the whole store: prefix ${JSON.stringify(prefix)}`,\n\t\t\t\t400\n\t\t\t);\n\t\t}\n\t\t// A definition's GUID prefix may have files in either bucket.\n\t\tawait Promise.all([\n\t\t\tthis.deletePrefixInBucket(this.publicBucket, prefix),\n\t\t\tthis.deletePrefixInBucket(this.privateBucket, prefix)\n\t\t]);\n\t}\n\n\tprivate async deletePrefixInBucket(bucket: string, prefix: string): Promise<void> {\n\t\tconst normalized = trimTrailing(prefix, '/');\n\t\tconst keys = await this.listAllKeys(bucket, normalized);\n\t\tif (keys.length === 0) return;\n\t\t// remove() caps out at 1000 paths per call.\n\t\tfor (let i = 0; i < keys.length; i += 1000) {\n\t\t\tconst slice = keys.slice(i, i + 1000);\n\t\t\tconst { error } = await this.client.storage.from(bucket).remove(slice);\n\t\t\tif (error) throw error;\n\t\t}\n\t}\n\n\t/** storage-js's `list` only returns immediate children of a \"folder\", so DFS to get everything under `prefix`. */\n\tprivate async listAllKeys(bucket: string, prefix: string): Promise<string[]> {\n\t\tconst out: string[] = [];\n\t\tconst stack: string[] = [prefix];\n\t\twhile (stack.length > 0) {\n\t\t\tconst dir = stack.pop()!;\n\t\t\tfor (let offset = 0; ; offset += LIST_PAGE_SIZE) {\n\t\t\t\tconst { data, error } = await this.client.storage.from(bucket).list(dir, {\n\t\t\t\t\tlimit: LIST_PAGE_SIZE,\n\t\t\t\t\toffset,\n\t\t\t\t\tsortBy: { column: 'name', order: 'asc' }\n\t\t\t\t});\n\t\t\t\tif (error) throw error;\n\t\t\t\tconst entries = data ?? [];\n\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\tconst full = dir ? `${dir}/${entry.name}` : entry.name;\n\t\t\t\t\t// storage-js marks folder entries with id === null.\n\t\t\t\t\tif (entry.id === null) {\n\t\t\t\t\t\tstack.push(full);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout.push(full);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (entries.length < LIST_PAGE_SIZE) break;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\tgetPublicUrl(storagePath: string): string {\n\t\tif (this.bucketFor(storagePath) === this.publicBucket) {\n\t\t\treturn `${this.publicBaseUrl}/${storagePath}`;\n\t\t}\n\t\treturn `${this.privateUrlPrefix}/${storagePath}`;\n\t}\n}\n","import { ProviderError } from '@selvajs/platform';\n\n/**\n * PostgREST/Postgres error translation shared by every Supabase store.\n *\n * `PGRST116` (the code `.single()` raises when a selector matches zero rows)\n * maps to 404 — that's almost always what a store's caller wants. So does\n * `P0002`, which our RPCs raise for a missing row. `42501` (RLS or a privilege\n * refusing the caller) maps to 403. Unique and FK violations map to 409.\n * Anything else becomes a plain `Error` (500\n * downstream via `api-errors`), with `details`/`hint`/`code` preserved on the\n * error object for logs.\n */\ninterface PostgrestErrorShape {\n\tcode?: string;\n\tmessage?: string;\n\tdetails?: string;\n\thint?: string;\n}\n\nexport function mapPostgrestError(e: unknown): Error {\n\tconst pg = e as PostgrestErrorShape;\n\tswitch (pg?.code) {\n\t\tcase 'PGRST116':\n\t\tcase 'P0002':\n\t\t\treturn new ProviderError(pg.message ?? 'Not found', 404);\n\t\tcase '42501':\n\t\t\treturn new ProviderError(pg.message ?? 'Forbidden', 403);\n\t\tcase '23505':\n\t\t\treturn new ProviderError(pg.message ?? 'Duplicate record', 409);\n\t\tcase '23503':\n\t\t\treturn new ProviderError(pg.message ?? 'Foreign key violation', 409);\n\t}\n\tif (e instanceof Error) return e;\n\tif (e && typeof e === 'object') {\n\t\tconst obj = e as PostgrestErrorShape;\n\t\tconst msg = obj.message ?? obj.details ?? obj.hint ?? 'Unknown Postgres error';\n\t\tconst err = new Error(obj.code ? `[${obj.code}] ${msg}` : msg);\n\t\tObject.assign(err, obj);\n\t\treturn err;\n\t}\n\treturn new Error(String(e));\n}\n","import type {\n\tIPlatformProjectGrantStore,\n\tPlatformProjectGrant,\n\tRequestContext\n} from '@selvajs/platform';\nimport { ERASED_ACTOR_ID, ProviderError } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\n\nconst GRANT_COLUMNS = 'id, project_id, grantee_type, grantee_id, can_solve, created_by, created_at';\n\n/** Reads go through the caller's client, so RLS shows a grantee only its own grants. */\nexport class SupabasePlatformProjectGrantStore implements IPlatformProjectGrantStore {\n\tconstructor(private readonly clients: ClientBundle) {}\n\n\tasync listByProject(ctx: RequestContext, projectId: string): Promise<PlatformProjectGrant[]> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('platform_project_grants')\n\t\t\t.select(GRANT_COLUMNS)\n\t\t\t.eq('project_id', projectId)\n\t\t\t.order('created_at', { ascending: true });\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn (data ?? []).map(rowToGrant);\n\t}\n\n\tasync listByProjects(\n\t\tctx: RequestContext,\n\t\tprojectIds: readonly string[]\n\t): Promise<Map<string, PlatformProjectGrant[]>> {\n\t\tconst result = new Map(projectIds.map((id) => [id, [] as PlatformProjectGrant[]]));\n\t\tif (projectIds.length === 0) return result;\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('platform_project_grants')\n\t\t\t.select(GRANT_COLUMNS)\n\t\t\t.in('project_id', [...projectIds])\n\t\t\t.order('created_at', { ascending: true });\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of data ?? []) {\n\t\t\tconst grant = rowToGrant(row);\n\t\t\tresult.get(grant.projectId)?.push(grant);\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync create(_ctx: RequestContext, grant: PlatformProjectGrant): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('platform_project_grants')\n\t\t\t.insert(grantToRow(grant));\n\t\tif (error?.code === '23505' && error.message.includes('platform_project_grants_grantee_key')) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`A grant for this ${grant.granteeType} already exists on this project`,\n\t\t\t\t409\n\t\t\t);\n\t\t}\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync delete(_ctx: RequestContext, id: string): Promise<void> {\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('platform_project_grants')\n\t\t\t.delete()\n\t\t\t.eq('id', id)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) throw new ProviderError(`Grant '${id}' not found`, 404);\n\t}\n\n\tasync deleteByProject(_ctx: RequestContext, projectId: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('platform_project_grants')\n\t\t\t.delete()\n\t\t\t.eq('project_id', projectId);\n\t\tif (error && !isMissingTable(error)) throw mapPostgrestError(error);\n\t}\n\n\tasync deleteByGranteeOrg(_ctx: RequestContext, orgId: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('platform_project_grants')\n\t\t\t.delete()\n\t\t\t.eq('grantee_type', 'org')\n\t\t\t.eq('grantee_id', orgId);\n\t\tif (error && !isMissingTable(error)) throw mapPostgrestError(error);\n\t}\n\n\t/** A user grant is the user's own, so it goes with them; one they created stays. */\n\tasync eraseUser(userId: string): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst deleted = await client\n\t\t\t.from('platform_project_grants')\n\t\t\t.delete()\n\t\t\t.eq('grantee_type', 'user')\n\t\t\t.eq('grantee_id', userId);\n\t\tif (deleted.error) {\n\t\t\tif (isMissingTable(deleted.error)) return;\n\t\t\tthrow mapPostgrestError(deleted.error);\n\t\t}\n\t\tconst anonymized = await client\n\t\t\t.from('platform_project_grants')\n\t\t\t.update({ created_by: null })\n\t\t\t.eq('created_by', userId);\n\t\tif (anonymized.error) throw mapPostgrestError(anonymized.error);\n\t}\n}\n\n/**\n * Deleting an org, a project or a user runs these cleanups on every deployment, also one whose\n * database is still behind `20261117200000`, which the migration handshake lets boot. Without the\n * table there is nothing to clean up.\n */\nfunction isMissingTable(error: { code?: string }): boolean {\n\treturn error.code === 'PGRST205' || error.code === '42P01';\n}\n\ninterface GrantRow {\n\tid: string;\n\tproject_id: string;\n\tgrantee_type: PlatformProjectGrant['granteeType'];\n\tgrantee_id: string;\n\tcan_solve: boolean;\n\tcreated_by: string | null;\n\tcreated_at: string;\n}\n\nfunction rowToGrant(row: GrantRow): PlatformProjectGrant {\n\treturn {\n\t\tid: row.id,\n\t\tprojectId: row.project_id,\n\t\tgranteeType: row.grantee_type,\n\t\tgranteeId: row.grantee_id,\n\t\tcanSolve: row.can_solve,\n\t\tcreatedBy: row.created_by ?? ERASED_ACTOR_ID,\n\t\tcreatedAt: row.created_at\n\t};\n}\n\nfunction grantToRow(g: PlatformProjectGrant): GrantRow {\n\treturn {\n\t\tid: g.id,\n\t\tproject_id: g.projectId,\n\t\tgrantee_type: g.granteeType,\n\t\tgrantee_id: g.granteeId,\n\t\tcan_solve: g.canSolve,\n\t\tcreated_by: g.createdBy === ERASED_ACTOR_ID ? null : g.createdBy,\n\t\tcreated_at: g.createdAt\n\t};\n}\n","/**\n * `ListOptions.cursor` is meant to be opaque; here it's just an offset\n * encoded as a string. Simple and correct for stable sorts, fine at Selva's\n * scale (bounded admin/definition lists, not infinite scroll over millions\n * of rows). Keyset pagination would be faster if that ever changes.\n */\n\nimport { clampPageLimit, decodeOffsetCursor, encodeOffsetCursor } from '@selvajs/platform';\nimport type { ListOptions } from '@selvajs/platform';\n\nexport interface RangeSpec {\n\tfrom: number;\n\tto: number;\n\tlimit: number;\n}\n\nexport { decodeOffsetCursor as decodeCursor, encodeOffsetCursor as encodeCursor };\n\nexport function toRange(opts: Pick<ListOptions, 'limit' | 'cursor'> | undefined): RangeSpec {\n\tconst limit = clampPageLimit(opts?.limit);\n\tconst from = decodeOffsetCursor(opts?.cursor);\n\treturn { from, to: from + limit - 1, limit };\n}\n\nexport function nextCursorFromRange(\n\trange: RangeSpec,\n\treturnedCount: number,\n\ttotalCount: number | null | undefined\n): string | undefined {\n\tconst consumed = range.from + returnedCount;\n\tif (totalCount != null) {\n\t\treturn consumed < totalCount ? encodeOffsetCursor(consumed) : undefined;\n\t}\n\t// Without total, we can only infer \"there might be more\" if we got a full page.\n\treturn returnedCount >= range.limit ? encodeOffsetCursor(consumed) : undefined;\n}\n\nexport function orderColumn(orderBy: ListOptions['orderBy'] | undefined): string {\n\tswitch (orderBy) {\n\t\tcase 'name':\n\t\t\treturn 'name';\n\t\tcase 'updatedAt':\n\t\t\treturn 'updated_at';\n\t\tcase 'createdAt':\n\t\tdefault:\n\t\t\treturn 'created_at';\n\t}\n}\n","import type { RequestContext } from '@selvajs/platform';\nimport { auditSoftDelete } from '@selvajs/platform';\n\n/**\n * Translates platform's camelCase audit fields (`updatedAt`/`updatedBy`) to\n * the snake_case columns every Supabase row uses.\n *\n * `updated_by` is written only when `ctx.userId` is set. On system contexts\n * `auditUpdate`/`auditSoftDelete` fall back to `''`, and the column FKs\n * `auth.users(id)` — writing `''` violates the FK — so it's omitted instead,\n * leaving the existing value untouched.\n *\n * Plain updates don't stamp `updated_at`: a per-table trigger already sets\n * it. Only soft-delete sets `updated_at` explicitly, to match `deleted_at`.\n */\n\nexport function stampUpdate(ctx: RequestContext): { updated_by?: string } {\n\treturn ctx.userId ? { updated_by: ctx.userId } : {};\n}\n\nexport function stampSoftDelete(\n\tctx: RequestContext,\n\tfallbackActor: string | null | undefined = ctx.userId\n): { deleted_at: string; updated_at: string; updated_by?: string } {\n\tconst stamp = auditSoftDelete(ctx, fallbackActor);\n\tconst row: { deleted_at: string; updated_at: string; updated_by?: string } = {\n\t\tdeleted_at: stamp.deletedAt,\n\t\tupdated_at: stamp.updatedAt\n\t};\n\tif (stamp.updatedBy) row.updated_by = stamp.updatedBy;\n\treturn row;\n}\n","import type {\n\tIOrgStore,\n\tIEventSink,\n\tOrganization,\n\tOrgMember,\n\tOrgRole,\n\tOrgPermission,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport {\n\tDEFAULT_ORG_PERMISSIONS,\n\tERASED_ACTOR_ID,\n\tProviderError,\n\tactorOf,\n\tNoopEventSink\n} from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { SupabasePlatformProjectGrantStore } from './SupabasePlatformProjectGrantStore.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, orderColumn, toRange } from './pagination.js';\nimport { stampSoftDelete, stampUpdate } from './rowStamp.js';\n\n/** Explicit column list for `orgs` — every field `rowToOrg` consumes. */\nconst ORG_COLUMNS =\n\t'id, name, slug, owner_id, assets, created_by, updated_by, created_at, updated_at, deleted_at';\n/** Explicit column list for `org_members` — every field `rowToOrgMember` consumes. */\nconst ORG_MEMBER_COLUMNS =\n\t'org_id, user_id, role, permissions, joined_at, updated_at, updated_by, deleted_at';\n\n/**\n * Org + org-membership store backed by Postgres. Reads run as the caller, so\n * RLS decides what they see. Writes run as the service role: the app has\n * already decided, and sessions hold no write privilege.\n */\nexport class SupabaseOrgStore implements IOrgStore {\n\tprivate readonly events: IEventSink;\n\n\t/** Grants have no soft-delete: deleting an org removes the grants it holds and those on its projects. */\n\tprivate readonly grants: SupabasePlatformProjectGrantStore;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tevents: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.events = events;\n\t\tthis.grants = new SupabasePlatformProjectGrantStore(clients);\n\t}\n\n\tasync listOrgs(ctx: RequestContext, opts?: ListOptions): Promise<Page<Organization>> {\n\t\tconst range = toRange(opts);\n\t\tconst direction = opts?.orderDir ?? 'desc';\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('orgs')\n\t\t\t.select(ORG_COLUMNS, { count: 'exact' })\n\t\t\t.is('deleted_at', null)\n\t\t\t.order(orderColumn(opts?.orderBy), { ascending: direction === 'asc' })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToOrg);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync getOrg(ctx: RequestContext, id: string): Promise<Organization | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('orgs')\n\t\t\t.select(ORG_COLUMNS)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToOrg(data) : null;\n\t}\n\n\tasync getOrgBySlug(ctx: RequestContext, slug: string): Promise<Organization | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('orgs')\n\t\t\t.select(ORG_COLUMNS)\n\t\t\t.eq('slug', slug)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToOrg(data) : null;\n\t}\n\n\tasync createOrg(ctx: RequestContext, org: Organization): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst { error } = await client.from('orgs').insert(orgToRow(org));\n\t\tif (error) throw mapPostgrestError(error);\n\n\t\t// Seed owner membership: RLS hides an org from anyone who is not a member,\n\t\t// its creator included. Upsert so a\n\t\t// stale soft-deleted row from a prior org with the same id is reactivated\n\t\t// rather than blocking creation.\n\t\tconst { error: memberError } = await client.from('org_members').upsert(\n\t\t\t{\n\t\t\t\torg_id: org.id,\n\t\t\t\tuser_id: org.ownerId,\n\t\t\t\trole: 'owner',\n\t\t\t\tpermissions: [...DEFAULT_ORG_PERMISSIONS.owner],\n\t\t\t\tjoined_at: new Date().toISOString(),\n\t\t\t\tdeleted_at: null\n\t\t\t},\n\t\t\t{ onConflict: 'org_id,user_id' }\n\t\t);\n\t\tif (memberError) throw mapPostgrestError(memberError);\n\t\tawait this.events.emit({ type: 'org.created', orgId: org.id, ...actorOf(ctx) });\n\t}\n\n\tasync updateOrg(\n\t\tctx: RequestContext,\n\t\tid: string,\n\t\tpatch: Partial<Pick<Organization, 'name' | 'slug' | 'assets'>>\n\t): Promise<void> {\n\t\tconst row: Record<string, unknown> = {};\n\t\tif (patch.name !== undefined) row.name = patch.name;\n\t\tif (patch.slug !== undefined) row.slug = patch.slug;\n\t\t// Callers pass the full merged map — store it as-is (JSONB column, no partial merge).\n\t\tif (patch.assets !== undefined) row.assets = patch.assets;\n\t\tif (Object.keys(row).length === 0) return;\n\t\t// `updated_at` is set by the trg_orgs_updated_at trigger; `stampUpdate`\n\t\t// only adds `updated_by`, and only when ctx.userId is set (empty on\n\t\t// system contexts would violate the `on delete set null` FK).\n\t\tObject.assign(row, stampUpdate(ctx));\n\n\t\tconst { error, data } = await this.clients.serviceClient\n\t\t\t.from('orgs')\n\t\t\t.update(row)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) throw new ProviderError(`Org '${id}' not found`, 404);\n\t}\n\n\tasync deleteOrg(ctx: RequestContext, id: string): Promise<void> {\n\t\t// Soft-delete with cascade, mirroring LocalOrgStore: org → org_members,\n\t\t// projects → project_members, definitions. Hard delete is reserved for\n\t\t// the background janitor; user-facing deletes preserve the audit trail.\n\t\tconst client = this.clients.serviceClient;\n\t\tconst stampRow = stampSoftDelete(ctx);\n\n\t\tconst { error: orgErr, data: orgData } = await client\n\t\t\t.from('orgs')\n\t\t\t.update(stampRow)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('id');\n\t\tif (orgErr) throw mapPostgrestError(orgErr);\n\t\tif (!orgData || orgData.length === 0) throw new ProviderError(`Org '${id}' not found`, 404);\n\n\t\tconst { error: omErr } = await client\n\t\t\t.from('org_members')\n\t\t\t.update(stampRow)\n\t\t\t.eq('org_id', id)\n\t\t\t.is('deleted_at', null);\n\t\tif (omErr) throw mapPostgrestError(omErr);\n\n\t\t// Fetch project IDs first so app code can cascade to project_members and\n\t\t// definitions — Postgres FK CASCADE only fires on hard DELETE, and this is a soft one.\n\t\tconst { data: orgProjects, error: projFetchErr } = await client\n\t\t\t.from('projects')\n\t\t\t.select('id')\n\t\t\t.eq('org_id', id)\n\t\t\t.is('deleted_at', null);\n\t\tif (projFetchErr) throw mapPostgrestError(projFetchErr);\n\t\tconst projectIds = (orgProjects ?? []).map((p) => p.id as string);\n\n\t\tconst { error: projErr } = await client\n\t\t\t.from('projects')\n\t\t\t.update(stampRow)\n\t\t\t.eq('org_id', id)\n\t\t\t.is('deleted_at', null);\n\t\tif (projErr) throw mapPostgrestError(projErr);\n\n\t\tif (projectIds.length > 0) {\n\t\t\tconst { error: pmErr } = await client\n\t\t\t\t.from('project_members')\n\t\t\t\t.update(stampRow)\n\t\t\t\t.in('project_id', projectIds)\n\t\t\t\t.is('deleted_at', null);\n\t\t\tif (pmErr) throw mapPostgrestError(pmErr);\n\n\t\t\tconst { error: defErr } = await client\n\t\t\t\t.from('definitions')\n\t\t\t\t.update(stampRow)\n\t\t\t\t.in('project_id', projectIds)\n\t\t\t\t.is('deleted_at', null);\n\t\t\tif (defErr) throw mapPostgrestError(defErr);\n\t\t}\n\n\t\t// These tables have no `deleted_at` column, and the org soft-delete above\n\t\t// doesn't trigger their FK CASCADE, so clean them up explicitly. Pending\n\t\t// invites and API keys for a dead org are unusable; stale compute config\n\t\t// is operational state with no audit need.\n\t\tconst { error: invErr } = await client.from('invites').delete().eq('org_id', id);\n\t\tif (invErr) throw mapPostgrestError(invErr);\n\n\t\tawait this.grants.deleteByGranteeOrg(ctx, id);\n\t\tfor (const projectId of projectIds) await this.grants.deleteByProject(ctx, projectId);\n\n\t\tconst { error: tokErr } = await client.from('api_tokens').delete().eq('org_id', id);\n\t\tif (tokErr) throw mapPostgrestError(tokErr);\n\n\t\tconst { error: cdErr } = await client\n\t\t\t.from('compute_server_org_defaults')\n\t\t\t.delete()\n\t\t\t.eq('org_id', id);\n\t\tif (cdErr) throw mapPostgrestError(cdErr);\n\n\t\tconst { error: shErr } = await client.from('compute_server_shares').delete().eq('org_id', id);\n\t\tif (shErr) throw mapPostgrestError(shErr);\n\n\t\tconst { error: csErr } = await client\n\t\t\t.from('compute_servers')\n\t\t\t.delete()\n\t\t\t.eq('scope', 'org')\n\t\t\t.eq('owner_org_id', id);\n\t\tif (csErr) throw mapPostgrestError(csErr);\n\n\t\tawait this.events.emit({ type: 'org.deleted', orgId: id, ...actorOf(ctx) });\n\t}\n\n\t// ============================================================================\n\t// Org members\n\t// ============================================================================\n\tasync listOrgMembers(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<OrgMember>> {\n\t\tconst range = toRange(opts);\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('org_members')\n\t\t\t.select(ORG_MEMBER_COLUMNS, { count: 'exact' })\n\t\t\t.eq('org_id', orgId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.order('joined_at', { ascending: (opts?.orderDir ?? 'desc') === 'asc' })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToOrgMember);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync getOrgMember(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string\n\t): Promise<OrgMember | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('org_members')\n\t\t\t.select(ORG_MEMBER_COLUMNS)\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToOrgMember(data) : null;\n\t}\n\n\t// One head count per org, in parallel: tallying selected rows would be capped by\n\t// PostgREST's max-rows, and grouped aggregates are off by default.\n\tasync countOrgMembers(\n\t\tctx: RequestContext,\n\t\torgIds: readonly string[]\n\t): Promise<Map<string, number>> {\n\t\tconst client = this.clients.forRequest(ctx);\n\t\tconst counts = await Promise.all(\n\t\t\torgIds.map(async (orgId) => {\n\t\t\t\tconst { count, error } = await client\n\t\t\t\t\t.from('org_members')\n\t\t\t\t\t.select('user_id', { count: 'exact', head: true })\n\t\t\t\t\t.eq('org_id', orgId)\n\t\t\t\t\t.is('deleted_at', null);\n\t\t\t\tif (error) throw mapPostgrestError(error);\n\t\t\t\treturn [orgId, count ?? 0] as const;\n\t\t\t})\n\t\t);\n\t\treturn new Map(counts);\n\t}\n\n\tasync getOrgMembersFor(\n\t\tctx: RequestContext,\n\t\torgIds: readonly string[],\n\t\tuserId: string\n\t): Promise<Map<string, OrgMember | null>> {\n\t\tconst result = new Map<string, OrgMember | null>(orgIds.map((id) => [id, null]));\n\t\tif (orgIds.length === 0) return result;\n\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('org_members')\n\t\t\t.select(ORG_MEMBER_COLUMNS)\n\t\t\t.in('org_id', [...orgIds])\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of data ?? []) result.set(row.org_id, rowToOrgMember(row));\n\t\treturn result;\n\t}\n\n\tasync findUserMembership(\n\t\tctx: RequestContext,\n\t\tuserId: string\n\t): Promise<{ org: Organization; member: OrgMember } | null> {\n\t\t// One round-trip: join org_members → orgs and filter live rows on\n\t\t// both sides. PostgREST `!inner` on the join keeps it a single SELECT,\n\t\t// avoiding the listOrgs + getOrgMember-per-org N+1 the bootstrap path\n\t\t// used to do. RLS still scopes by ctx; service-role sees all.\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('org_members')\n\t\t\t.select(`${ORG_MEMBER_COLUMNS}, org:orgs!inner(${ORG_COLUMNS})`)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.is('org.deleted_at', null)\n\t\t\t.order('joined_at', { ascending: true })\n\t\t\t.limit(1)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data) return null;\n\n\t\t// PostgREST embeds the related row as `org` per the alias above. Strip\n\t\t// it off the member row before mapping so OrgMember stays clean.\n\t\tconst row = data as OrgMemberRow & { org: OrgRow | OrgRow[] };\n\t\tconst orgRow = Array.isArray(row.org) ? row.org[0] : row.org;\n\t\tif (!orgRow) return null;\n\t\tconst { org: _omit, ...memberRow } = row;\n\t\treturn {\n\t\t\torg: rowToOrg(orgRow),\n\t\t\tmember: rowToOrgMember(memberRow as OrgMemberRow)\n\t\t};\n\t}\n\n\tasync addOrgMember(ctx: RequestContext, member: OrgMember): Promise<void> {\n\t\t// Upsert so a prior soft-deleted row is reactivated rather than throwing\n\t\t// a duplicate-key error. Mirrors LocalOrgStore.addOrgMember.\n\t\tconst row: Record<string, unknown> = {\n\t\t\t...memberToRow(member),\n\t\t\tdeleted_at: null,\n\t\t\t...stampUpdate(ctx)\n\t\t};\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('org_members')\n\t\t\t.upsert(row, { onConflict: 'org_id,user_id' });\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.added',\n\t\t\torgId: member.orgId,\n\t\t\tuserId: member.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateOrgMemberRole(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string,\n\t\trole: OrgRole\n\t): Promise<void> {\n\t\t// Matches LocalOrgStore: changing role re-seeds default permissions for that role.\n\t\tconst row: Record<string, unknown> = {\n\t\t\trole,\n\t\t\tpermissions: [...DEFAULT_ORG_PERMISSIONS[role]],\n\t\t\t...stampUpdate(ctx)\n\t\t};\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('org_members')\n\t\t\t.update(row)\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0)\n\t\t\tthrow new ProviderError(`Org member '${userId}' not found`, 404);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.role_changed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\trole,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateOrgMemberPermissions(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string,\n\t\tpermissions: readonly OrgPermission[]\n\t): Promise<void> {\n\t\t// Distinct from updateOrgMemberRole so callers can grant a finer-grained\n\t\t// set without re-seeding defaults from the role. Matches LocalOrgStore.\n\t\tconst row: Record<string, unknown> = { permissions: [...permissions], ...stampUpdate(ctx) };\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('org_members')\n\t\t\t.update(row)\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0)\n\t\t\tthrow new ProviderError(`Org member '${userId}' not found`, 404);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.permissions_changed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\tpermissions: [...permissions],\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync removeOrgMember(ctx: RequestContext, orgId: string, userId: string): Promise<void> {\n\t\t// An RPC so the membership and the leaver's project memberships end in one\n\t\t// transaction.\n\t\tconst svc = this.clients.serviceClient;\n\t\tlet { error } = await svc.rpc('remove_org_member', {\n\t\t\to: orgId,\n\t\t\tu: userId,\n\t\t\tactor: ctx.userId || null\n\t\t});\n\t\t// The app updates before `20261113120000` is pushed, and the function it\n\t\t// replaces takes no actor. Drop this once that migration is the floor.\n\t\tif (error?.code === 'PGRST202') {\n\t\t\t({ error } = await svc.rpc('remove_org_member', { o: orgId, u: userId }));\n\t\t}\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.removed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Row ↔ domain mappers\n// ============================================================================\n//\n// Audit columns (`created_by` / `updated_by`) FK to `auth.users(id)` with\n// `ON DELETE SET NULL`, so they can legitimately become NULL when the\n// referenced user is deleted. Mappers fall back to `owner_id` / `user_id` so\n// the domain type stays non-nullable; UIs that care about creator-vs-owner\n// attribution should render \"Deleted user\" at that layer.\n\ninterface OrgRow {\n\tid: string;\n\tname: string;\n\tslug: string;\n\towner_id: string | null;\n\tassets?: Record<string, string> | null;\n\tcreated_by?: string | null;\n\tupdated_by?: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n\tdeleted_at?: string | null;\n}\n\ninterface OrgMemberRow {\n\torg_id: string;\n\tuser_id: string;\n\trole: OrgRole;\n\tpermissions: string[];\n\tjoined_at: string;\n\tupdated_at?: string | null;\n\tupdated_by?: string | null;\n\tdeleted_at?: string | null;\n}\n\nfunction rowToOrg(row: OrgRow): Organization {\n\tconst owner = row.owner_id ?? ERASED_ACTOR_ID;\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\townerId: owner,\n\t\tassets: row.assets ?? undefined,\n\t\tcreatedBy: row.created_by ?? owner,\n\t\tupdatedBy: row.updated_by ?? owner,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tdeletedAt: row.deleted_at ?? null\n\t};\n}\n\nfunction orgToRow(org: Organization): OrgRow {\n\treturn {\n\t\tid: org.id,\n\t\tname: org.name,\n\t\tslug: org.slug,\n\t\towner_id: org.ownerId,\n\t\t// `assets` is `not null default '{}'` — an explicit null defeats the\n\t\t// default and violates the constraint.\n\t\tassets: org.assets ?? {},\n\t\tcreated_by: org.createdBy,\n\t\tupdated_by: org.updatedBy,\n\t\tcreated_at: org.createdAt,\n\t\tupdated_at: org.updatedAt,\n\t\tdeleted_at: org.deletedAt ?? null\n\t};\n}\n\nfunction rowToOrgMember(row: OrgMemberRow): OrgMember {\n\treturn {\n\t\torgId: row.org_id,\n\t\tuserId: row.user_id,\n\t\trole: row.role,\n\t\tpermissions: (row.permissions ?? []) as OrgMember['permissions'],\n\t\tjoinedAt: row.joined_at,\n\t\tupdatedAt: row.updated_at ?? row.joined_at,\n\t\tupdatedBy: row.updated_by ?? row.user_id,\n\t\tdeletedAt: row.deleted_at ?? null\n\t};\n}\n\nfunction memberToRow(m: OrgMember): OrgMemberRow {\n\treturn {\n\t\torg_id: m.orgId,\n\t\tuser_id: m.userId,\n\t\trole: m.role,\n\t\tpermissions: m.permissions ?? [],\n\t\tjoined_at: m.joinedAt\n\t};\n}\n","import type {\n\tIProjectStore,\n\tIEventSink,\n\tProject,\n\tProjectMember,\n\tProjectRole,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { ERASED_ACTOR_ID, ProviderError, actorOf, NoopEventSink } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { SupabasePlatformProjectGrantStore } from './SupabasePlatformProjectGrantStore.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, orderColumn, toRange } from './pagination.js';\nimport { stampSoftDelete, stampUpdate } from './rowStamp.js';\n\n/** Explicit column list for `projects` — every field `rowToProject` consumes. */\nconst PROJECT_COLUMNS =\n\t'id, org_id, name, slug, description, visibility, owner_id, created_by, updated_by, auto_join_on_upload, created_at, updated_at, deleted_at';\n/** Explicit column list for `project_members` — every field `rowToProjectMember` consumes. */\nconst PROJECT_MEMBER_COLUMNS =\n\t'project_id, user_id, role, joined_at, updated_at, updated_by, deleted_at';\n\n/**\n * Project + project-membership store backed by Postgres. Visibility (public /\n * org / private) is enforced by the `visible_project()` RLS helper. Access\n * predicates (canEdit / canManage / canView) live in `@selvajs/platform/access`;\n * the route layer composes them with pre-loaded entities.\n */\nexport class SupabaseProjectStore implements IProjectStore {\n\tprivate readonly events: IEventSink;\n\n\t/** Grants have no soft-delete: deleting a project removes its grants, as in the local provider. */\n\tprivate readonly grants: SupabasePlatformProjectGrantStore;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tevents: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.events = events;\n\t\tthis.grants = new SupabasePlatformProjectGrantStore(clients);\n\t}\n\n\tasync listProjects(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<Project>> {\n\t\tconst range = toRange(opts);\n\t\tconst direction = opts?.orderDir ?? 'desc';\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('projects')\n\t\t\t.select(PROJECT_COLUMNS, { count: 'exact' })\n\t\t\t.eq('org_id', orgId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.order(orderColumn(opts?.orderBy), { ascending: direction === 'asc' })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToProject);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync getProject(ctx: RequestContext, id: string): Promise<Project | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('projects')\n\t\t\t.select(PROJECT_COLUMNS)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToProject(data) : null;\n\t}\n\n\tasync getProjectBySlug(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tslug: string\n\t): Promise<Project | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('projects')\n\t\t\t.select(PROJECT_COLUMNS)\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('slug', slug)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToProject(data) : null;\n\t}\n\n\tasync createProject(ctx: RequestContext, project: Project): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst { error } = await client.from('projects').insert(projectToRow(project));\n\t\tif (error) throw mapPostgrestError(error);\n\n\t\t// Upsert: a stale soft-deleted row from a prior project with this id\n\t\t// gets reactivated instead of blocking creation.\n\t\tconst { error: memberError } = await client.from('project_members').upsert(\n\t\t\t{\n\t\t\t\tproject_id: project.id,\n\t\t\t\tuser_id: project.ownerId,\n\t\t\t\trole: 'owner',\n\t\t\t\tjoined_at: new Date().toISOString(),\n\t\t\t\tdeleted_at: null\n\t\t\t},\n\t\t\t{ onConflict: 'project_id,user_id' }\n\t\t);\n\t\tif (memberError) throw mapPostgrestError(memberError);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project.created',\n\t\t\tprojectId: project.id,\n\t\t\torgId: project.orgId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateProject(\n\t\tctx: RequestContext,\n\t\tid: string,\n\t\tpatch: Partial<\n\t\t\tPick<Project, 'name' | 'slug' | 'description' | 'visibility' | 'autoJoinOnUpload'>\n\t\t>\n\t): Promise<void> {\n\t\tconst row: Record<string, unknown> = {};\n\t\tif (patch.name !== undefined) row.name = patch.name;\n\t\tif (patch.slug !== undefined) row.slug = patch.slug;\n\t\tif (patch.description !== undefined) row.description = patch.description;\n\t\tif (patch.visibility !== undefined) row.visibility = patch.visibility;\n\t\tif (patch.autoJoinOnUpload !== undefined) row.auto_join_on_upload = patch.autoJoinOnUpload;\n\t\tif (Object.keys(row).length === 0) return;\n\t\tObject.assign(row, stampUpdate(ctx));\n\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('projects')\n\t\t\t.update(row)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) throw new ProviderError(`Project '${id}' not found`, 404);\n\t}\n\n\tasync deleteProject(ctx: RequestContext, id: string): Promise<void> {\n\t\t// Soft-delete cascades in app code, not via FK: project → project_members,\n\t\t// definitions. FK CASCADE only fires on a real DELETE.\n\t\tconst client = this.clients.serviceClient;\n\t\tconst stampRow = stampSoftDelete(ctx);\n\n\t\tconst { data, error } = await client\n\t\t\t.from('projects')\n\t\t\t.update(stampRow)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) throw new ProviderError(`Project '${id}' not found`, 404);\n\n\t\tconst { error: pmErr } = await client\n\t\t\t.from('project_members')\n\t\t\t.update(stampRow)\n\t\t\t.eq('project_id', id)\n\t\t\t.is('deleted_at', null);\n\t\tif (pmErr) throw mapPostgrestError(pmErr);\n\n\t\t// Cascades to definitions inline instead of delegating to the definition\n\t\t// store, to avoid a cross-store constructor dependency. Must stay in sync\n\t\t// with SupabaseDefinitionStore.deleteByProject.\n\t\tconst { data: deletedDefs, error: defErr } = await client\n\t\t\t.from('definitions')\n\t\t\t.update(stampRow)\n\t\t\t.eq('project_id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (defErr) throw mapPostgrestError(defErr);\n\t\tfor (const row of deletedDefs ?? []) {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'definition.deleted',\n\t\t\t\tdefinitionId: row.guid,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\n\t\tawait this.grants.deleteByProject(ctx, id);\n\n\t\tawait this.events.emit({ type: 'project.deleted', projectId: id, ...actorOf(ctx) });\n\t}\n\n\tasync reactivateProject(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tslug: string\n\t): Promise<Project | null> {\n\t\tconst client = this.clients.serviceClient;\n\n\t\t// `.not('deleted_at', 'is', null)` guards against clobbering a live row;\n\t\t// the unique constraint on (org_id, slug) means at most one tombstone exists.\n\t\tconst { data, error } = await client\n\t\t\t.from('projects')\n\t\t\t.update({ deleted_at: null })\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('slug', slug)\n\t\t\t.not('deleted_at', 'is', null)\n\t\t\t.select(PROJECT_COLUMNS)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data) return null;\n\n\t\t// deleteProject cascades the soft-delete to project_members; undo it here too.\n\t\tif (data.owner_id) {\n\t\t\tconst { error: pmErr } = await client\n\t\t\t\t.from('project_members')\n\t\t\t\t.update({ deleted_at: null })\n\t\t\t\t.eq('project_id', data.id)\n\t\t\t\t.eq('user_id', data.owner_id)\n\t\t\t\t.not('deleted_at', 'is', null);\n\t\t\tif (pmErr) throw mapPostgrestError(pmErr);\n\t\t}\n\n\t\tconst project = rowToProject(data);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project.created',\n\t\t\tprojectId: project.id,\n\t\t\torgId: project.orgId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t\treturn project;\n\t}\n\n\t// ============================================================================\n\t// Project members\n\t// ============================================================================\n\tasync listProjectMembers(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<ProjectMember>> {\n\t\tconst range = toRange(opts);\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('project_members')\n\t\t\t.select(PROJECT_MEMBER_COLUMNS, { count: 'exact' })\n\t\t\t.eq('project_id', projectId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.order('joined_at', { ascending: (opts?.orderDir ?? 'desc') === 'asc' })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToProjectMember);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync getProjectMember(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\tuserId: string\n\t): Promise<ProjectMember | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('project_members')\n\t\t\t.select(PROJECT_MEMBER_COLUMNS)\n\t\t\t.eq('project_id', projectId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToProjectMember(data) : null;\n\t}\n\n\tasync getProjectMembersFor(\n\t\tctx: RequestContext,\n\t\tprojectIds: readonly string[],\n\t\tuserId: string\n\t): Promise<Map<string, ProjectMember | null>> {\n\t\tconst result = new Map<string, ProjectMember | null>(projectIds.map((id) => [id, null]));\n\t\tif (projectIds.length === 0) return result;\n\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('project_members')\n\t\t\t.select(PROJECT_MEMBER_COLUMNS)\n\t\t\t.in('project_id', [...projectIds])\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of data ?? []) result.set(row.project_id, rowToProjectMember(row));\n\t\treturn result;\n\t}\n\n\t// One head count per project, in parallel: tallying selected rows would be capped\n\t// by PostgREST's max-rows, and grouped aggregates are off by default.\n\tasync countProjectMembers(\n\t\tctx: RequestContext,\n\t\tprojectIds: readonly string[]\n\t): Promise<Map<string, number>> {\n\t\tconst client = this.clients.forRequest(ctx);\n\t\tconst counts = await Promise.all(\n\t\t\tprojectIds.map(async (projectId) => {\n\t\t\t\tconst { count, error } = await client\n\t\t\t\t\t.from('project_members')\n\t\t\t\t\t.select('user_id', { count: 'exact', head: true })\n\t\t\t\t\t.eq('project_id', projectId)\n\t\t\t\t\t.is('deleted_at', null);\n\t\t\t\tif (error) throw mapPostgrestError(error);\n\t\t\t\treturn [projectId, count ?? 0] as const;\n\t\t\t})\n\t\t);\n\t\treturn new Map(counts);\n\t}\n\n\tasync addProjectMember(ctx: RequestContext, member: ProjectMember): Promise<void> {\n\t\t// Upsert reactivates a prior soft-deleted row instead of throwing duplicate-key.\n\t\tconst row: Record<string, unknown> = {\n\t\t\t...projectMemberToRow(member),\n\t\t\tdeleted_at: null,\n\t\t\t...stampUpdate(ctx)\n\t\t};\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('project_members')\n\t\t\t.upsert(row, { onConflict: 'project_id,user_id' });\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.added',\n\t\t\tprojectId: member.projectId,\n\t\t\tuserId: member.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateProjectMemberRole(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\tuserId: string,\n\t\trole: ProjectRole\n\t): Promise<void> {\n\t\tconst row: Record<string, unknown> = { role, ...stampUpdate(ctx) };\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('project_members')\n\t\t\t.update(row)\n\t\t\t.eq('project_id', projectId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0)\n\t\t\tthrow new ProviderError(`Project member '${userId}' not found`, 404);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.role_changed',\n\t\t\tprojectId,\n\t\t\tuserId,\n\t\t\trole,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync removeProjectMember(ctx: RequestContext, projectId: string, userId: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('project_members')\n\t\t\t.update(stampSoftDelete(ctx))\n\t\t\t.eq('project_id', projectId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.removed',\n\t\t\tprojectId,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Row ↔ domain mappers\n// ============================================================================\n//\n// `created_by` / `updated_by` FK to `auth.users(id)` ON DELETE SET NULL, so they\n// go NULL when that user is deleted. Mappers fall back to owner_id (Project) or\n// user_id / joined_at (ProjectMember) to keep the domain type non-nullable.\n\ninterface ProjectRow {\n\tid: string;\n\torg_id: string;\n\tname: string;\n\tslug: string;\n\tdescription: string | null;\n\tvisibility: Project['visibility'];\n\towner_id: string | null;\n\tcreated_by?: string | null;\n\tupdated_by?: string | null;\n\tauto_join_on_upload?: boolean | null;\n\tcreated_at: string;\n\tupdated_at: string;\n\tdeleted_at?: string | null;\n}\n\ninterface ProjectMemberRow {\n\tproject_id: string;\n\tuser_id: string;\n\trole: ProjectRole;\n\tjoined_at: string;\n\tupdated_at?: string | null;\n\tupdated_by?: string | null;\n\tdeleted_at?: string | null;\n}\n\nfunction rowToProject(row: ProjectRow): Project {\n\tconst owner = row.owner_id ?? ERASED_ACTOR_ID;\n\treturn {\n\t\tid: row.id,\n\t\torgId: row.org_id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tdescription: row.description ?? undefined,\n\t\tvisibility: row.visibility,\n\t\townerId: owner,\n\t\tcreatedBy: row.created_by ?? owner,\n\t\tupdatedBy: row.updated_by ?? owner,\n\t\tautoJoinOnUpload: row.auto_join_on_upload ?? false,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tdeletedAt: row.deleted_at ?? null\n\t};\n}\n\nfunction projectToRow(p: Project): ProjectRow {\n\treturn {\n\t\tid: p.id,\n\t\torg_id: p.orgId,\n\t\tname: p.name,\n\t\tslug: p.slug,\n\t\tdescription: p.description ?? null,\n\t\tvisibility: p.visibility,\n\t\towner_id: p.ownerId,\n\t\tcreated_by: p.createdBy,\n\t\tupdated_by: p.updatedBy,\n\t\tauto_join_on_upload: p.autoJoinOnUpload,\n\t\tcreated_at: p.createdAt,\n\t\tupdated_at: p.updatedAt,\n\t\tdeleted_at: p.deletedAt ?? null\n\t};\n}\n\nfunction rowToProjectMember(row: ProjectMemberRow): ProjectMember {\n\treturn {\n\t\tprojectId: row.project_id,\n\t\tuserId: row.user_id,\n\t\trole: row.role,\n\t\tjoinedAt: row.joined_at,\n\t\tupdatedAt: row.updated_at ?? row.joined_at,\n\t\tupdatedBy: row.updated_by ?? row.user_id,\n\t\tdeletedAt: row.deleted_at ?? null\n\t};\n}\n\nfunction projectMemberToRow(m: ProjectMember): ProjectMemberRow {\n\treturn {\n\t\tproject_id: m.projectId,\n\t\tuser_id: m.userId,\n\t\trole: m.role,\n\t\tjoined_at: m.joinedAt\n\t};\n}\n","import type {\n\tIDefinitionStore,\n\tIEventSink,\n\tDefinitionRecord,\n\tDefinitionRecordPatch,\n\tDefinitionStatus,\n\tDefinitionFileExt,\n\tDefinitionVersion,\n\tRequestContext,\n\tDefinitionListOptions,\n\tListOptions,\n\tPage,\n\tUISchema,\n\tDocumentInventory,\n\tInventorySummary\n} from '@selvajs/platform';\nimport { ERASED_ACTOR_ID, ProviderError, actorOf, NoopEventSink } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, toRange } from './pagination.js';\nimport { stampSoftDelete, stampUpdate } from './rowStamp.js';\n\n/** Explicit column list for `definitions` — every field `rowToRecord` consumes. */\nconst DEFINITION_COLUMNS =\n\t'guid, project_id, owner_id, created_by, updated_by, compute_server_id, solve_cache_limit, display_name, description, category, tags, cover_image, status, run_count, next_version_number, live_version_id, draft_version_id, source_document_id, created_at, updated_at, deleted_at';\n/**\n * Explicit column list for `definition_versions`, minus the `schema` and `inventory` JSONB.\n * Each can be hundreds of KB per row, so the list projection leaves them out\n * and `listVersions` returns rows without them; only `getVersion`\n * (which reads one row, for a caller that needs them) pulls them in.\n */\nconst DEFINITION_VERSION_COLUMNS =\n\t'id, definition_guid, version_number, file_ext, file_key, original_filename, uploaded_by, uploaded_at, change_note, schema_extracted_at, inventory_summary';\n/**\n * `getVersion`'s projection — the list columns plus the `schema` and `inventory` JSONB. Spelled\n * out rather than built with a template literal: supabase-js infers the row\n * type from the literal column string, and a template literal degrades it to\n * `string`.\n */\n/** PostgREST's default `max-rows`: a longer read comes back cut at it. */\nconst VERSIONS_PAGE = 1000;\n\nconst DEFINITION_VERSION_COLUMNS_WITH_SCHEMA =\n\t'id, definition_guid, version_number, file_ext, file_key, original_filename, uploaded_by, uploaded_at, change_note, schema_extracted_at, inventory_summary, schema, inventory';\n\n/**\n * Definition metadata + version store backed by Postgres. `definitions` carries\n * the parent record and the `live`/`draft` channel pointers; `definition_versions`\n * carries the immutable per-upload rows.\n */\nexport class SupabaseDefinitionStore implements IDefinitionStore {\n\tprivate readonly events: IEventSink;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tevents: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.events = events;\n\t}\n\n\t// ============================================================================\n\t// Definitions\n\t// ============================================================================\n\n\tasync list(ctx: RequestContext, opts?: DefinitionListOptions): Promise<Page<DefinitionRecord>> {\n\t\treturn this.runList(ctx, undefined, opts);\n\t}\n\n\tasync listByProject(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\topts?: DefinitionListOptions\n\t): Promise<Page<DefinitionRecord>> {\n\t\treturn this.runList(ctx, { projectId }, opts);\n\t}\n\n\tasync listPublic(\n\t\tctx: RequestContext,\n\t\topts?: DefinitionListOptions & { orgId?: string }\n\t): Promise<Page<DefinitionRecord>> {\n\t\treturn this.runList(ctx, { publicOnly: true, orgId: opts?.orgId }, opts);\n\t}\n\n\tprivate async runList(\n\t\tctx: RequestContext,\n\t\tfilter: { projectId?: string; publicOnly?: boolean; orgId?: string } | undefined,\n\t\topts?: DefinitionListOptions\n\t): Promise<Page<DefinitionRecord>> {\n\t\tconst range = toRange(opts);\n\t\tconst direction = opts?.orderDir ?? 'desc';\n\n\t\t// Picked up front so there's a single `.select()` call — calling it twice\n\t\t// (once per branch) would give the builder two different inferred types.\n\t\tconst selectColumns = filter?.publicOnly\n\t\t\t? `${DEFINITION_COLUMNS}, project:projects!inner(visibility, org_id)`\n\t\t\t: DEFINITION_COLUMNS;\n\n\t\tlet query = this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('definitions')\n\t\t\t.select(selectColumns, { count: 'exact' })\n\t\t\t.is('deleted_at', null);\n\n\t\tif (filter?.publicOnly) {\n\t\t\tquery = query.eq('project.visibility', 'public');\n\t\t\tif (filter.orgId) query = query.eq('project.org_id', filter.orgId);\n\t\t}\n\n\t\tif (filter?.projectId) query = query.eq('project_id', filter.projectId);\n\n\t\t// An empty `projectIds` must match nothing. PostgREST's `in.()` is a syntax\n\t\t// error, so short-circuit rather than building the query.\n\t\tif (opts?.projectIds) {\n\t\t\tif (opts.projectIds.length === 0) return { items: [] };\n\t\t\tquery = query.in('project_id', [...opts.projectIds]);\n\t\t}\n\n\t\tif (opts?.sourceDocumentId) query = query.eq('source_document_id', opts.sourceDocumentId);\n\n\t\tif (opts?.statuses?.length) {\n\t\t\tquery = query.in('status', opts.statuses);\n\t\t} else {\n\t\t\tconst excluded: string[] = [];\n\t\t\tif (!opts?.includePending) excluded.push('pending');\n\t\t\tif (!opts?.includeArchived) excluded.push('archived');\n\t\t\tif (excluded.length) {\n\t\t\t\tquery = query.not('status', 'in', `(${excluded.join(',')})`);\n\t\t\t}\n\t\t}\n\n\t\tquery = query\n\t\t\t.order(definitionOrderColumn(opts?.orderBy), { ascending: direction === 'asc' })\n\t\t\t.range(range.from, range.to);\n\n\t\tconst { data, error, count } = await query;\n\t\tif (error) throw mapPostgrestError(error);\n\t\t// `data`'s type comes from the dynamic select string, which PostgREST\n\t\t// can't resolve to a row shape — the columns are all present regardless,\n\t\t// so cast through the known `DefinitionRow`.\n\t\tconst items = ((data ?? []) as unknown as DefinitionRow[]).map(rowToRecord);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync get(ctx: RequestContext, guid: string): Promise<DefinitionRecord | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('definitions')\n\t\t\t.select(DEFINITION_COLUMNS)\n\t\t\t.eq('guid', guid)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToRecord(data) : null;\n\t}\n\n\tasync getDefinitionsFor(\n\t\tctx: RequestContext,\n\t\tguids: readonly string[]\n\t): Promise<Map<string, DefinitionRecord>> {\n\t\tconst found = new Map<string, DefinitionRecord>();\n\t\tif (guids.length === 0) return found;\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('definitions')\n\t\t\t.select(DEFINITION_COLUMNS)\n\t\t\t.in('guid', [...new Set(guids)])\n\t\t\t.is('deleted_at', null);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of data ?? []) found.set(row.guid, rowToRecord(row));\n\t\treturn found;\n\t}\n\n\tasync create(ctx: RequestContext, record: DefinitionRecord): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definitions')\n\t\t\t.insert(recordToRow(record));\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition.created',\n\t\t\tdefinitionId: record.guid,\n\t\t\tprojectId: record.projectId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync update(ctx: RequestContext, guid: string, patch: DefinitionRecordPatch): Promise<void> {\n\t\tconst row = patchToRow(patch);\n\t\tif (Object.keys(row).length === 0) return;\n\t\tObject.assign(row, stampUpdate(ctx));\n\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('definitions')\n\t\t\t.update(row)\n\t\t\t.eq('guid', guid)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) throw new ProviderError(`Definition '${guid}' not found`, 404);\n\t}\n\n\tasync delete(ctx: RequestContext, guid: string): Promise<void> {\n\t\t// Soft-delete, matching the local provider. A retention sweep running\n\t\t// as service-role hard-deletes later, which cascades versions +\n\t\t// share_links via FK.\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('definitions')\n\t\t\t.update(stampSoftDelete(ctx))\n\t\t\t.eq('guid', guid)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (error) throw mapPostgrestError(error);\n\t\t// No row: already deleted. Not a deletion to record.\n\t\tif (!data || data.length === 0) return;\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition.deleted',\n\t\t\tdefinitionId: guid,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync deleteByProject(ctx: RequestContext, projectId: string): Promise<void> {\n\t\t// Cascade from `deleteProject`. `select('guid')` returns the affected rows\n\t\t// so we can emit a `definition.deleted` per record, matching the local\n\t\t// provider and the single-`delete` path above.\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('definitions')\n\t\t\t.update(stampSoftDelete(ctx))\n\t\t\t.eq('project_id', projectId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of data ?? []) {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'definition.deleted',\n\t\t\t\tdefinitionId: row.guid,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\t}\n\n\tasync incrementSolveCount(ctx: RequestContext, guid: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient.rpc('increment_run_count', { g: guid });\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync reserveNextVersionNumber(ctx: RequestContext, guid: string): Promise<number> {\n\t\t// Atomic reserve-and-increment in one SQL function — no read-modify-write\n\t\t// race. Raises no_data_found (mapped to 404) when the definition is\n\t\t// missing or soft-deleted.\n\t\tconst { data, error } = await this.clients.serviceClient.rpc('reserve_next_version_number', {\n\t\t\tg: guid\n\t\t});\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (typeof data !== 'number') {\n\t\t\tthrow new ProviderError(`Definition '${guid}' not found`, 404);\n\t\t}\n\t\treturn data;\n\t}\n\n\t// ============================================================================\n\t// Versions\n\t// ============================================================================\n\n\tasync createVersion(ctx: RequestContext, version: DefinitionVersion): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definition_versions')\n\t\t\t.insert(versionToRow(version));\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition_version.created',\n\t\t\tversionId: version.id,\n\t\t\tdefinitionId: version.definitionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync listVersions(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<DefinitionVersion>> {\n\t\tconst range = toRange(opts);\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('definition_versions')\n\t\t\t.select(DEFINITION_VERSION_COLUMNS, { count: 'exact' })\n\t\t\t.eq('definition_guid', definitionId)\n\t\t\t.order('version_number', { ascending: false })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToVersion);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync listVersionsFor(\n\t\tctx: RequestContext,\n\t\tdefinitionIds: readonly string[]\n\t): Promise<Map<string, DefinitionVersion[]>> {\n\t\tconst byDefinition = new Map<string, DefinitionVersion[]>(definitionIds.map((id) => [id, []]));\n\t\tif (definitionIds.length === 0) return byDefinition;\n\t\t// Paged by PostgREST's row cap; the order keeps each definition's versions newest first.\n\t\tfor (let from = 0; ; from += VERSIONS_PAGE) {\n\t\t\tconst { data, error } = await this.clients\n\t\t\t\t.forRequest(ctx)\n\t\t\t\t.from('definition_versions')\n\t\t\t\t.select(DEFINITION_VERSION_COLUMNS)\n\t\t\t\t.in('definition_guid', [...new Set(definitionIds)])\n\t\t\t\t.order('definition_guid')\n\t\t\t\t.order('version_number', { ascending: false })\n\t\t\t\t.range(from, from + VERSIONS_PAGE - 1);\n\t\t\tif (error) throw mapPostgrestError(error);\n\t\t\tconst rows = data ?? [];\n\t\t\tfor (const row of rows) byDefinition.get(row.definition_guid)?.push(rowToVersion(row));\n\t\t\tif (rows.length < VERSIONS_PAGE) return byDefinition;\n\t\t}\n\t}\n\n\tasync getVersion(ctx: RequestContext, versionId: string): Promise<DefinitionVersion | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('definition_versions')\n\t\t\t.select(DEFINITION_VERSION_COLUMNS_WITH_SCHEMA)\n\t\t\t.eq('id', versionId)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToVersion(data) : null;\n\t}\n\n\tasync setVersionSchema(ctx: RequestContext, versionId: string, schema: UISchema): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definition_versions')\n\t\t\t.update({ schema, schema_extracted_at: new Date().toISOString() })\n\t\t\t.eq('id', versionId);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync setVersionInventory(\n\t\t_ctx: RequestContext,\n\t\tversionId: string,\n\t\tinventory: DocumentInventory,\n\t\tsummary: InventorySummary\n\t): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definition_versions')\n\t\t\t.update({ inventory, inventory_summary: summary })\n\t\t\t.eq('id', versionId);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync deleteVersion(ctx: RequestContext, versionId: string): Promise<void> {\n\t\t// live_version_id / draft_version_id are ON DELETE RESTRICT — if the\n\t\t// version is referenced by either channel, Postgres raises 23503 →\n\t\t// mapPostgrestError → ProviderError(409).\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definition_versions')\n\t\t\t.delete()\n\t\t\t.eq('id', versionId);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition_version.deleted',\n\t\t\tversionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync setLiveVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tawait this.repointChannel(ctx, definitionId, versionId, 'live_version_id');\n\t\t// Only `live` advancement fires `definition.published`. Draft repointing\n\t\t// is the editor's working pointer, not a publication signal.\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition.published',\n\t\t\tdefinitionId,\n\t\t\tversionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync setDraftVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tawait this.repointChannel(ctx, definitionId, versionId, 'draft_version_id');\n\t}\n\n\tasync attachInitialVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\t// Duplicates repointChannel's ownership check rather than calling it,\n\t\t// so the bootstrap path enforces the same invariant independently of\n\t\t// the two-channel repoint logic.\n\t\tconst { data: version, error: vError } = await client\n\t\t\t.from('definition_versions')\n\t\t\t.select('id, definition_guid')\n\t\t\t.eq('id', versionId)\n\t\t\t.maybeSingle();\n\t\tif (vError) throw mapPostgrestError(vError);\n\t\tif (!version || version.definition_guid !== definitionId) {\n\t\t\tthrow new ProviderError(`Version '${versionId}' not found for this definition`, 404);\n\t\t}\n\n\t\t// Single UPDATE — both channel pointers and status flip in one row\n\t\t// write, so a mid-flight failure can't leave a half-promoted record.\n\t\tconst row: Record<string, unknown> = {\n\t\t\tlive_version_id: versionId,\n\t\t\tdraft_version_id: versionId,\n\t\t\tstatus: 'draft',\n\t\t\t...stampUpdate(ctx)\n\t\t};\n\n\t\tconst { data, error } = await client\n\t\t\t.from('definitions')\n\t\t\t.update(row)\n\t\t\t.eq('guid', definitionId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) {\n\t\t\tthrow new ProviderError(`Definition '${definitionId}' not found`, 404);\n\t\t}\n\t\t// No `definition.published` event: this is a bootstrap, not a publish.\n\t}\n\n\tprivate async repointChannel(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string,\n\t\tcolumn: 'live_version_id' | 'draft_version_id'\n\t): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst { data: version, error: vError } = await client\n\t\t\t.from('definition_versions')\n\t\t\t.select('id, definition_guid')\n\t\t\t.eq('id', versionId)\n\t\t\t.maybeSingle();\n\t\tif (vError) throw mapPostgrestError(vError);\n\t\tif (!version || version.definition_guid !== definitionId) {\n\t\t\tthrow new ProviderError(`Version '${versionId}' not found for this definition`, 404);\n\t\t}\n\n\t\tconst row: Record<string, unknown> = { [column]: versionId, ...stampUpdate(ctx) };\n\t\tconst { data, error } = await client\n\t\t\t.from('definitions')\n\t\t\t.update(row)\n\t\t\t.eq('guid', definitionId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) {\n\t\t\tthrow new ProviderError(`Definition '${definitionId}' not found`, 404);\n\t\t}\n\t}\n}\n\n// ============================================================================\n// Row ↔ domain mappers\n// ============================================================================\ninterface DefinitionRow {\n\tguid: string;\n\tproject_id: string;\n\towner_id: string | null;\n\tcreated_by?: string | null;\n\tupdated_by?: string | null;\n\tcompute_server_id: string | null;\n\tsolve_cache_limit: number | string | null;\n\tdisplay_name: string;\n\tdescription: string | null;\n\tcategory: string | null;\n\ttags: string[] | null;\n\tcover_image: string | null;\n\tstatus: DefinitionStatus;\n\trun_count: number | string;\n\tnext_version_number: number | string;\n\tlive_version_id: string | null;\n\tdraft_version_id: string | null;\n\tsource_document_id?: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n\tdeleted_at?: string | null;\n}\n\ninterface DefinitionVersionRow {\n\tid: string;\n\tdefinition_guid: string;\n\tversion_number: number;\n\tfile_ext: DefinitionFileExt;\n\tfile_key: string;\n\toriginal_filename: string | null;\n\tuploaded_by: string | null;\n\tuploaded_at: string;\n\tchange_note?: string | null;\n\tschema?: UISchema | null;\n\tschema_extracted_at?: string | null;\n\tinventory?: DocumentInventory | null;\n\tinventory_summary?: InventorySummary | null;\n}\n\nfunction rowToRecord(row: DefinitionRow): DefinitionRecord {\n\tconst owner = row.owner_id ?? ERASED_ACTOR_ID;\n\treturn {\n\t\tguid: row.guid,\n\t\tprojectId: row.project_id,\n\t\townerId: owner,\n\t\tcreatedBy: row.created_by ?? owner,\n\t\tupdatedBy: row.updated_by ?? owner,\n\t\tliveVersionId: row.live_version_id,\n\t\tdraftVersionId: row.draft_version_id,\n\t\tcomputeServerId: row.compute_server_id ?? undefined,\n\t\tsolveCacheLimit:\n\t\t\trow.solve_cache_limit == null\n\t\t\t\t? undefined\n\t\t\t\t: typeof row.solve_cache_limit === 'string'\n\t\t\t\t\t? Number(row.solve_cache_limit)\n\t\t\t\t\t: row.solve_cache_limit,\n\t\tdisplayName: row.display_name,\n\t\tdescription: row.description ?? undefined,\n\t\tcategory: row.category ?? undefined,\n\t\ttags: row.tags ?? undefined,\n\t\tcoverImage: row.cover_image ?? undefined,\n\t\tstatus: row.status,\n\t\tsolveCount: typeof row.run_count === 'string' ? Number(row.run_count) : row.run_count,\n\t\tnextVersionNumber:\n\t\t\ttypeof row.next_version_number === 'string'\n\t\t\t\t? Number(row.next_version_number)\n\t\t\t\t: row.next_version_number,\n\t\tsourceDocumentId: row.source_document_id ?? undefined,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tdeletedAt: row.deleted_at ?? null\n\t};\n}\n\nfunction recordToRow(r: DefinitionRecord): Record<string, unknown> {\n\tconst row: Record<string, unknown> = {\n\t\tguid: r.guid,\n\t\tproject_id: r.projectId,\n\t\towner_id: r.ownerId,\n\t\tcreated_by: r.createdBy,\n\t\tupdated_by: r.updatedBy,\n\t\tlive_version_id: r.liveVersionId,\n\t\tdraft_version_id: r.draftVersionId,\n\t\tcompute_server_id: r.computeServerId ?? null,\n\t\tsolve_cache_limit: r.solveCacheLimit ?? null,\n\t\tdisplay_name: r.displayName,\n\t\tdescription: r.description ?? null,\n\t\tcategory: r.category ?? null,\n\t\tcover_image: r.coverImage ?? null,\n\t\tstatus: r.status,\n\t\trun_count: r.solveCount,\n\t\tnext_version_number: r.nextVersionNumber,\n\t\tsource_document_id: r.sourceDocumentId ?? null,\n\t\tcreated_at: r.createdAt,\n\t\tupdated_at: r.updatedAt,\n\t\tdeleted_at: r.deletedAt ?? null\n\t};\n\tif (r.tags !== undefined) row.tags = r.tags;\n\treturn row;\n}\n\nfunction patchToRow(patch: DefinitionRecordPatch): Record<string, unknown> {\n\tconst row: Record<string, unknown> = {};\n\tif (patch.displayName !== undefined) row.display_name = patch.displayName;\n\tif (patch.description !== undefined) row.description = patch.description;\n\tif (patch.category !== undefined) row.category = patch.category;\n\tif (patch.tags !== undefined) row.tags = patch.tags ?? [];\n\tif (patch.coverImage !== undefined) row.cover_image = patch.coverImage;\n\tif (patch.projectId !== undefined) row.project_id = patch.projectId;\n\tif (patch.computeServerId !== undefined) row.compute_server_id = patch.computeServerId;\n\tif (patch.solveCacheLimit !== undefined) row.solve_cache_limit = patch.solveCacheLimit;\n\tif (patch.status !== undefined) row.status = patch.status;\n\tif (patch.ownerId !== undefined) row.owner_id = patch.ownerId;\n\tif (patch.sourceDocumentId !== undefined) row.source_document_id = patch.sourceDocumentId;\n\treturn row;\n}\n\nfunction rowToVersion(row: DefinitionVersionRow): DefinitionVersion {\n\treturn {\n\t\tid: row.id,\n\t\tdefinitionId: row.definition_guid,\n\t\tversionNumber: row.version_number,\n\t\tfileExt: row.file_ext,\n\t\tfileKey: row.file_key,\n\t\toriginalFilename: row.original_filename ?? undefined,\n\t\tuploadedBy: row.uploaded_by ?? ERASED_ACTOR_ID,\n\t\tuploadedAt: row.uploaded_at,\n\t\tchangeNote: row.change_note ?? undefined,\n\t\tschema: row.schema ?? undefined,\n\t\tschemaExtractedAt: row.schema_extracted_at ?? undefined,\n\t\tinventory: row.inventory ?? undefined,\n\t\tinventorySummary: row.inventory_summary ?? undefined\n\t};\n}\n\nfunction versionToRow(v: DefinitionVersion): Record<string, unknown> {\n\tconst row: Record<string, unknown> = {\n\t\tid: v.id,\n\t\tdefinition_guid: v.definitionId,\n\t\tversion_number: v.versionNumber,\n\t\tfile_ext: v.fileExt,\n\t\tfile_key: v.fileKey,\n\t\toriginal_filename: v.originalFilename ?? null,\n\t\tuploaded_by: v.uploadedBy,\n\t\tuploaded_at: v.uploadedAt\n\t};\n\tif (v.changeNote !== undefined) row.change_note = v.changeNote;\n\tif (v.schema !== undefined) row.schema = v.schema;\n\tif (v.schemaExtractedAt !== undefined) row.schema_extracted_at = v.schemaExtractedAt;\n\tif (v.inventory !== undefined) row.inventory = v.inventory;\n\tif (v.inventorySummary !== undefined) row.inventory_summary = v.inventorySummary;\n\treturn row;\n}\n\nfunction definitionOrderColumn(orderBy: DefinitionListOptions['orderBy'] | undefined): string {\n\tswitch (orderBy) {\n\t\tcase 'name':\n\t\t\treturn 'display_name';\n\t\tcase 'solveCount':\n\t\t\treturn 'run_count';\n\t\tcase 'updatedAt':\n\t\t\treturn 'updated_at';\n\t\tcase 'createdAt':\n\t\tdefault:\n\t\t\treturn 'created_at';\n\t}\n}\n","import type {\n\tIInviteStore,\n\tIEventSink,\n\tInvite,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { NoopEventSink, actorOf } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, toRange } from './pagination.js';\n\n/** Explicit column list for `invites` — every field `rowToInvite` consumes. */\nconst INVITE_COLUMNS =\n\t'id, token_hash, email, org_id, org_role, org_permissions, platform_permissions, invited_by, created_at, expires_at, accepted_at, accepted_by_user_id';\n\n/**\n * Invite store. `getByTokenHash` routes through a SECURITY DEFINER RPC so an\n * unauthenticated caller (still validating an invite link) can resolve it\n * without RLS blocking them. The raw token is hashed at the route layer\n * (`invites/token.server.ts` in the selva app); this store only ever sees the\n * HMAC digest. Reads run as the caller, where RLS asks for `manage_org_members`;\n * writes run as the service role.\n */\nexport class SupabaseInviteStore implements IInviteStore {\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tprivate readonly events: IEventSink = new NoopEventSink()\n\t) {}\n\n\tasync create(ctx: RequestContext, invite: Invite): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient.from('invites').insert(inviteToRow(invite));\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.created',\n\t\t\tinviteId: invite.id,\n\t\t\torgId: invite.orgId,\n\t\t\temail: invite.email,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync getByTokenHash(ctx: RequestContext, tokenHash: string): Promise<Invite | null> {\n\t\t// SECURITY DEFINER RPC: the token itself is the capability, so an\n\t\t// unauthenticated caller on /accept-invite can still resolve it.\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.rpc('get_invite_by_token_hash', { h: tokenHash });\n\t\tif (error) throw mapPostgrestError(error);\n\t\t// PostgREST may wrap a scalar-returning RPC result in an array depending\n\t\t// on the function signature — normalize both shapes.\n\t\tconst row = Array.isArray(data) ? data[0] : data;\n\t\treturn row ? rowToInvite(row as InviteRow) : null;\n\t}\n\n\tasync listByOrg(ctx: RequestContext, orgId: string, opts?: ListOptions): Promise<Page<Invite>> {\n\t\tconst range = toRange(opts);\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('invites')\n\t\t\t.select(INVITE_COLUMNS, { count: 'exact' })\n\t\t\t.eq('org_id', orgId)\n\t\t\t.order('created_at', { ascending: (opts?.orderDir ?? 'desc') === 'asc' })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToInvite);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync markAccepted(ctx: RequestContext, id: string, userId: string): Promise<boolean> {\n\t\t// `.is('accepted_at', null)` makes this the claim: a second call matches nothing.\n\t\tconst now = new Date().toISOString();\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('invites')\n\t\t\t.update({ accepted_at: now, accepted_by_user_id: userId })\n\t\t\t.eq('id', id)\n\t\t\t.is('accepted_at', null)\n\t\t\t.gt('expires_at', now)\n\t\t\t.select('org_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst row = data?.[0];\n\t\tif (!row) return false;\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.accepted',\n\t\t\tinviteId: id,\n\t\t\torgId: (row as { org_id: string }).org_id,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t\treturn true;\n\t}\n\n\tasync reopen(ctx: RequestContext, id: string, userId: string): Promise<boolean> {\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('invites')\n\t\t\t.update({ accepted_at: null, accepted_by_user_id: null })\n\t\t\t.eq('id', id)\n\t\t\t.eq('accepted_by_user_id', userId)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn (data?.length ?? 0) > 0;\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('invites')\n\t\t\t.delete()\n\t\t\t.eq('id', id)\n\t\t\t.is('accepted_at', null)\n\t\t\t.select('org_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst row = data?.[0];\n\t\tif (!row) return;\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.revoked',\n\t\t\tinviteId: id,\n\t\t\torgId: (row as { org_id: string }).org_id,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync revokePendingByEmail(ctx: RequestContext, orgId: string, email: string): Promise<string[]> {\n\t\t// Emails are stored lowercase at mint time; normalize the needle too so an\n\t\t// offboarding call with the address as the admin typed it still matches.\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('invites')\n\t\t\t.delete()\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('email', email.trim().toLowerCase())\n\t\t\t.is('accepted_at', null)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst ids = (data ?? []).map((r) => (r as { id: string }).id);\n\t\tfor (const id of ids) {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'invite.revoked',\n\t\t\t\tinviteId: id,\n\t\t\t\torgId,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\t\treturn ids;\n\t}\n\n\tasync deleteByOrg(ctx: RequestContext, orgId: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient.from('invites').delete().eq('org_id', orgId);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n}\n\ninterface InviteRow {\n\tid: string;\n\ttoken_hash: string;\n\temail: string;\n\torg_id: string;\n\torg_role: Invite['orgRole'];\n\torg_permissions: string[];\n\tplatform_permissions: string[];\n\tinvited_by: string;\n\tcreated_at: string;\n\texpires_at: string;\n\taccepted_at: string | null;\n\taccepted_by_user_id: string | null;\n}\n\nfunction rowToInvite(row: InviteRow): Invite {\n\treturn {\n\t\tid: row.id,\n\t\ttokenHash: row.token_hash,\n\t\temail: row.email,\n\t\torgId: row.org_id,\n\t\torgRole: row.org_role,\n\t\torgPermissions: row.org_permissions as Invite['orgPermissions'],\n\t\t// `?? []` covers a row read through a client whose projection predates the\n\t\t// column, not a null default — the column is `not null default '{}'`.\n\t\tplatformPermissions: (row.platform_permissions ?? []) as NonNullable<\n\t\t\tInvite['platformPermissions']\n\t\t>,\n\t\tinvitedBy: row.invited_by,\n\t\tcreatedAt: row.created_at,\n\t\texpiresAt: row.expires_at,\n\t\tacceptedAt: row.accepted_at ?? undefined,\n\t\tacceptedByUserId: row.accepted_by_user_id ?? undefined\n\t};\n}\n\nfunction inviteToRow(i: Invite): InviteRow {\n\treturn {\n\t\tid: i.id,\n\t\ttoken_hash: i.tokenHash,\n\t\temail: i.email,\n\t\torg_id: i.orgId,\n\t\torg_role: i.orgRole,\n\t\torg_permissions: i.orgPermissions,\n\t\tplatform_permissions: i.platformPermissions ?? [],\n\t\tinvited_by: i.invitedBy,\n\t\tcreated_at: i.createdAt,\n\t\texpires_at: i.expiresAt,\n\t\taccepted_at: i.acceptedAt ?? null,\n\t\taccepted_by_user_id: i.acceptedByUserId ?? null\n\t};\n}\n","import {\n\tisOrgServer,\n\tisPlatformServer,\n\tscopeConfigToOrg,\n\ttype IComputeServerStore,\n\ttype ComputeConfig,\n\ttype ComputeServerConfig,\n\ttype GetConfigOptions,\n\ttype RequestContext,\n\ttype SecretVerificationFailure,\n\ttype SecretVerificationReport,\n\ttype ILogger\n} from '@selvajs/platform';\nimport { NoopLogger } from '@selvajs/platform';\n// `node:crypto`-based, so it's a server-only subpath, not the root barrel.\nimport {\n\tdecryptWithKeys,\n\tencryptSecret,\n\tisEncryptedSecret,\n\tisLegacyEnvelope,\n\tisUnknownEnvelope,\n\ttype SecretBinding\n} from '@selvajs/platform/computeServer';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\n\n// Sessions have no SELECT on `api_key`, so this list is all a session can read.\n// Keys come from `readApiKeys`, after RLS has said which servers the caller sees.\nconst SERVER_COLUMNS = 'id, scope, owner_org_id, shared_with_all, label, server_url, has_api_key';\nconst SHARE_COLUMNS = 'server_id, org_id';\nconst ORG_DEFAULT_COLUMNS = 'org_id, default_server_id';\n\n/** The columns a key read needs: `server_url` is half the key's binding. */\ntype KeyRow = Pick<ServerRow, 'id' | 'label' | 'server_url' | 'api_key'>;\n\nconst bindingOf = (row: KeyRow): SecretBinding => ({ id: row.id, url: row.server_url });\n\n/**\n * Compute-server config backed by three tables:\n * - `compute_servers`: one row per server. `scope = 'platform' | 'org'`.\n * Platform rows carry a `shared_with_all` flag + `compute_server_shares`\n * allowlist; org rows carry `owner_org_id`.\n * - `compute_server_shares`: many-to-many for platform servers shared\n * with specific orgs (when `shared_with_all = false`).\n * - `compute_server_org_defaults`: per-org `orgDefaults[orgId]` choice.\n * - `compute_server_platform_default`: single-row sentinel for the global\n * `defaultServerId`.\n *\n * `getConfig` returns the full doc; the visibility predicate is applied by\n * callers (resolver, page loaders) using helpers in `@selvajs/platform`.\n */\nexport class SupabaseComputeServerStore implements IComputeServerStore {\n\t/**\n\t * `secretKey` (from `SELVA_AT_REST_KEY`) encrypts/decrypts `compute_servers.api_key`\n\t * so the Rhino.Compute credential never sits in the DB as plaintext. Optional\n\t * only for construction paths that never touch apiKeys — a store built\n\t * without a key throws if asked to write or read a secret.\n\t */\n\tprivate readonly logger: ILogger;\n\t/** Current key first; the previous one still opens rows sealed before a rotation. */\n\tprivate readonly keys: Buffer[];\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tprivate readonly secretKey?: Buffer,\n\t\tlogger?: ILogger,\n\t\tpreviousKey?: Buffer\n\t) {\n\t\tthis.logger = logger ?? new NoopLogger();\n\t\tthis.keys = secretKey ? (previousKey ? [secretKey, previousKey] : [secretKey]) : [];\n\t}\n\n\tasync getConfig(ctx: RequestContext, opts: GetConfigOptions = {}): Promise<ComputeConfig> {\n\t\tconst client = this.clients.forRequest(ctx);\n\t\tconst withKeys = opts.includeApiKeys === true;\n\n\t\tconst [serversRes, sharesRes, orgDefRes, platDefRes] = await Promise.all([\n\t\t\tclient.from('compute_servers').select(SERVER_COLUMNS),\n\t\t\tclient.from('compute_server_shares').select(SHARE_COLUMNS),\n\t\t\tclient.from('compute_server_org_defaults').select(ORG_DEFAULT_COLUMNS),\n\t\t\tclient\n\t\t\t\t.from('compute_server_platform_default')\n\t\t\t\t.select('default_server_id')\n\t\t\t\t.eq('singleton', true)\n\t\t\t\t.maybeSingle()\n\t\t]);\n\n\t\tif (serversRes.error) throw mapPostgrestError(serversRes.error);\n\t\tif (sharesRes.error) throw mapPostgrestError(sharesRes.error);\n\t\tif (orgDefRes.error) throw mapPostgrestError(orgDefRes.error);\n\t\tif (platDefRes.error) throw mapPostgrestError(platDefRes.error);\n\n\t\tconst sharedByServer = new Map<string, string[]>();\n\t\tfor (const row of sharesRes.data ?? []) {\n\t\t\tconst list = sharedByServer.get(row.server_id) ?? [];\n\t\t\tlist.push(row.org_id);\n\t\t\tsharedByServer.set(row.server_id, list);\n\t\t}\n\n\t\tconst rows: ServerRow[] = serversRes.data ?? [];\n\t\tconst keyed = withKeys ? await this.withApiKeys(rows) : rows;\n\t\tconst servers = keyed.map((row) => rowToServer(row, sharedByServer, withKeys));\n\n\t\tconst orgDefaults: Record<string, string> = {};\n\t\tfor (const row of orgDefRes.data ?? []) {\n\t\t\tif (row.default_server_id) orgDefaults[row.org_id] = row.default_server_id;\n\t\t}\n\n\t\tconst config: ComputeConfig = {\n\t\t\tservers,\n\t\t\tdefaultServerId: platDefRes.data?.default_server_id ?? undefined,\n\t\t\torgDefaults\n\t\t};\n\t\treturn opts.scopeToOrgId ? scopeConfigToOrg(config, opts.scopeToOrgId) : config;\n\t}\n\n\t/**\n\t * The solve path's entry point: one row lookup + one decrypt instead of\n\t * `getConfig`'s whole-table read. An unknown id or unreadable ciphertext\n\t * yields `undefined` rather than throwing.\n\t */\n\tasync getServerApiKey(ctx: RequestContext, serverId: string): Promise<string | undefined> {\n\t\tconst { data: visible, error: visibleError } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('compute_servers')\n\t\t\t.select('id')\n\t\t\t.eq('id', serverId)\n\t\t\t.maybeSingle();\n\t\tif (visibleError) throw mapPostgrestError(visibleError);\n\t\tif (!visible) return undefined;\n\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('compute_servers')\n\t\t\t.select('id, label, server_url, api_key')\n\t\t\t.eq('id', serverId)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data) return undefined;\n\t\treturn this.decryptRowApiKey(data as KeyRow).api_key ?? undefined;\n\t}\n\n\t/** `rows` must come from a session read: this reaches keys with the service role. */\n\tprivate async withApiKeys(rows: ServerRow[]): Promise<ServerRow[]> {\n\t\tif (rows.length === 0) return rows;\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('compute_servers')\n\t\t\t.select('id, label, api_key')\n\t\t\t.in(\n\t\t\t\t'id',\n\t\t\t\trows.map((r) => r.id)\n\t\t\t);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst keys = new Map((data ?? []).map((r) => [r.id as string, r.api_key as string | null]));\n\t\treturn rows.map((row) => this.decryptRowApiKey({ ...row, api_key: keys.get(row.id) ?? null }));\n\t}\n\n\tasync savePlatformServers(\n\t\tctx: RequestContext,\n\t\tservers: ComputeServerConfig[],\n\t\tdefaultServerId: string | undefined\n\t): Promise<void> {\n\t\tconst platformOnly = servers.filter(isPlatformServer);\n\t\tconst shares = platformOnly.flatMap((s) =>\n\t\t\ts.sharedWith === 'all'\n\t\t\t\t? []\n\t\t\t\t: s.sharedWith.map((orgId) => ({ server_id: s.id, org_id: orgId }))\n\t\t);\n\t\tconst { error } = await this.clients.serviceClient.rpc('save_platform_compute_servers', {\n\t\t\tservers: platformOnly.map((s) => serverToRow(this.encryptServerApiKey(s))),\n\t\t\tshares,\n\t\t\tdefault_server: defaultServerId ?? null\n\t\t});\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync saveOrgServers(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tservers: ComputeServerConfig[],\n\t\tdefaultServerId?: string | null\n\t): Promise<void> {\n\t\tconst orgOnly = servers.filter(isOrgServer).map((s) => ({ ...s, ownerOrgId: orgId }));\n\t\tconst { error } = await this.clients.serviceClient.rpc('save_org_compute_servers', {\n\t\t\to: orgId,\n\t\t\tservers: orgOnly.map((s) => serverToRow(this.encryptServerApiKey(s))),\n\t\t\tset_default: defaultServerId !== undefined,\n\t\t\tdefault_server: defaultServerId ?? null\n\t\t});\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync setOrgDefault(ctx: RequestContext, orgId: string, serverId: string | null): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tif (serverId === null) {\n\t\t\tconst { error } = await client\n\t\t\t\t.from('compute_server_org_defaults')\n\t\t\t\t.delete()\n\t\t\t\t.eq('org_id', orgId);\n\t\t\tif (error) throw mapPostgrestError(error);\n\t\t\treturn;\n\t\t}\n\t\tconst { error } = await client\n\t\t\t.from('compute_server_org_defaults')\n\t\t\t.upsert({ org_id: orgId, default_server_id: serverId });\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync deleteByOrg(ctx: RequestContext, orgId: string): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\n\t\t// Org soft-delete doesn't trigger the FK cascade from orgs(id), so\n\t\t// each dependent table needs an explicit delete here.\n\t\tconst { error: defErr } = await client\n\t\t\t.from('compute_server_org_defaults')\n\t\t\t.delete()\n\t\t\t.eq('org_id', orgId);\n\t\tif (defErr) throw mapPostgrestError(defErr);\n\n\t\tconst { error: srvErr } = await client\n\t\t\t.from('compute_servers')\n\t\t\t.delete()\n\t\t\t.eq('scope', 'org')\n\t\t\t.eq('owner_org_id', orgId);\n\t\tif (srvErr) throw mapPostgrestError(srvErr);\n\n\t\tconst { error: shErr } = await client\n\t\t\t.from('compute_server_shares')\n\t\t\t.delete()\n\t\t\t.eq('org_id', orgId);\n\t\tif (shErr) throw mapPostgrestError(shErr);\n\t}\n\n\t// ==========================================================================\n\t// At-rest secret handling\n\t// ==========================================================================\n\n\t/**\n\t * Encrypt a server's `apiKey` before it is written to the DB, bound to its id\n\t * and URL. Throws on a value that is already an envelope, and if the store was\n\t * built without a key, so we never silently persist plaintext.\n\t */\n\tprivate encryptServerApiKey(s: ComputeServerConfig): ComputeServerConfig {\n\t\tif (!s.apiKey) return s;\n\t\tif (!this.secretKey) {\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot store a compute-server apiKey: SELVA_AT_REST_KEY is not configured. ' +\n\t\t\t\t\t'Set it so secrets are encrypted at rest.'\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\t...s,\n\t\t\tapiKey: encryptSecret(s.apiKey, this.secretKey, { id: s.id, url: s.serverUrl })\n\t\t};\n\t}\n\n\t/**\n\t * Decrypt a row's `api_key` on read. Tolerant, mirroring the local provider:\n\t * a row whose ciphertext can't be authenticated under the current key is\n\t * returned with `api_key: null` and a warning logged, so the page keeps\n\t * rendering (solves against that server fail later at Rhino.Compute). A\n\t * plaintext value that predates encryption is passed through unchanged and\n\t * surfaced by `verifySecrets()` — never silently dropped.\n\t */\n\tprivate decryptRowApiKey<R extends KeyRow>(row: R): R {\n\t\tif (!row.api_key) return row;\n\t\tif (isUnknownEnvelope(row.api_key)) {\n\t\t\tthis.logger.warn(\n\t\t\t\t`Could not read api_key: it is sealed as ${row.api_key.slice(0, 6)}, a format this Selva version does not know. ` +\n\t\t\t\t\t'A newer version wrote it. This server is returned without an apiKey and solves against it will fail. ' +\n\t\t\t\t\t'Upgrade Selva again, or re-enter the key via /admin/compute',\n\t\t\t\t{ component: 'selva', serverLabel: row.label, serverId: row.id }\n\t\t\t);\n\t\t\treturn { ...row, api_key: null };\n\t\t}\n\t\tif (!isEncryptedSecret(row.api_key)) {\n\t\t\tthis.logger.warn(\n\t\t\t\t'Compute server row has a plaintext api_key; re-save it via /admin/compute so it is stored encrypted',\n\t\t\t\t{ component: 'selva', serverLabel: row.label, serverId: row.id }\n\t\t\t);\n\t\t\treturn row;\n\t\t}\n\t\tif (!this.secretKey) {\n\t\t\tthis.logger.warn(\n\t\t\t\t'Cannot decrypt api_key: SELVA_AT_REST_KEY is not configured. Returning without a key; solves will fail',\n\t\t\t\t{ component: 'selva', serverLabel: row.label, serverId: row.id }\n\t\t\t);\n\t\t\treturn { ...row, api_key: null };\n\t\t}\n\t\ttry {\n\t\t\treturn { ...row, api_key: decryptWithKeys(row.api_key, this.keys, bindingOf(row)).plaintext };\n\t\t} catch (cause) {\n\t\t\tthis.logger.warn(\n\t\t\t\t'Could not decrypt api_key: the stored ciphertext does not match the current SELVA_AT_REST_KEY. ' +\n\t\t\t\t\t'This server is returned without an apiKey and solves against it will fail. ' +\n\t\t\t\t\t'Re-enter the key via /admin/compute, or restore the original SELVA_AT_REST_KEY',\n\t\t\t\t{\n\t\t\t\t\tcomponent: 'selva',\n\t\t\t\t\tserverLabel: row.label,\n\t\t\t\t\tserverId: row.id,\n\t\t\t\t\terr: cause instanceof Error ? (cause.stack ?? cause.message) : String(cause)\n\t\t\t\t}\n\t\t\t);\n\t\t\treturn { ...row, api_key: null };\n\t\t}\n\t}\n\n\t/**\n\t * Boot-time integrity check over every `compute_servers` row. Uses the\n\t * service client (no request context at boot) to read raw ciphertext, then\n\t * attempts to decrypt each `api_key`. Does NOT throw — returns a structured\n\t * report for boot health to drive `/api/health`.\n\t */\n\tasync verifySecrets(): Promise<SecretVerificationReport> {\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('compute_servers')\n\t\t\t.select('id, label, server_url, api_key');\n\t\tif (error) throw mapPostgrestError(error);\n\n\t\tconst failures: SecretVerificationFailure[] = [];\n\t\tlet plaintextFound = false;\n\t\tlet onPreviousKey = 0;\n\t\tlet legacyEnvelopes = 0;\n\n\t\tfor (const row of (data ?? []) as KeyRow[]) {\n\t\t\tconst { api_key: apiKey, id, label } = row;\n\t\t\tif (!apiKey) continue;\n\t\t\tif (isUnknownEnvelope(apiKey)) {\n\t\t\t\tfailures.push({ serverId: id, serverLabel: label, reason: 'unknown_envelope' });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isEncryptedSecret(apiKey)) {\n\t\t\t\tplaintextFound = true;\n\t\t\t\tfailures.push({ serverId: id, serverLabel: label, reason: 'plaintext_on_disk' });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!this.secretKey) {\n\t\t\t\tfailures.push({\n\t\t\t\t\tserverId: id,\n\t\t\t\t\tserverLabel: label,\n\t\t\t\t\treason: 'key_mismatch',\n\t\t\t\t\tcause: 'SELVA_AT_REST_KEY is not configured'\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isLegacyEnvelope(apiKey)) legacyEnvelopes += 1;\n\t\t\ttry {\n\t\t\t\tif (decryptWithKeys(apiKey, this.keys, bindingOf(row)).keyIndex > 0) onPreviousKey += 1;\n\t\t\t} catch (cause) {\n\t\t\t\tfailures.push({\n\t\t\t\t\tserverId: id,\n\t\t\t\t\tserverLabel: label,\n\t\t\t\t\treason: 'key_mismatch',\n\t\t\t\t\tcause: cause instanceof Error ? cause.message : String(cause)\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tok: failures.length === 0,\n\t\t\tfailures,\n\t\t\tplaintextFound,\n\t\t\t...(this.keys.length > 1 ? { onPreviousKey } : {}),\n\t\t\t...(legacyEnvelopes > 0 ? { legacyEnvelopes } : {})\n\t\t};\n\t}\n\n\t/**\n\t * Re-seal, under the current key and the row's binding, every row only the\n\t * previous key opens or that sits in a legacy envelope. The update matches on\n\t * the old ciphertext and URL too, so a row an admin re-saved in between is\n\t * left alone rather than overwritten.\n\t */\n\tasync reencryptSecrets(): Promise<number> {\n\t\tif (!this.secretKey) return 0;\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('compute_servers')\n\t\t\t.select('id, label, server_url, api_key');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tlet changed = 0;\n\t\tfor (const row of (data ?? []) as KeyRow[]) {\n\t\t\tif (!row.api_key || !isEncryptedSecret(row.api_key)) continue;\n\t\t\tlet opened: { plaintext: string; keyIndex: number };\n\t\t\ttry {\n\t\t\t\topened = decryptWithKeys(row.api_key, this.keys, bindingOf(row));\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (opened.keyIndex === 0 && !isLegacyEnvelope(row.api_key)) continue;\n\t\t\tconst { error: updateError, count } = await this.clients.serviceClient\n\t\t\t\t.from('compute_servers')\n\t\t\t\t.update(\n\t\t\t\t\t{ api_key: encryptSecret(opened.plaintext, this.secretKey, bindingOf(row)) },\n\t\t\t\t\t{ count: 'exact' }\n\t\t\t\t)\n\t\t\t\t.eq('id', row.id)\n\t\t\t\t.eq('server_url', row.server_url)\n\t\t\t\t.eq('api_key', row.api_key);\n\t\t\tif (updateError) throw mapPostgrestError(updateError);\n\t\t\tchanged += count ?? 0;\n\t\t}\n\t\treturn changed;\n\t}\n}\n\ninterface ServerRow {\n\tid: string;\n\tscope: 'platform' | 'org';\n\towner_org_id: string | null;\n\tshared_with_all: boolean;\n\tlabel: string;\n\tserver_url: string;\n\t/** Absent unless the row went through `withApiKeys`. */\n\tapi_key?: string | null;\n\t/** Generated column — true when a key is stored, without reading it. */\n\thas_api_key?: boolean;\n}\n\n/**\n * `withKey` mirrors the projection the row was read with. It gates `apiKey`\n * explicitly rather than trusting the row's shape, so a key can never ride along\n * on a read that didn't ask for one.\n */\nfunction rowToServer(\n\trow: ServerRow,\n\tsharedByServer: Map<string, string[]>,\n\twithKey: boolean\n): ComputeServerConfig {\n\tconst common = {\n\t\tid: row.id,\n\t\tlabel: row.label,\n\t\tserverUrl: row.server_url,\n\t\tapiKey: withKey ? (row.api_key ?? undefined) : undefined,\n\t\thasApiKey: row.has_api_key ?? !!row.api_key\n\t};\n\tif (row.scope === 'platform') {\n\t\treturn {\n\t\t\t...common,\n\t\t\tscope: 'platform',\n\t\t\tsharedWith: row.shared_with_all ? 'all' : (sharedByServer.get(row.id) ?? [])\n\t\t};\n\t}\n\tif (!row.owner_org_id) {\n\t\tthrow new Error(`compute_servers row ${row.id} has scope='org' but null owner_org_id`);\n\t}\n\treturn { ...common, scope: 'org', ownerOrgId: row.owner_org_id };\n}\n\n/**\n * Insert shape. Deliberately not `ServerRow`: `has_api_key` is generated by the\n * database and rejected on write, so the writable columns are their own type.\n */\ntype ServerWriteRow = Omit<ServerRow, 'has_api_key'>;\n\nfunction serverToRow(s: ComputeServerConfig): ServerWriteRow {\n\tconst base = {\n\t\tid: s.id,\n\t\tlabel: s.label,\n\t\tserver_url: s.serverUrl,\n\t\tapi_key: s.apiKey ?? null\n\t};\n\tif (isPlatformServer(s)) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tscope: 'platform',\n\t\t\towner_org_id: null,\n\t\t\tshared_with_all: s.sharedWith === 'all'\n\t\t};\n\t}\n\treturn {\n\t\t...base,\n\t\tscope: 'org',\n\t\towner_org_id: s.ownerOrgId,\n\t\tshared_with_all: false\n\t};\n}\n","import type {\n\tIShareLinkStore,\n\tIEventSink,\n\tOrgShareLink,\n\tShareLink,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { actorOf, NoopEventSink, ProviderError } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, toRange } from './pagination.js';\n\n/** Explicit column list for `share_links` — every field `rowToLink` consumes. */\nconst SHARE_LINK_COLUMNS =\n\t'id, definition_guid, channel, token_hash, name, created_by, created_at, expires_at, revoked_at, allow_solve, max_solves, solve_count';\n\n/**\n * Share-link store backed by Postgres.\n *\n * `getByTokenHash` and `tryIncrementSolveCount` go through the service-role\n * client and a SECURITY DEFINER RPC, bypassing RLS: the token itself is the\n * credential, not the authenticated user's identity.\n *\n * Reads filter `revoked_at` AND `expires_at` — a dead link must read dead\n * through the store, not only wherever a route remembers to re-check the date.\n * `try_increment_share_link_solve_count` already enforces both server-side.\n */\nexport class SupabaseShareLinkStore implements IShareLinkStore {\n\tprivate readonly events: IEventSink;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tevents: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.events = events;\n\t}\n\n\tasync create(ctx: RequestContext, link: ShareLink): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient.from('share_links').insert(linkToRow(link));\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'share_link.minted',\n\t\t\tlinkId: link.id,\n\t\t\tdefinitionId: link.definitionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync listByDefinition(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<ShareLink>> {\n\t\tconst range = toRange(opts);\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('share_links')\n\t\t\t.select(SHARE_LINK_COLUMNS, { count: 'exact' })\n\t\t\t.eq('definition_guid', definitionId)\n\t\t\t.is('revoked_at', null)\n\t\t\t.or(`expires_at.is.null,expires_at.gt.${new Date().toISOString()}`)\n\t\t\t.order('created_at', { ascending: false })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToLink);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync listByOrg(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<OrgShareLink>> {\n\t\t// An RPC because `definitions` and `projects` RLS would hide private projects\n\t\t// from the leadership reading this, and those are the links offboarding needs.\n\t\tconst range = toRange(opts);\n\t\tconst { data, error } = await this.clients.forRequest(ctx).rpc('org_share_link_roster', {\n\t\t\to: orgId,\n\t\t\tpage_limit: range.limit,\n\t\t\tpage_offset: range.from\n\t\t});\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst rows = (data ?? []) as OrgShareLinkRow[];\n\t\tconst nextCursor = nextCursorFromRange(range, rows.length, rows[0]?.total_count ?? 0);\n\t\treturn { items: rows.map(rowToOrgLink), nextCursor };\n\t}\n\n\tasync getById(ctx: RequestContext, id: string): Promise<ShareLink | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('share_links')\n\t\t\t.select(SHARE_LINK_COLUMNS)\n\t\t\t.eq('id', id)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToLink(data) : null;\n\t}\n\n\tasync getByTokenHash(_ctx: RequestContext, tokenHash: string): Promise<ShareLink | null> {\n\t\t// Service-role: RLS would scope this to \"links the current user can see\",\n\t\t// but an anonymous caller resolving a token has no user to scope to.\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('share_links')\n\t\t\t.select(`${SHARE_LINK_COLUMNS}, definitions!inner(deleted_at)`)\n\t\t\t.eq('token_hash', tokenHash)\n\t\t\t.is('revoked_at', null)\n\t\t\t.or(`expires_at.is.null,expires_at.gt.${new Date().toISOString()}`)\n\t\t\t.is('definitions.deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToLink(data) : null;\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst { data, error } = await client\n\t\t\t.from('share_links')\n\t\t\t.update({ revoked_at: new Date().toISOString() })\n\t\t\t.eq('id', id)\n\t\t\t.is('revoked_at', null)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) {\n\t\t\t// No rows means already revoked, which is fine, or no such link.\n\t\t\tconst { data: existing, error: readError } = await client\n\t\t\t\t.from('share_links')\n\t\t\t\t.select('revoked_at')\n\t\t\t\t.eq('id', id)\n\t\t\t\t.maybeSingle();\n\t\t\tif (readError) throw mapPostgrestError(readError);\n\t\t\tif (!existing) throw new ProviderError(`Share link '${id}' not found`, 404);\n\t\t\treturn;\n\t\t}\n\t\tawait this.events.emit({ type: 'share_link.revoked', linkId: id, ...actorOf(ctx) });\n\t}\n\n\tasync tryIncrementSolveCount(_ctx: RequestContext, id: string): Promise<number | null> {\n\t\t// Atomic check-and-increment in one RPC call: returns null if the link is\n\t\t// missing/revoked/expired/capped or its definition is soft-deleted, so\n\t\t// concurrent solves can't overshoot max_solves.\n\t\tconst { data, error } = await this.clients.serviceClient.rpc(\n\t\t\t'try_increment_share_link_solve_count',\n\t\t\t{ link_id: id }\n\t\t);\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn typeof data === 'number' ? data : null;\n\t}\n}\n\n// ============================================================================\n// Row ↔ domain mappers\n// ============================================================================\ninterface ShareLinkRow {\n\tid: string;\n\tdefinition_guid: string;\n\tchannel: 'live' | 'draft';\n\ttoken_hash: string;\n\tname: string | null;\n\tcreated_by: string;\n\tcreated_at: string;\n\texpires_at: string | null;\n\trevoked_at: string | null;\n\tallow_solve: boolean;\n\tmax_solves: number | null;\n\tsolve_count: number;\n}\n\n/** A row of the `org_share_link_roster` RPC. */\ninterface OrgShareLinkRow extends ShareLinkRow {\n\tdefinition_name: string;\n\tproject_id: string;\n\tproject_name: string;\n\ttotal_count: number;\n}\n\nfunction rowToOrgLink(row: OrgShareLinkRow): OrgShareLink {\n\t// `tokenHash` is dropped rather than carried: this row is built for a page\n\t// spanning every definition in the tenant.\n\tconst { tokenHash: _tokenHash, ...rest } = rowToLink(row);\n\treturn {\n\t\t...rest,\n\t\tdefinitionName: row.definition_name,\n\t\tprojectId: row.project_id,\n\t\tprojectName: row.project_name\n\t};\n}\n\nfunction rowToLink(row: ShareLinkRow): ShareLink {\n\treturn {\n\t\tid: row.id,\n\t\tdefinitionId: row.definition_guid,\n\t\tchannel: row.channel,\n\t\ttokenHash: row.token_hash,\n\t\tname: row.name ?? undefined,\n\t\tcreatedBy: row.created_by,\n\t\tcreatedAt: row.created_at,\n\t\texpiresAt: row.expires_at,\n\t\trevokedAt: row.revoked_at,\n\t\tallowSolve: row.allow_solve,\n\t\tmaxSolves: row.max_solves,\n\t\tsolveCount: row.solve_count\n\t};\n}\n\nfunction linkToRow(l: ShareLink): Record<string, unknown> {\n\treturn {\n\t\tid: l.id,\n\t\tdefinition_guid: l.definitionId,\n\t\tchannel: l.channel,\n\t\ttoken_hash: l.tokenHash,\n\t\tname: l.name ?? null,\n\t\tcreated_by: l.createdBy,\n\t\tcreated_at: l.createdAt,\n\t\texpires_at: l.expiresAt ?? null,\n\t\trevoked_at: l.revokedAt ?? null,\n\t\tallow_solve: l.allowSolve,\n\t\tmax_solves: l.maxSolves ?? null,\n\t\tsolve_count: l.solveCount\n\t};\n}\n","import type {\n\tApiToken,\n\tApiTokenRevokeReason,\n\tApiTokenSummary,\n\tIApiTokenStore,\n\tIEventSink,\n\tListOptions,\n\tPage,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopEventSink, actorOf } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, toRange } from './pagination.js';\n\n/** Every column a session may read: the hash is granted to service role only. */\nconst SUMMARY_COLUMNS =\n\t'id, user_id, created_by, org_id, name, scopes, created_at, expires_at, last_used_at, revoked_at';\n\n/**\n * API token store. `getByTokenHash` and `touchLastUsed` are called with\n * `SYSTEM_CONTEXT`, so they run as service role. Every other call runs under\n * the caller's session, and RLS limits it to their own keys plus, for\n * `manage_org_members`, the org's roster.\n */\nexport class SupabaseApiTokenStore implements IApiTokenStore {\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tprivate readonly events: IEventSink = new NoopEventSink()\n\t) {}\n\n\tasync create(ctx: RequestContext, token: ApiToken): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient.from('api_tokens').insert(tokenToRow(token));\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'api_token.created',\n\t\t\tapiTokenId: token.id,\n\t\t\torgId: token.orgId,\n\t\t\tuserId: token.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync getByTokenHash(ctx: RequestContext, tokenHash: string): Promise<ApiToken | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('api_tokens')\n\t\t\t.select(`${SUMMARY_COLUMNS}, token_hash`)\n\t\t\t.eq('token_hash', tokenHash)\n\t\t\t.is('revoked_at', null)\n\t\t\t.gt('expires_at', new Date().toISOString())\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToToken(data as ApiTokenRow) : null;\n\t}\n\n\tasync get(ctx: RequestContext, id: string): Promise<ApiTokenSummary | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('api_tokens')\n\t\t\t.select(SUMMARY_COLUMNS)\n\t\t\t.eq('id', id)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToSummary(data as SummaryRow) : null;\n\t}\n\n\tasync listByOrg(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions & { userId?: string }\n\t): Promise<Page<ApiTokenSummary>> {\n\t\tconst range = toRange(opts);\n\t\tlet query = this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('api_tokens')\n\t\t\t.select(SUMMARY_COLUMNS, { count: 'exact' })\n\t\t\t.eq('org_id', orgId);\n\t\tif (opts?.userId) query = query.eq('user_id', opts.userId);\n\t\tconst { data, error, count } = await query\n\t\t\t.order('created_at', { ascending: (opts?.orderDir ?? 'desc') === 'asc' })\n\t\t\t.order('id')\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = ((data ?? []) as SummaryRow[]).map(rowToSummary);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string, reason: ApiTokenRevokeReason): Promise<void> {\n\t\t// `.is('revoked_at', null)` keeps the first revocation time and makes a repeat a no-op.\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('api_tokens')\n\t\t\t.update({ revoked_at: new Date().toISOString() })\n\t\t\t.eq('id', id)\n\t\t\t.is('revoked_at', null)\n\t\t\t.select('id, org_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of (data ?? []) as RevokedRow[]) await this.emitRevoked(ctx, row, reason);\n\t}\n\n\tasync revokeAllForUser(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\topts: { orgId?: string; reason: ApiTokenRevokeReason }\n\t): Promise<string[]> {\n\t\tlet query = this.clients.serviceClient\n\t\t\t.from('api_tokens')\n\t\t\t.update({ revoked_at: new Date().toISOString() })\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('revoked_at', null);\n\t\tif (opts.orgId) query = query.eq('org_id', opts.orgId);\n\t\tconst { data, error } = await query.select('id, org_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst rows = (data ?? []) as RevokedRow[];\n\t\tfor (const row of rows) await this.emitRevoked(ctx, row, opts.reason);\n\t\treturn rows.map((r) => r.id);\n\t}\n\n\tasync touchLastUsed(ctx: RequestContext, id: string, at: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('api_tokens')\n\t\t\t.update({ last_used_at: at })\n\t\t\t.eq('id', id);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\t/**\n\t * Deleting the auth user does this through the FKs already. This covers a\n\t * caller erasing the rows before (or without) deleting the identity.\n\t */\n\tasync eraseUser(_ctx: RequestContext, userId: string): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst deleted = await client.from('api_tokens').delete().eq('user_id', userId);\n\t\tif (deleted.error) throw mapPostgrestError(deleted.error);\n\t\tconst cleared = await client\n\t\t\t.from('api_tokens')\n\t\t\t.update({ created_by: null })\n\t\t\t.eq('created_by', userId);\n\t\tif (cleared.error) throw mapPostgrestError(cleared.error);\n\t}\n\n\tasync deleteByOrg(ctx: RequestContext, orgId: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('api_tokens')\n\t\t\t.delete()\n\t\t\t.eq('org_id', orgId);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tprivate emitRevoked(\n\t\tctx: RequestContext,\n\t\trow: RevokedRow,\n\t\treason: ApiTokenRevokeReason\n\t): Promise<void> {\n\t\treturn this.events.emit({\n\t\t\ttype: 'api_token.revoked',\n\t\t\tapiTokenId: row.id,\n\t\t\torgId: row.org_id,\n\t\t\treason,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n\ninterface SummaryRow {\n\tid: string;\n\tuser_id: string;\n\tcreated_by: string | null;\n\torg_id: string;\n\tname: string;\n\tscopes: string[];\n\tcreated_at: string;\n\texpires_at: string;\n\tlast_used_at: string | null;\n\trevoked_at: string | null;\n}\n\ninterface ApiTokenRow extends SummaryRow {\n\ttoken_hash: string;\n}\n\ninterface RevokedRow {\n\tid: string;\n\torg_id: string;\n}\n\nfunction rowToSummary(row: SummaryRow): ApiTokenSummary {\n\treturn {\n\t\tid: row.id,\n\t\tuserId: row.user_id,\n\t\tcreatedBy: row.created_by,\n\t\torgId: row.org_id,\n\t\tname: row.name,\n\t\tscopes: row.scopes,\n\t\tcreatedAt: row.created_at,\n\t\texpiresAt: row.expires_at,\n\t\tlastUsedAt: row.last_used_at,\n\t\trevokedAt: row.revoked_at\n\t};\n}\n\nfunction rowToToken(row: ApiTokenRow): ApiToken {\n\treturn { ...rowToSummary(row), tokenHash: row.token_hash };\n}\n\nfunction tokenToRow(t: ApiToken): ApiTokenRow {\n\treturn {\n\t\tid: t.id,\n\t\tuser_id: t.userId,\n\t\tcreated_by: t.createdBy,\n\t\torg_id: t.orgId,\n\t\tname: t.name,\n\t\ttoken_hash: t.tokenHash,\n\t\tscopes: t.scopes,\n\t\tcreated_at: t.createdAt,\n\t\texpires_at: t.expiresAt,\n\t\tlast_used_at: t.lastUsedAt,\n\t\trevoked_at: t.revokedAt\n\t};\n}\n","/**\n * Timestamp prefix of the newest file in `supabase/migrations/`. Bump this\n * whenever a migration is added — `migration-head.test.ts` asserts it\n * matches the migrations directory, so CI catches drift.\n */\nexport const EXPECTED_MIGRATION_HEAD = '20261117200000';\n\n/**\n * The oldest head this build runs on; the handshake fails below it. Behind\n * {@link EXPECTED_MIGRATION_HEAD} only while a migration has to land after the\n * app: `20261113120000` takes every write away from sessions, which an older\n * build still writes with, so the app updates first and `db push` follows.\n * Raise it to the newest head once nothing needs that order.\n */\nexport const REQUIRED_MIGRATION_HEAD = '20261108140000';\n","import { createClient, type SupabaseClient } from '@supabase/supabase-js';\nimport type { RequestContext } from '@selvajs/platform';\n\n/**\n * supabase-js surfaces the schema as a type generic, and the bare\n * `SupabaseClient` default is pinned to `'public'` — this alias is what a\n * client with `db: { schema: 'selva' }` actually type-checks as.\n */\nexport type SelvaSchemaClient = SupabaseClient<any, 'public', 'selva'>;\n\n/** Default schema every engine store targets. */\nexport const DEFAULT_SCHEMA = 'selva' as const;\n\n/** A client pinned to a caller-chosen schema (opaque generic for non-`'selva'` schemas). */\nexport type SchemaClient = SupabaseClient<any, string, any>;\n\nexport interface ForRequestOptions {\n\t/** Postgres schema this client targets. Defaults to `'selva'`. */\n\tschema?: string;\n}\n\n/**\n * `forRequest` picks one of three fail-closed modes:\n * - `ctx.system === true` → service-role, bypasses RLS. Never derive this\n * flag from a user session — it must come from an explicitly-trusted\n * server flow (admin paths, janitors, bootstrap).\n * - `ctx.adapterContext.sessionToken` set → user-scoped, `authenticated`\n * role, RLS enforces per-user visibility via `auth.uid()`.\n * - neither → anon role, RLS active, no `auth.uid()`. This is the safety\n * net: a context built without a forwarded session token and without\n * `system: true` is untrusted by default.\n *\n * An earlier version fell back to service-role when the session token was\n * missing — fail-OPEN, so a synthetic ctx (e.g. share-token resolve) could\n * silently bypass RLS. Opt into service-role explicitly now, or you get RLS.\n *\n * `forRequest` caches per `(RequestContext, schema)` in a WeakMap so\n * multiple store calls in one HTTP handler share a client — and its fetch\n * connection — without leaking auth across requests.\n */\nexport interface ClientBundle {\n\t/**\n\t * Long-lived service-role client, pinned to the `'selva'` schema. Bypasses RLS.\n\t * Every write to `selva` goes through it: `anon` and `authenticated` hold\n\t * SELECT only, so the caller's own client cannot write.\n\t */\n\tserviceClient: SelvaSchemaClient;\n\t/** The caller's client, for reads: RLS decides what comes back. */\n\tforRequest(ctx: RequestContext, opts?: ForRequestOptions): SchemaClient;\n}\n\nexport interface BuildClientOptions {\n\tsupabaseUrl: string;\n\tanonKey: string;\n\tserviceRoleKey: string;\n}\n\nexport function buildClientBundle(opts: BuildClientOptions): ClientBundle {\n\t// Stateless w.r.t. request identity, so one instance per schema is safe to share.\n\tconst serviceBySchema = new Map<string, SchemaClient>();\n\tconst anonBySchema = new Map<string, SchemaClient>();\n\n\tfunction serviceFor(schema: string): SchemaClient {\n\t\tlet client = serviceBySchema.get(schema);\n\t\tif (!client) {\n\t\t\tclient = createClient(opts.supabaseUrl, opts.serviceRoleKey, {\n\t\t\t\tdb: { schema },\n\t\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t\t});\n\t\t\tserviceBySchema.set(schema, client);\n\t\t}\n\t\treturn client;\n\t}\n\n\tfunction anonFor(schema: string): SchemaClient {\n\t\tlet client = anonBySchema.get(schema);\n\t\tif (!client) {\n\t\t\tclient = createClient(opts.supabaseUrl, opts.anonKey, {\n\t\t\t\tdb: { schema },\n\t\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t\t});\n\t\t\tanonBySchema.set(schema, client);\n\t\t}\n\t\treturn client;\n\t}\n\n\tconst serviceClient = serviceFor(DEFAULT_SCHEMA) as SelvaSchemaClient;\n\tconst perRequestCache = new WeakMap<RequestContext, Map<string, SchemaClient>>();\n\n\treturn {\n\t\tserviceClient,\n\t\tforRequest(ctx: RequestContext, forOpts?: ForRequestOptions): SchemaClient {\n\t\t\tconst schema = forOpts?.schema ?? DEFAULT_SCHEMA;\n\t\t\tif (ctx.system) return serviceFor(schema);\n\n\t\t\tconst token = extractSessionToken(ctx.adapterContext);\n\t\t\tif (!token) return anonFor(schema);\n\n\t\t\tlet bySchema = perRequestCache.get(ctx);\n\t\t\tif (!bySchema) {\n\t\t\t\tbySchema = new Map();\n\t\t\t\tperRequestCache.set(ctx, bySchema);\n\t\t\t}\n\t\t\tconst cached = bySchema.get(schema);\n\t\t\tif (cached) return cached;\n\n\t\t\tconst client = createClient(opts.supabaseUrl, opts.anonKey, {\n\t\t\t\tdb: { schema },\n\t\t\t\tauth: { persistSession: false, autoRefreshToken: false },\n\t\t\t\tglobal: {\n\t\t\t\t\theaders: { Authorization: `Bearer ${token}` }\n\t\t\t\t}\n\t\t\t});\n\t\t\tbySchema.set(schema, client);\n\t\t\treturn client;\n\t\t}\n\t};\n}\n\n/**\n * Reads only `SUPABASE_URL` / `SUPABASE_ANON_KEY` / `SUPABASE_SERVICE_ROLE_KEY`.\n * Deliberately does not require `SELVA_AT_REST_KEY` — that's only needed for\n * compute-server secret encryption, which an app building its own `'public'`\n * stores never touches. `SupabaseDataProvider.fromEnv` adds that requirement\n * on top.\n */\nexport function clientBundleFromEnv(env: Record<string, string | undefined>): ClientBundle {\n\tconst supabaseUrl = env.SUPABASE_URL;\n\tconst anonKey = env.SUPABASE_ANON_KEY;\n\tconst serviceRoleKey = env.SUPABASE_SERVICE_ROLE_KEY;\n\tif (!supabaseUrl) throw new Error('Missing required env var: SUPABASE_URL');\n\tif (!anonKey) throw new Error('Missing required env var: SUPABASE_ANON_KEY');\n\tif (!serviceRoleKey) throw new Error('Missing required env var: SUPABASE_SERVICE_ROLE_KEY');\n\treturn buildClientBundle({ supabaseUrl, anonKey, serviceRoleKey });\n}\n\nfunction extractSessionToken(adapterContext: unknown): string | undefined {\n\tif (!adapterContext || typeof adapterContext !== 'object') return undefined;\n\tconst maybe = (adapterContext as { sessionToken?: unknown }).sessionToken;\n\treturn typeof maybe === 'string' && maybe.length > 0 ? maybe : undefined;\n}\n","import {\n\tAUDIT_EVENT_VERSION,\n\tNoopLogger,\n\ttype BaseEvent,\n\ttype DomainEvent,\n\ttype IEventSink,\n\ttype ILogger\n} from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\n\n/**\n * Persists every domain event to `public.audit_events`. Writes use the\n * service-role client so RLS does not gate the audit trail — the sink runs\n * as a system process attached to whichever store emitted the event.\n *\n * Per the `IEventSink` contract, `emit` MUST NOT throw. The user-facing\n * mutation has already succeeded by the time we're here; a failed audit\n * write is logged and swallowed so the response still completes.\n */\nexport class SupabaseEventSink<E extends BaseEvent = DomainEvent> implements IEventSink<E> {\n\tprivate readonly logger: ILogger;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\topts: { logger?: ILogger } = {}\n\t) {\n\t\tthis.logger = opts.logger ?? new NoopLogger();\n\t}\n\n\tasync emit(event: E): Promise<void> {\n\t\ttry {\n\t\t\tconst { error } = await this.clients.serviceClient.from('audit_events').insert({\n\t\t\t\ttype: event.type,\n\t\t\t\tactor_id: event.actorId,\n\t\t\t\tevent_version: AUDIT_EVENT_VERSION,\n\t\t\t\tdata: event,\n\t\t\t\t// Only when set, so session traffic still writes against a database\n\t\t\t\t// that predates the column.\n\t\t\t\t...(event.tokenId ? { token_id: event.tokenId } : {})\n\t\t\t});\n\t\t\tif (error) {\n\t\t\t\t// Only the event's identifiers are logged, never the whole event: an\n\t\t\t\t// `invite.created` payload embeds the invitee's email address, and log\n\t\t\t\t// records outlive and out-travel the audit row itself.\n\t\t\t\tthis.logger.error('Audit event insert failed', {\n\t\t\t\t\tcomponent: 'SupabaseEventSink',\n\t\t\t\t\teventType: event.type,\n\t\t\t\t\tactorId: event.actorId,\n\t\t\t\t\terr: error.message\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthis.logger.error('Unexpected error writing audit event', {\n\t\t\t\tcomponent: 'SupabaseEventSink',\n\t\t\t\teventType: event.type,\n\t\t\t\tactorId: event.actorId,\n\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t});\n\t\t}\n\t}\n}\n","import type { ISolveMetricSink, RequestContext, SolveMetric } from '@selvajs/platform';\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\n\ntype MetricRow = {\n\tactor_id: string;\n\tdefinition_url: string;\n\tdefinition_id: string | null;\n\tversion_id: string | null;\n\tchannel: string;\n\torg_id: string | null;\n\tduration_ms: number;\n\tok: boolean;\n\tfailure_kind: string;\n\terror_count: number;\n\twarning_count: number;\n};\n\nexport interface SolveMetricSinkOptions {\n\t/** Flush once this many rows are buffered. */\n\tmaxBatchSize?: number;\n\t/** Flush a non-empty buffer after this many ms, even if under `maxBatchSize`. */\n\tflushIntervalMs?: number;\n\t/**\n\t * Hard cap on rows not yet written, counting batches waiting their turn. Past\n\t * this, the oldest rows are dropped so a stalled or failing backend cannot grow\n\t * memory without bound.\n\t */\n\tmaxBufferSize?: number;\n\t/**\n\t * Structured logger for flush failures and buffer drops. Optional; defaults to\n\t * `NoopLogger` so this library never writes to stdout unless the app wires one.\n\t */\n\tlogger?: ILogger;\n}\n\nconst DEFAULT_MAX_BATCH_SIZE = 100;\nconst DEFAULT_FLUSH_INTERVAL_MS = 2000;\nconst DEFAULT_MAX_BUFFER_SIZE = 10_000;\n\n/**\n * Persists solve timings to `selva.solve_metrics`. Writes go through the\n * service-role client — the sink is a system process attached to the compute\n * route, not the requesting user, so RLS doesn't apply.\n *\n * Rows are buffered and batch-written: slider scrubbing fires solves far\n * faster than they're worth individual round-trips against a Postgres that\n * also serves auth. A batch flushes at `maxBatchSize` rows or `flushIntervalMs`\n * elapsed, whichever comes first.\n *\n * `record` must never throw — it runs on the hot path after the solve\n * response is already sent, so it only buffers; a failed flush is logged and\n * swallowed. That means an unclean shutdown loses buffered metrics; call\n * `close()` to drain deliberately.\n */\nexport class SupabaseSolveMetricSink implements ISolveMetricSink {\n\tprivate buffer: MetricRow[] = [];\n\t/** Claimed batches, oldest first, not counting the one being written. */\n\tprivate queued: MetricRow[][] = [];\n\tprivate timer: ReturnType<typeof setTimeout> | null = null;\n\tprivate draining = false;\n\tprivate drained: Promise<void> = Promise.resolve();\n\tprivate closed = false;\n\n\tprivate readonly maxBatchSize: number;\n\tprivate readonly flushIntervalMs: number;\n\tprivate readonly maxBufferSize: number;\n\tprivate readonly logger: ILogger;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\topts: SolveMetricSinkOptions = {}\n\t) {\n\t\tthis.maxBatchSize = opts.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;\n\t\tthis.flushIntervalMs = opts.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;\n\t\tthis.maxBufferSize = opts.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n\t\tthis.logger = opts.logger ?? new NoopLogger();\n\t}\n\n\tasync record(ctx: RequestContext, metric: SolveMetric): Promise<void> {\n\t\tif (this.closed) return;\n\n\t\tthis.buffer.push({\n\t\t\tactor_id: ctx.userId || 'system',\n\t\t\tdefinition_url: metric.definitionUrl,\n\t\t\tdefinition_id: metric.definitionId,\n\t\t\tversion_id: metric.versionId,\n\t\t\tchannel: metric.channel,\n\t\t\torg_id: metric.orgId,\n\t\t\tduration_ms: metric.durationMs,\n\t\t\tok: metric.ok,\n\t\t\tfailure_kind: metric.failureKind,\n\t\t\terror_count: metric.errorCount,\n\t\t\twarning_count: metric.warningCount\n\t\t});\n\n\t\tthis.enforceCap();\n\n\t\tif (this.buffer.length >= this.maxBatchSize) {\n\t\t\tvoid this.flush();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.scheduleFlush();\n\t}\n\n\t/**\n\t * Writes everything buffered and resolves once the write settles. Serialized\n\t * against any in-flight flush so batches cannot interleave. Never throws.\n\t */\n\tasync flush(): Promise<void> {\n\t\t// Claim the buffered rows synchronously, before yielding — otherwise a\n\t\t// record() landing between here and the write joins a batch already\n\t\t// counted as claimed, and the row is written twice or not at all.\n\t\tif (this.buffer.length > 0) this.queued.push(this.buffer);\n\t\tthis.buffer = [];\n\t\tthis.clearTimer();\n\t\tif (!this.draining) this.drained = this.drain();\n\t\treturn this.drained;\n\t}\n\n\t/** Rows held in memory waiting to be written. */\n\tget pendingRows(): number {\n\t\treturn this.buffer.length + this.queued.reduce((total, batch) => total + batch.length, 0);\n\t}\n\n\tprivate async drain(): Promise<void> {\n\t\tthis.draining = true;\n\t\tfor (let batch = this.queued.shift(); batch; batch = this.queued.shift()) {\n\t\t\tawait this.write(batch);\n\t\t}\n\t\tthis.draining = false;\n\t}\n\n\tprivate enforceCap(): void {\n\t\tconst overflow = this.pendingRows - this.maxBufferSize;\n\t\tif (overflow <= 0) return;\n\t\tlet remaining = overflow;\n\t\twhile (remaining > 0 && this.queued.length > 0) {\n\t\t\tconst oldest = this.queued[0];\n\t\t\tremaining -= oldest.splice(0, remaining).length;\n\t\t\tif (oldest.length === 0) this.queued.shift();\n\t\t}\n\t\tthis.buffer.splice(0, remaining);\n\t\tthis.logger.error('Metric buffer full, dropped oldest metrics', {\n\t\t\tcomponent: 'SupabaseSolveMetricSink',\n\t\t\tdropped: overflow\n\t\t});\n\t}\n\n\t/**\n\t * Stops the timer, drains the buffer, and makes further `record` calls no-ops.\n\t * Call on shutdown so the last partial batch isn't lost.\n\t */\n\tasync close(): Promise<void> {\n\t\tthis.closed = true;\n\t\tthis.clearTimer();\n\t\tawait this.flush();\n\t}\n\n\tprivate scheduleFlush(): void {\n\t\tif (this.timer) return;\n\t\tthis.timer = setTimeout(() => {\n\t\t\tthis.timer = null;\n\t\t\tvoid this.flush();\n\t\t}, this.flushIntervalMs);\n\t\t// Never hold the process open for telemetry.\n\t\tthis.timer.unref?.();\n\t}\n\n\tprivate clearTimer(): void {\n\t\tif (!this.timer) return;\n\t\tclearTimeout(this.timer);\n\t\tthis.timer = null;\n\t}\n\n\tprivate async write(batch: MetricRow[]): Promise<void> {\n\t\ttry {\n\t\t\tconst { error } = await this.clients.serviceClient.from('solve_metrics').insert(batch);\n\t\t\tif (error) {\n\t\t\t\tthis.logger.error('Metric batch insert failed', {\n\t\t\t\t\tcomponent: 'SupabaseSolveMetricSink',\n\t\t\t\t\tcount: batch.length,\n\t\t\t\t\terr: error.message\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthis.logger.error('Unexpected error writing metric batch', {\n\t\t\t\tcomponent: 'SupabaseSolveMetricSink',\n\t\t\t\tcount: batch.length,\n\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t});\n\t\t}\n\t}\n}\n","import type {\n\tAuditEventRow,\n\tAuditQueryFilters,\n\tAuditQueryResult,\n\tBaseEvent,\n\tDomainEvent,\n\tIAuditQuery,\n\tRequestContext\n} from '@selvajs/platform';\nimport { clampPageLimit } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\n\nconst ISO_RE = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:?\\d{2})$/;\nconst UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n/**\n * Read-side for `audit_events`. Always uses the service-role client — RLS\n * blocks all reads by design, so the route layer is the sole trust boundary\n * and must gate callers on `instance_admin`.\n *\n * Pagination is keyset on `(occurred_at desc, id desc)`; the `id` tie-breaker\n * prevents skipped rows when multiple events land in the same millisecond.\n */\nexport class SupabaseAuditQuery<E extends BaseEvent = DomainEvent> implements IAuditQuery<E> {\n\tconstructor(private readonly clients: ClientBundle) {}\n\n\tasync list(_ctx: RequestContext, filters: AuditQueryFilters<E>): Promise<AuditQueryResult<E>> {\n\t\tconst limit = clampPageLimit(filters.limit);\n\n\t\tlet q = this.clients.serviceClient\n\t\t\t.from('audit_events')\n\t\t\t.select('id, type, actor_id, occurred_at, data')\n\t\t\t.order('occurred_at', { ascending: false })\n\t\t\t.order('id', { ascending: false })\n\t\t\t.limit(limit + 1); // one extra row to detect \"has more\" without a count query\n\n\t\tif (filters.types && filters.types.length > 0) {\n\t\t\tq = q.in('type', [...filters.types]);\n\t\t}\n\t\tif (filters.actorId) {\n\t\t\tq = q.eq('actor_id', filters.actorId);\n\t\t}\n\t\tif (filters.sinceIso) {\n\t\t\tq = q.gte('occurred_at', filters.sinceIso);\n\t\t}\n\t\tif (filters.untilIso) {\n\t\t\tq = q.lte('occurred_at', filters.untilIso);\n\t\t}\n\t\tif (filters.cursor) {\n\t\t\t// Expresses `(occurred_at, id) < (cursorTs, cursorId)` as a PostgREST\n\t\t\t// `.or()` string: strictly older, or same timestamp with a smaller id.\n\t\t\t// Both values get interpolated into that string, so a malformed cursor\n\t\t\t// could inject arbitrary PostgREST operators — validate shape first.\n\t\t\tconst ts = filters.cursor.occurredAt;\n\t\t\tconst id = filters.cursor.id;\n\t\t\tif (!ISO_RE.test(ts) || !UUID_RE.test(id)) {\n\t\t\t\tthrow new Error('audit_events query: malformed cursor');\n\t\t\t}\n\t\t\tq = q.or(`occurred_at.lt.${ts},and(occurred_at.eq.${ts},id.lt.${id})`);\n\t\t}\n\n\t\tconst { data, error } = await q;\n\t\tif (error) {\n\t\t\tthrow new Error(`audit_events query failed: ${error.message}`);\n\t\t}\n\n\t\tconst fetched = (data ?? []) as Array<{\n\t\t\tid: string;\n\t\t\ttype: string;\n\t\t\tactor_id: string;\n\t\t\toccurred_at: string;\n\t\t\tdata: E;\n\t\t}>;\n\n\t\tconst hasMore = fetched.length > limit;\n\t\tconst page = hasMore ? fetched.slice(0, limit) : fetched;\n\t\tconst last = page[page.length - 1];\n\n\t\treturn {\n\t\t\trows: page.map((r) => ({\n\t\t\t\tid: r.id,\n\t\t\t\ttype: r.type as E['type'],\n\t\t\t\tactorId: r.actor_id,\n\t\t\t\toccurredAt: r.occurred_at,\n\t\t\t\tdata: r.data\n\t\t\t})) satisfies AuditEventRow<E>[],\n\t\t\tnextCursor: hasMore && last ? { occurredAt: last.occurred_at, id: last.id } : null\n\t\t};\n\t}\n}\n","import type {\n\tIUserProfileStore,\n\tRecentRun,\n\tRequestContext,\n\tUserManagementResult,\n\tUserProfile\n} from '@selvajs/platform';\nimport { ProviderError } from '@selvajs/platform';\nimport { assertCanAccessProfile, MAX_RECENT_RUNS } from '@selvajs/platform/userProfile';\nimport type { ClientBundle } from '../data/client.js';\n\n/**\n * Backed by `public.user_profiles` (one row per `auth.users.id`), auto-seeded\n * by the `handle_new_auth_user` trigger on signup — this store never inserts,\n * only reads/updates. Service-role throughout since RLS here is too coarse\n * for server-side flows like the hooks.server.ts profile load; `assertCanAccessProfile`\n * enforces \"own profile only\" at the app layer instead.\n */\n\nexport class SupabaseUserProfileProvider implements IUserProfileStore {\n\tconstructor(private readonly clients: ClientBundle) {}\n\n\tprivate client() {\n\t\treturn this.clients.serviceClient;\n\t}\n\n\tasync getProfile(ctx: RequestContext, userId: string): Promise<UserProfile | null> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id, display_name, starred_definitions, recent_runs')\n\t\t\t.eq('user_id', userId)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapError(error);\n\t\treturn data ? rowToProfile(data) : null;\n\t}\n\n\tasync getProfiles(_ctx: RequestContext, userIds: readonly string[]): Promise<UserProfile[]> {\n\t\t// No assertCanAccessProfile: this serves display-name lookups across other users.\n\t\tif (userIds.length === 0) return [];\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id, display_name, starred_definitions, recent_runs')\n\t\t\t.in('user_id', [...userIds]);\n\t\tif (error) throw mapError(error);\n\t\treturn (data ?? []).map(rowToProfile);\n\t}\n\n\tasync updateProfile(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tpatch: { displayName?: string }\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\tconst row: Record<string, unknown> = {};\n\t\tif (patch.displayName !== undefined) row.display_name = patch.displayName;\n\t\tif (Object.keys(row).length === 0) return 'ok';\n\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.update(row)\n\t\t\t.eq('user_id', userId)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapError(error);\n\t\treturn data && data.length > 0 ? 'ok' : 'not_found';\n\t}\n\n\tasync starDefinition(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tdefinitionId: string\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\t// Read-modify-write races under concurrent starring; a SECURITY DEFINER\n\t\t// RPC using array_append + array_distinct would close it if that matters.\n\t\tconst existing = await this.getProfile(ctx, userId);\n\t\tif (!existing) return 'not_found';\n\t\tif (existing.starredDefinitions.includes(definitionId)) return 'ok';\n\n\t\tconst next = [...existing.starredDefinitions, definitionId];\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.update({ starred_definitions: next })\n\t\t\t.eq('user_id', userId)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapError(error);\n\t\treturn data && data.length > 0 ? 'ok' : 'not_found';\n\t}\n\n\tasync unstarDefinition(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tdefinitionId: string\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\tconst existing = await this.getProfile(ctx, userId);\n\t\tif (!existing) return 'not_found';\n\t\tif (!existing.starredDefinitions.includes(definitionId)) return 'ok';\n\n\t\tconst next = existing.starredDefinitions.filter((id) => id !== definitionId);\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.update({ starred_definitions: next })\n\t\t\t.eq('user_id', userId)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapError(error);\n\t\treturn data && data.length > 0 ? 'ok' : 'not_found';\n\t}\n\n\tasync recordRun(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\trun: RecentRun\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\tconst existing = await this.getProfile(ctx, userId);\n\t\tif (!existing) return 'not_found';\n\n\t\tconst filtered = existing.recentRuns.filter((r) => r.definitionId !== run.definitionId);\n\t\tconst next = [run, ...filtered].slice(0, MAX_RECENT_RUNS);\n\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.update({ recent_runs: next })\n\t\t\t.eq('user_id', userId)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapError(error);\n\t\treturn data && data.length > 0 ? 'ok' : 'not_found';\n\t}\n}\n\ninterface ProfileRow {\n\tuser_id: string;\n\tdisplay_name: string | null;\n\tstarred_definitions: string[] | null;\n\trecent_runs: RecentRun[] | null;\n}\n\nfunction rowToProfile(row: ProfileRow): UserProfile {\n\treturn {\n\t\tuserId: row.user_id,\n\t\tdisplayName: row.display_name ?? undefined,\n\t\tstarredDefinitions: row.starred_definitions ?? [],\n\t\trecentRuns: row.recent_runs ?? []\n\t};\n}\n\ninterface PostgrestError {\n\tcode?: string;\n\tmessage?: string;\n}\n\nfunction mapError(e: unknown): Error {\n\tconst pg = e as PostgrestError;\n\tif (pg?.code === '23505') return new ProviderError(pg.message ?? 'Duplicate record', 409);\n\tif (pg?.code === '23503') return new ProviderError(pg.message ?? 'Foreign key violation', 409);\n\tif (e instanceof Error) return e;\n\tif (e && typeof e === 'object') {\n\t\tconst obj = e as { message?: string; code?: string };\n\t\treturn new Error(obj.code ? `[${obj.code}] ${obj.message ?? ''}` : (obj.message ?? String(e)));\n\t}\n\treturn new Error(String(e));\n}\n","import type {\n\tIPlatformPermissionStore,\n\tPlatformPermission,\n\tRequestContext,\n\tUserManagementResult\n} from '@selvajs/platform';\nimport { ProviderError, ALL_PLATFORM_PERMISSIONS } from '@selvajs/platform';\nimport {\n\tassertCanManagePermissions,\n\tassertCanReadPermissions,\n\tassertCanReadPermissionsBatch\n} from '@selvajs/platform/permissions';\nimport type { ClientBundle } from '../data/client.js';\n\n/**\n * Reads and writes `public.user_profiles.platform_permissions` (auto-seeded\n * by the `handle_new_auth_user` trigger). Service-role throughout — RLS on\n * `user_profiles` is too coarse for cross-user reads, so `assertCanManagePermissions` /\n * `assertCanReadPermissions` enforce the auth boundary here instead.\n *\n * `user_profiles.disabled` mirrors the user's ban and `app_metadata.disabled` via\n * the `sync_auth_user_disabled` trigger, so admin-count queries can exclude\n * disabled admins with a single indexed query instead of cross-referencing\n * the auth admin API per candidate.\n */\nexport class SupabasePlatformPermissionStore implements IPlatformPermissionStore {\n\tconstructor(private readonly clients: ClientBundle) {}\n\n\tprivate client() {\n\t\treturn this.clients.serviceClient;\n\t}\n\n\tasync getFor(ctx: RequestContext, userId: string): Promise<PlatformPermission[]> {\n\t\tassertCanReadPermissions(ctx, userId);\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('platform_permissions')\n\t\t\t.eq('user_id', userId)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapError(error);\n\t\treturn filterValid(data?.platform_permissions ?? []);\n\t}\n\n\tasync getForBatch(\n\t\tctx: RequestContext,\n\t\tuserIds: readonly string[]\n\t): Promise<Map<string, PlatformPermission[]>> {\n\t\tassertCanReadPermissionsBatch(ctx);\n\t\tconst out = new Map<string, PlatformPermission[]>();\n\t\tif (userIds.length === 0) return out;\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id, platform_permissions')\n\t\t\t.in('user_id', [...userIds]);\n\t\tif (error) throw mapError(error);\n\t\tfor (const row of data ?? []) {\n\t\t\tout.set(row.user_id as string, filterValid((row.platform_permissions ?? []) as string[]));\n\t\t}\n\t\treturn out;\n\t}\n\n\tasync set(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tpermissions: readonly PlatformPermission[]\n\t): Promise<UserManagementResult> {\n\t\tassertCanManagePermissions(ctx);\n\n\t\t// The last-admin check runs inside the RPC, under the locks that guard the\n\t\t// write. A count here would let two demotions each see the other survive.\n\t\tconst { data, error } = await this.client().rpc('set_platform_permissions', {\n\t\t\tp_user_id: userId,\n\t\t\tp_permissions: [...permissions]\n\t\t});\n\t\tif (error) throw mapError(error);\n\t\tif ((data ?? 0) > 0) return 'ok';\n\n\t\t// Zero rows written: either the row is absent, or the predicate refused\n\t\t// the demotion. Only the second is `last_admin`, so disambiguate.\n\t\tconst { data: existing, error: fetchError } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id')\n\t\t\t.eq('user_id', userId)\n\t\t\t.maybeSingle();\n\t\tif (fetchError) throw mapError(fetchError);\n\t\treturn existing ? 'last_admin' : 'not_found';\n\t}\n\n\tasync claimFirstInstanceAdmin(\n\t\t_ctx: RequestContext,\n\t\tuserId: string,\n\t\tpermissions: readonly PlatformPermission[]\n\t): Promise<boolean> {\n\t\t// No `assertCanManagePermissions`: by definition nobody holds `instance_admin` when this\n\t\t// succeeds. The RPC takes an advisory lock and re-reads inside it, so a\n\t\t// second concurrent signer blocks and then correctly loses.\n\t\tconst { data, error } = await this.client().rpc('claim_first_instance_admin', {\n\t\t\tp_user_id: userId,\n\t\t\tp_permissions: [...permissions]\n\t\t});\n\t\tif (error) throw mapError(error);\n\t\treturn data === true;\n\t}\n\n\tasync hasInstanceAdmin(_ctx: RequestContext): Promise<boolean> {\n\t\tconst { count, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id', { count: 'exact', head: true })\n\t\t\t.contains('platform_permissions', ['instance_admin'])\n\t\t\t.eq('disabled', false);\n\t\tif (error) throw mapError(error);\n\t\treturn (count ?? 0) > 0;\n\t}\n\n\tasync countInstanceAdminsExcluding(_ctx: RequestContext, excludeUserId: string): Promise<number> {\n\t\treturn this.countOtherEnabledAdmins(excludeUserId);\n\t}\n\n\tprivate async countOtherEnabledAdmins(excludeUserId: string): Promise<number> {\n\t\tconst { count, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id', { count: 'exact', head: true })\n\t\t\t.contains('platform_permissions', ['instance_admin'])\n\t\t\t.eq('disabled', false)\n\t\t\t.neq('user_id', excludeUserId);\n\t\tif (error) throw mapError(error);\n\t\treturn count ?? 0;\n\t}\n}\n\nconst VALID_PERMISSIONS = new Set<string>(ALL_PLATFORM_PERMISSIONS);\n\nfunction filterValid(raw: readonly string[]): PlatformPermission[] {\n\treturn raw.filter((p): p is PlatformPermission => VALID_PERMISSIONS.has(p));\n}\n\ninterface PostgrestError {\n\tcode?: string;\n\tmessage?: string;\n}\n\nfunction mapError(e: unknown): Error {\n\tconst pg = e as PostgrestError;\n\tif (pg?.code === '23505') return new ProviderError(pg.message ?? 'Duplicate record', 409);\n\tif (pg?.code === '23503') return new ProviderError(pg.message ?? 'Foreign key violation', 409);\n\tif (e instanceof Error) return e;\n\tif (e && typeof e === 'object') {\n\t\tconst obj = e as { message?: string; code?: string };\n\t\treturn new Error(obj.code ? `[${obj.code}] ${obj.message ?? ''}` : (obj.message ?? String(e)));\n\t}\n\treturn new Error(String(e));\n}\n","import type {\n\tIDataProvider,\n\tIEventSink,\n\tPurgeResult,\n\tRequestContext,\n\tRetentionCutoffs,\n\tSchemaVersionReport,\n\tUserErasureOptions\n} from '@selvajs/platform';\nimport { ERASED_ACTOR_ID, NoopLogger, ProviderError, type ILogger } from '@selvajs/platform';\nimport { readAtRestKeys } from '@selvajs/platform/computeServer';\nimport { EXPECTED_MIGRATION_HEAD, REQUIRED_MIGRATION_HEAD } from './migrationHead.js';\nimport type { ClientBundle, BuildClientOptions } from './client.js';\nimport { buildClientBundle, clientBundleFromEnv } from './client.js';\nimport { SupabaseEventSink } from './SupabaseEventSink.js';\nimport { SupabaseSolveMetricSink } from './SupabaseSolveMetricSink.js';\nimport { SupabaseAuditQuery } from './SupabaseAuditQuery.js';\nimport { SupabaseOrgStore } from './SupabaseOrgStore.js';\nimport { SupabaseProjectStore } from './SupabaseProjectStore.js';\nimport { SupabaseDefinitionStore } from './SupabaseDefinitionStore.js';\nimport { SupabaseInviteStore } from './SupabaseInviteStore.js';\nimport { SupabaseComputeServerStore } from './SupabaseComputeServerStore.js';\nimport { SupabaseShareLinkStore } from './SupabaseShareLinkStore.js';\nimport { SupabaseApiTokenStore } from './SupabaseApiTokenStore.js';\nimport { SupabaseUserProfileProvider } from '../userProfile/SupabaseUserProfileProvider.js';\nimport { SupabasePlatformPermissionStore } from '../permissions/SupabasePlatformPermissionStore.js';\nimport { SupabasePlatformProjectGrantStore } from './SupabasePlatformProjectGrantStore.js';\n\n/**\n * Composition of every data store for the Supabase backend. Builds one\n * `ClientBundle` and wires every store to it, so all stores in a process\n * share the same pooled clients.\n */\nexport class SupabaseDataProvider implements IDataProvider {\n\treadonly orgs: SupabaseOrgStore;\n\treadonly projects: SupabaseProjectStore;\n\treadonly definitions: SupabaseDefinitionStore;\n\treadonly invites: SupabaseInviteStore;\n\treadonly computeServer: SupabaseComputeServerStore;\n\treadonly shareLinks: SupabaseShareLinkStore;\n\treadonly apiTokens: SupabaseApiTokenStore;\n\treadonly userProfile: SupabaseUserProfileProvider;\n\treadonly permissions: SupabasePlatformPermissionStore;\n\treadonly platformProjectGrants: SupabasePlatformProjectGrantStore;\n\treadonly auditQuery: SupabaseAuditQuery;\n\treadonly events: IEventSink;\n\t/** Built from the same client bundle so wiring `SelvaConfig.solveMetrics` doesn't need a second Supabase client. */\n\treadonly solveMetrics: SupabaseSolveMetricSink;\n\n\tprivate constructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tevents: IEventSink,\n\t\tsecretKey?: Buffer,\n\t\tlogger: ILogger = new NoopLogger(),\n\t\tpreviousSecretKey?: Buffer\n\t) {\n\t\tthis.events = events;\n\t\tthis.solveMetrics = new SupabaseSolveMetricSink(clients, { logger });\n\t\tthis.orgs = new SupabaseOrgStore(clients, events);\n\t\tthis.projects = new SupabaseProjectStore(clients, events);\n\t\tthis.definitions = new SupabaseDefinitionStore(clients, events);\n\t\tthis.invites = new SupabaseInviteStore(clients, events);\n\t\tthis.computeServer = new SupabaseComputeServerStore(\n\t\t\tclients,\n\t\t\tsecretKey,\n\t\t\tlogger,\n\t\t\tpreviousSecretKey\n\t\t);\n\t\tthis.shareLinks = new SupabaseShareLinkStore(clients, events);\n\t\tthis.apiTokens = new SupabaseApiTokenStore(clients, events);\n\t\tthis.userProfile = new SupabaseUserProfileProvider(clients);\n\t\tthis.permissions = new SupabasePlatformPermissionStore(clients);\n\t\tthis.platformProjectGrants = new SupabasePlatformProjectGrantStore(clients);\n\t\tthis.auditQuery = new SupabaseAuditQuery(clients);\n\t}\n\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tevents?: IEventSink,\n\t\tlogger: ILogger = new NoopLogger()\n\t): SupabaseDataProvider {\n\t\tconst bundle = clientBundleFromEnv(env);\n\t\t// Same encryption-at-rest guarantee as the local provider's on-disk envelope.\n\t\tconst keys = readAtRestKeys(env);\n\t\treturn new SupabaseDataProvider(\n\t\t\tbundle,\n\t\t\tevents ?? new SupabaseEventSink(bundle, { logger }),\n\t\t\tkeys.current,\n\t\t\tlogger,\n\t\t\tkeys.previous\n\t\t);\n\t}\n\n\tstatic create(\n\t\topts: BuildClientOptions,\n\t\tevents?: IEventSink,\n\t\tsecretKey?: Buffer,\n\t\tlogger: ILogger = new NoopLogger()\n\t): SupabaseDataProvider {\n\t\tconst bundle = buildClientBundle(opts);\n\t\treturn new SupabaseDataProvider(\n\t\t\tbundle,\n\t\t\tevents ?? new SupabaseEventSink(bundle, { logger }),\n\t\t\tsecretKey,\n\t\t\tlogger\n\t\t);\n\t}\n\n\t/**\n\t * Build from a pre-existing `ClientBundle` — for tests or callers that need\n\t * to inject a custom event sink or share a bundle externally. Omit\n\t * `secretKey` only if the caller never touches compute-server apiKeys:\n\t * writes without a key throw rather than persist plaintext.\n\t */\n\tstatic fromBundle(\n\t\tbundle: ClientBundle,\n\t\tevents?: IEventSink,\n\t\tsecretKey?: Buffer,\n\t\tlogger: ILogger = new NoopLogger()\n\t): SupabaseDataProvider {\n\t\treturn new SupabaseDataProvider(\n\t\t\tbundle,\n\t\t\tevents ?? new SupabaseEventSink(bundle, { logger }),\n\t\t\tsecretKey,\n\t\t\tlogger\n\t\t);\n\t}\n\n\t/** Lets other providers in this package (storage, user profile, auth) share one set of clients per process. */\n\tgetClientBundle(): ClientBundle {\n\t\treturn this.clients;\n\t}\n\n\t/**\n\t * Calls `selva.migration_head()` (a SECURITY DEFINER RPC shipped in this\n\t * package's migrations) and compares it to the head this build expects.\n\t * Three failure shapes: the RPC is missing (handshake migration never\n\t * applied), the head is empty (no migrations pushed), or the head is\n\t * lexicographically behind {@link REQUIRED_MIGRATION_HEAD} (operator upgraded\n\t * the app but skipped `supabase db push`). A head between that and the newest\n\t * is ok, with a message naming what is pending. Never throws — boot health\n\t * consumes the report.\n\t */\n\tasync verifySchemaVersion(): Promise<SchemaVersionReport> {\n\t\tconst expected = EXPECTED_MIGRATION_HEAD;\n\t\tconst pushHint =\n\t\t\t'Apply the pending Supabase migrations: run `npx selva-supabase` to copy them ' +\n\t\t\t'into your project, then `npx supabase db push`.';\n\t\ttry {\n\t\t\tconst { data, error } = await this.clients.serviceClient.rpc('migration_head');\n\t\t\tif (error) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\texpected,\n\t\t\t\t\tactual: null,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`selva.migration_head() is not available (${error.message ?? error.code ?? 'unknown error'}) ` +\n\t\t\t\t\t\t`— the database schema is behind this app version. ${pushHint}`\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst actual = typeof data === 'string' ? data : '';\n\t\t\tif (!actual) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\texpected,\n\t\t\t\t\tactual: '',\n\t\t\t\t\tmessage: `The database reports no applied migrations. ${pushHint}`\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Timestamp prefixes are fixed-width, so string comparison is chronological.\n\t\t\t// A head ahead of the app (rolled-back app, newer DB) is tolerated — schema\n\t\t\t// changes are append-only by convention.\n\t\t\tif (actual < REQUIRED_MIGRATION_HEAD) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\texpected,\n\t\t\t\t\tactual,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`Database migration head ${actual} is behind ${REQUIRED_MIGRATION_HEAD}, ` +\n\t\t\t\t\t\t`the oldest this app runs on. ${pushHint}`\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\texpected,\n\t\t\t\tactual,\n\t\t\t\tmessage:\n\t\t\t\t\tactual < expected\n\t\t\t\t\t\t? `Migrations after ${actual} are pending; the app runs without them. ${pushHint}`\n\t\t\t\t\t\t: undefined\n\t\t\t};\n\t\t} catch (err) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\texpected,\n\t\t\t\tactual: null,\n\t\t\t\tmessage: `Schema handshake failed: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t};\n\t\t}\n\t}\n\n\t/** No-op: the `handle_new_auth_user` trigger seeds `user_profiles` on every `auth.users` insert. */\n\tasync ensureUser(): Promise<void> {\n\t\t// no-op\n\t}\n\n\t/**\n\t * FK cascade against `auth.users` already removes the profile, memberships,\n\t * and owned rows. Four classes of personal data aren't reachable by those\n\t * FKs and get scrubbed here explicitly, with the RLS-bypassing service client:\n\t *\n\t * 1. `audit_events` keyed by a plain-text `actor_id` (no FK) — deleted.\n\t * 2. The user's email in `invites.email` and in `invite.created` audit\n\t * payloads (`data->>'email'`). Invite rows are deleted; the audit email\n\t * is redacted in place — the fact that an invite was created stays, only\n\t * the PII goes.\n\t * 3. `solve_metrics.actor_id`, deliberately not FK-cascaded (retention\n\t * telemetry) — tombstoned to {@link ERASED_ACTOR_ID} so the row's\n\t * aggregate value survives without identifying the person.\n\t * 4. `platform_project_grants`, whose grantee has no FK: grants to the user\n\t * are deleted, and those they created lose `created_by`.\n\t *\n\t * Each step tolerates missing rows, so retrying is safe. Email scrubs are\n\t * skipped when `opts.email` is absent — the caller must capture it before\n\t * `deleteUser`.\n\t */\n\tasync onUserDeleted(\n\t\t_ctx: RequestContext,\n\t\tuserId: string,\n\t\topts?: UserErasureOptions\n\t): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\t// Invites, and the `invite.created` payloads that copy them, hold the address lowercased.\n\t\tconst email = opts?.email?.trim().toLowerCase();\n\n\t\tconst deletedActions = await client.from('audit_events').delete().eq('actor_id', userId);\n\t\tif (deletedActions.error) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Failed to erase audit_events for user: ${deletedActions.error.message}`,\n\t\t\t\t500\n\t\t\t);\n\t\t}\n\n\t\tconst tombstoned = await client\n\t\t\t.from('solve_metrics')\n\t\t\t.update({ actor_id: ERASED_ACTOR_ID })\n\t\t\t.eq('actor_id', userId);\n\t\tif (tombstoned.error) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Failed to anonymize solve_metrics for user: ${tombstoned.error.message}`,\n\t\t\t\t500\n\t\t\t);\n\t\t}\n\n\t\tawait this.platformProjectGrants.eraseUser(userId);\n\n\t\tif (!email) return;\n\n\t\t// `invited_by` FK cascade only removes invites this user SENT, not ones addressed to them.\n\t\tconst deletedInvites = await client.from('invites').delete().eq('email', email);\n\t\tif (deletedInvites.error) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Failed to erase invites for user email: ${deletedInvites.error.message}`,\n\t\t\t\t500\n\t\t\t);\n\t\t}\n\n\t\tconst redacted = await client.rpc('redact_audit_event_email', { p_email: email });\n\t\tif (redacted.error) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Failed to redact audit_events email payloads: ${redacted.error.message}`,\n\t\t\t\t500\n\t\t\t);\n\t\t}\n\t}\n\n\tasync purgeExpired(_ctx: RequestContext, cutoffs: RetentionCutoffs): Promise<PurgeResult> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst purge = async (table: 'audit_events' | 'solve_metrics', before?: Date) => {\n\t\t\tif (!before) return 0;\n\t\t\t// Both tables carry an `occurred_at` index, so this is a range delete, not a scan.\n\t\t\tconst { error, count } = await client\n\t\t\t\t.from(table)\n\t\t\t\t.delete({ count: 'exact' })\n\t\t\t\t.lt('occurred_at', before.toISOString());\n\t\t\tif (error) throw new ProviderError(`Failed to purge ${table}: ${error.message}`, 500);\n\t\t\treturn count ?? 0;\n\t\t};\n\t\treturn {\n\t\t\tauditEvents: await purge('audit_events', cutoffs.auditEventsBefore),\n\t\t\tsolveMetrics: await purge('solve_metrics', cutoffs.solveMetricsBefore)\n\t\t};\n\t}\n}\n","import { createHmac, createPrivateKey, randomUUID, sign } from 'node:crypto';\nimport {\n\tNoopLogger,\n\tProviderError,\n\ttype DelegatedSessionStatus,\n\ttype IDelegatedSession,\n\ttype ILogger,\n\ttrimTrailing\n} from '@selvajs/platform';\n\nexport interface SupabaseDelegatedSessionConfig {\n\tsupabaseUrl: string;\n\tanonKey: string;\n\t/** `SUPABASE_JWT_SIGNING_KEY`: a private ES256 JWK the project trusts. Preferred. */\n\tsigningKey?: string;\n\t/** `SUPABASE_JWT_SECRET`: the legacy HS256 secret. Used only without `signingKey`. */\n\tjwtSecret?: string;\n\t/**\n\t * How long a minted session lives. It is minted once per request, so it must\n\t * outlive the slowest one (a solve), or the writes after it fail with an\n\t * expired JWT. Default 60.\n\t */\n\tttlSeconds?: number;\n\tlogger?: ILogger;\n\tfetch?: typeof fetch;\n\tnow?: () => number;\n}\n\nconst DEFAULT_TTL_SECONDS = 60;\n/** A failed check (network, or a key not yet rotated in) is retried after this long. */\nconst RECHECK_FAILED_MS = 30_000;\n\ninterface CheckEntry {\n\tresult: Promise<DelegatedSessionStatus>;\n\t/** Null after a success, which is never re-checked. */\n\tfailedAt: number | null;\n}\n\ninterface Signer {\n\talg: 'ES256' | 'HS256';\n\tkid?: string;\n\t/** Names the key for an operator, without any key material. */\n\tlabel: string;\n\thint: string;\n\tsign(data: Buffer): Buffer;\n}\n\n/**\n * Signs short-lived Supabase session JWTs so API-token requests run under the\n * owner's row security. The claims are fixed: `role` is always\n * `authenticated`, never caller-chosen, because the same key can sign a\n * `service_role` token that bypasses every policy.\n *\n * `aud` is required by GoTrue's `getUser` (400 without it); `session_id` is\n * omitted because GoTrue looks it up and rejects one with no session row.\n *\n * `selva_org` marks the session as delegated. `selva.is_instance_admin()`\n * returns false for any session carrying it, so an instance admin's key can't\n * reach other orgs through the policies' admin bypass.\n */\nexport class SupabaseDelegatedSession implements IDelegatedSession {\n\tprivate readonly signer: Signer | null;\n\tprivate readonly configError: string | null;\n\tprivate readonly logger: ILogger;\n\tprivate readonly fetchFn: typeof fetch;\n\tprivate readonly now: () => number;\n\tprivate readonly baseUrl: string;\n\tprivate check: CheckEntry | null = null;\n\n\tconstructor(private readonly config: SupabaseDelegatedSessionConfig) {\n\t\tthis.baseUrl = trimTrailing(config.supabaseUrl, '/');\n\t\tthis.logger = config.logger ?? new NoopLogger();\n\t\tthis.fetchFn = config.fetch ?? fetch;\n\t\tthis.now = config.now ?? Date.now;\n\t\tlet signer: Signer | null = null;\n\t\tlet configError: string | null = null;\n\t\ttry {\n\t\t\tsigner = config.signingKey\n\t\t\t\t? es256Signer(config.signingKey)\n\t\t\t\t: config.jwtSecret\n\t\t\t\t\t? hs256Signer(config.jwtSecret)\n\t\t\t\t\t: null;\n\t\t\tif (!signer) {\n\t\t\t\tconfigError =\n\t\t\t\t\t'API tokens need SUPABASE_JWT_SIGNING_KEY (or the legacy SUPABASE_JWT_SECRET) so Selva can act as the token owner under row security.';\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconfigError = err instanceof Error ? err.message : String(err);\n\t\t}\n\t\tthis.signer = signer;\n\t\tthis.configError = configError;\n\t}\n\n\tstatus(): Promise<DelegatedSessionStatus> {\n\t\tif (!this.signer) return Promise.resolve({ ok: false, message: this.configError! });\n\t\tconst current = this.check;\n\t\tif (\n\t\t\tcurrent &&\n\t\t\t(current.failedAt === null || this.now() - current.failedAt < RECHECK_FAILED_MS)\n\t\t) {\n\t\t\treturn current.result;\n\t\t}\n\t\tconst next = { failedAt: null } as CheckEntry;\n\t\tnext.result = this.probe(this.signer).then((status) => {\n\t\t\tif (!status.ok) {\n\t\t\t\tnext.failedAt = this.now();\n\t\t\t\tthis.logger.error('API tokens are off: delegated sessions failed their check', {\n\t\t\t\t\tcomponent: 'delegatedSession',\n\t\t\t\t\treason: status.message\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn status;\n\t\t});\n\t\tthis.check = next;\n\t\treturn next.result;\n\t}\n\n\tasync mint(userId: string, { orgId }: { orgId: string }): Promise<string> {\n\t\tconst status = await this.status();\n\t\tif (!status.ok) throw new ProviderError(status.message, 503);\n\t\treturn this.signFor(this.signer!, userId, orgId);\n\t}\n\n\t/**\n\t * Proves PostgREST accepts what this key signs, which a JWKS lookup alone\n\t * doesn't: Supabase lists a standby key in the JWKS but only trusts it once\n\t * the project has rotated to it. The random `sub` matches no rows, so the\n\t * read is empty either way; only a 401 means the key is refused.\n\t */\n\tprivate async probe(signer: Signer): Promise<DelegatedSessionStatus> {\n\t\ttry {\n\t\t\tconst res = await this.fetchFn(`${this.baseUrl}/rest/v1/orgs?select=id&limit=1`, {\n\t\t\t\theaders: {\n\t\t\t\t\tapikey: this.config.anonKey,\n\t\t\t\t\tAuthorization: `Bearer ${this.signFor(signer, randomUUID(), randomUUID())}`,\n\t\t\t\t\t'Accept-Profile': 'selva'\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (res.ok) return { ok: true };\n\t\t\tif (res.status === 401) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tmessage: `Supabase rejected a session signed with ${signer.label}. ${signer.hint}`\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: `Couldn't check ${signer.label}: Supabase answered ${res.status}.`\n\t\t\t};\n\t\t} catch (err) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: `Couldn't reach Supabase to check ${signer.label}: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate signFor(signer: Signer, userId: string, orgId: string): string {\n\t\tconst iat = Math.floor(this.now() / 1000);\n\t\tconst header = { alg: signer.alg, typ: 'JWT', ...(signer.kid ? { kid: signer.kid } : {}) };\n\t\tconst payload = {\n\t\t\tsub: userId,\n\t\t\trole: 'authenticated',\n\t\t\taud: 'authenticated',\n\t\t\tiat,\n\t\t\texp: iat + (this.config.ttlSeconds ?? DEFAULT_TTL_SECONDS),\n\t\t\tiss: `${this.baseUrl}/auth/v1`,\n\t\t\tselva_org: orgId\n\t\t};\n\t\tconst input = `${base64url(header)}.${base64url(payload)}`;\n\t\treturn `${input}.${signer.sign(Buffer.from(input)).toString('base64url')}`;\n\t}\n}\n\nfunction base64url(value: object): string {\n\treturn Buffer.from(JSON.stringify(value)).toString('base64url');\n}\n\ninterface EcJwk {\n\tkty?: string;\n\tcrv?: string;\n\tx?: string;\n\ty?: string;\n\td?: string;\n\tkid?: string;\n\tkey_ops?: string[];\n}\n\n/** Accepts the JWK `supabase gen signing-key` prints, or an array of them (a `signing_keys.json`). */\nfunction es256Signer(raw: string): Signer {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\tthrow new Error(\n\t\t\t'SUPABASE_JWT_SIGNING_KEY is not valid JSON. Expected the private JWK from `supabase gen signing-key --algorithm ES256`.'\n\t\t);\n\t}\n\tconst keys = (Array.isArray(parsed) ? parsed : [parsed]) as EcJwk[];\n\tconst jwk = keys.find((k) => k?.key_ops?.includes('sign')) ?? keys[0];\n\tif (!jwk || jwk.kty !== 'EC' || jwk.crv !== 'P-256' || !jwk.d || !jwk.x || !jwk.y) {\n\t\tthrow new Error(\n\t\t\t'SUPABASE_JWT_SIGNING_KEY must be a private ES256 key: kty \"EC\", crv \"P-256\", with \"d\".'\n\t\t);\n\t}\n\tif (!jwk.kid) {\n\t\tthrow new Error(\n\t\t\t'SUPABASE_JWT_SIGNING_KEY has no \"kid\". Supabase matches tokens to keys by it.'\n\t\t);\n\t}\n\tconst key = createPrivateKey({\n\t\tkey: { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y, d: jwk.d },\n\t\tformat: 'jwk'\n\t});\n\treturn {\n\t\talg: 'ES256',\n\t\tkid: jwk.kid,\n\t\tlabel: `SUPABASE_JWT_SIGNING_KEY (kid ${jwk.kid})`,\n\t\thint:\n\t\t\t'On hosted Supabase, import it as a standby key under Settings → JWT signing keys, then rotate to it. ' +\n\t\t\t'Self-hosted, it must be in JWT_KEYS and JWT_JWKS.',\n\t\t// JWS wants the raw r||s form, not DER.\n\t\tsign: (data) => sign('sha256', data, { key, dsaEncoding: 'ieee-p1363' })\n\t};\n}\n\n/** Legacy fallback. Stops working once the project revokes its legacy secret. */\nfunction hs256Signer(secret: string): Signer {\n\treturn {\n\t\talg: 'HS256',\n\t\tlabel: 'SUPABASE_JWT_SECRET',\n\t\thint: \"Check it matches the project's legacy JWT secret and that the secret hasn't been revoked.\",\n\t\tsign: (data) => createHmac('sha256', secret).update(data).digest()\n\t};\n}\n","import {\n\tcomposeManifest,\n\tdefineSetting,\n\tresolveConfig,\n\ttype EnvRecord\n} from '@selvajs/platform/config';\n\nexport const SUPABASE_SETTINGS = composeManifest([\n\tdefineSetting({\n\t\tkey: 'SUPABASE_URL',\n\t\tlabel: 'Supabase project',\n\t\ttype: 'url',\n\t\trequired: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'Supabase project URL.',\n\t\timpact: 'Pointing it at another project shows that project’s users and data.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_ANON_KEY',\n\t\tlabel: 'Supabase publishable key',\n\t\ttype: 'string',\n\t\trequired: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tdescription: 'Publishable key (sb_publishable_…).'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_SERVICE_ROLE_KEY',\n\t\tlabel: 'Supabase secret key',\n\t\ttype: 'string',\n\t\trequired: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tdescription: 'Secret key (sb_secret_…). Bypasses row security: server only.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_JWT_SIGNING_KEY',\n\t\tlabel: 'Supabase JWT signing key',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tdescription: 'Private ES256 JWK, one line. Needed for API tokens.',\n\t\timpact: 'Without it, or SUPABASE_JWT_SECRET, API tokens answer 503.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_JWT_SECRET',\n\t\tlabel: 'Supabase JWT secret (legacy)',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tdescription: 'Legacy HS256 JWT secret. Used only without SUPABASE_JWT_SIGNING_KEY.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_ENABLE_SELF_SIGNUP',\n\t\tlabel: 'Self sign-up',\n\t\ttype: 'bool',\n\t\tdefault: false,\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription: 'Allow self-service sign-up at /signup.',\n\t\tlegacy: { bool: 'exact-true' }\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_ALLOW_EMAIL_LINK_SIGNUP',\n\t\tlabel: 'Sign-up by email link',\n\t\ttype: 'bool',\n\t\tdefault: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription: 'A magic link to an unknown address creates an account.',\n\t\tlegacy: { bool: 'not-false' }\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_OAUTH_PROVIDERS',\n\t\tlabel: 'OAuth sign-in buttons',\n\t\ttype: 'list',\n\t\tdefault: [],\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription: 'OAuth buttons on the login page (google, github, azure, gitlab).'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_PUBLIC_BUCKET',\n\t\tlabel: 'Public files bucket',\n\t\ttype: 'string',\n\t\tdefault: 'selva-public',\n\t\tonInvalid: 'fail',\n\t\tclass: 'tunable',\n\t\tdescription: 'Storage bucket for public files.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_PRIVATE_BUCKET',\n\t\tlabel: 'Private files bucket',\n\t\ttype: 'string',\n\t\tdefault: 'selva-private',\n\t\tonInvalid: 'fail',\n\t\tclass: 'tunable',\n\t\tdescription: 'Storage bucket for private files.'\n\t})\n]);\n\n/** Resolve this provider's keys, throwing on the first fail-closed error. */\nexport function resolveSupabaseEnv(env: EnvRecord): Record<string, unknown> {\n\tconst { values, errors } = resolveConfig(SUPABASE_SETTINGS, env);\n\tif (errors.length > 0) {\n\t\tconst e = errors[0];\n\t\tthrow new Error(\n\t\t\te.problem === 'is required' ? `Missing required env var: ${e.key}` : `${e.key} ${e.problem}.`\n\t\t);\n\t}\n\treturn values;\n}\n","import { createClient, type SupabaseClient, type User } from '@supabase/supabase-js';\nimport { NoopLogger, clampPageLimit, type ILogger } from '@selvajs/platform';\nimport { DEFAULT_SCHEMA, type SelvaSchemaClient } from '../data/client.js';\nimport { SupabaseDelegatedSession } from './SupabaseDelegatedSession.js';\nimport { resolveSupabaseEnv } from '../config.js';\nimport type {\n\tIAuthProvider,\n\tIDelegatedSession,\n\tIEmailLinkAuth,\n\tIOAuthAuth,\n\tIPasswordAuth,\n\tISessionRefresh,\n\tAuthUser,\n\tLoginResult,\n\tUserManagementResult,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\n\n/**\n * Auth backed by Supabase Auth (GoTrue). Identity-only — platform permissions\n * live on `IPlatformPermissionStore`, profile state on `IUserProfileStore`.\n */\nexport interface SupabaseAuthProviderConfig {\n\tsupabaseUrl: string;\n\tanonKey: string;\n\tserviceRoleKey: string;\n\t/** Allow self-service signup via `passwordAuth.registerUser`. Default false. */\n\tenableSelfSignup?: boolean;\n\t/**\n\t * OAuth providers enabled in the Supabase dashboard (lowercased: \"google\",\n\t * \"github\", …), surfaced via `oauth.listProviders()`. Default empty.\n\t */\n\toauthProviders?: readonly string[];\n\t/**\n\t * Allow `emailLink.sendMagicLink` to create new users on first request.\n\t * Default true, matching Supabase's `signInWithOtp` default. Set false for\n\t * invite-only deployments; `sendMagicLink` for an unknown email then\n\t * returns `{ ok: false, reason: 'signup_disabled' }`.\n\t */\n\tallowEmailLinkSignup?: boolean;\n\t/**\n\t * How `verifyToken` validates session JWTs — see that method for the\n\t * rationale. `'hybrid'` (default) verifies locally and rechecks GoTrue\n\t * periodically; `'strict'` calls GoTrue on every request.\n\t */\n\ttokenVerification?: 'hybrid' | 'strict';\n\t/** Recheck window for `'hybrid'` verification, in ms. Default 60s. */\n\trevalidateMs?: number;\n\t/**\n\t * Private ES256 JWK the project trusts, for API-token requests. Without it\n\t * (or `jwtSecret`), API tokens are off; sign-in is unaffected.\n\t */\n\tjwtSigningKey?: string;\n\t/** Legacy HS256 secret, used only when `jwtSigningKey` is unset. */\n\tjwtSecret?: string;\n\t/** Lifetime of an API-token request's delegated session; see `SupabaseDelegatedSessionConfig.ttlSeconds`. */\n\tdelegatedSessionTtlSeconds?: number;\n\t/**\n\t * Sink for best-effort failures the provider swallows rather than throwing\n\t * (currently `touchLastLogin`). Defaults to `NoopLogger`. Only identifiers\n\t * are ever logged, never payloads.\n\t */\n\tlogger?: ILogger;\n}\n\nconst DEFAULT_REVALIDATE_MS = 60_000;\n\nexport class SupabaseAuthProvider implements IAuthProvider {\n\treadonly name = 'Supabase Auth';\n\treadonly passwordAuth: IPasswordAuth;\n\treadonly oauth: IOAuthAuth;\n\treadonly emailLink: IEmailLinkAuth;\n\treadonly sessionRefresh: ISessionRefresh;\n\treadonly delegatedSession: IDelegatedSession;\n\n\tprivate readonly admin: SupabaseClient;\n\t/**\n\t * Service-role client pinned to the `selva` schema. `this.admin` stays\n\t * unpinned because it only drives `auth.admin.*` (GoTrue's own REST\n\t * surface, unaffected by the PostgREST schema setting) — any table read\n\t * or write must go through `db` instead.\n\t */\n\tprivate readonly db: SelvaSchemaClient;\n\tprivate readonly anon: SupabaseClient;\n\tprivate readonly anonKey: string;\n\tprivate readonly supabaseUrl: string;\n\tprivate readonly tokenVerification: 'hybrid' | 'strict';\n\tprivate readonly revalidateMs: number;\n\tprivate readonly logger: ILogger;\n\n\t/**\n\t * Last GoTrue recheck per session (epoch ms), keyed by JWT `session_id`.\n\t * Swept lazily in `markRevalidated` so session churn can't leak memory.\n\t * Per-process — multi-instance drift is harmless, each instance rechecks\n\t * on its own schedule.\n\t */\n\tprivate readonly lastRevalidatedAt = new Map<string, number>();\n\t/**\n\t * When this process ended a user's sessions (sign-out, disable, delete), by\n\t * user id. A session last rechecked before that moment is rechecked on its\n\t * next request instead of riding out the window. Other instances still take\n\t * up to `revalidateMs`.\n\t */\n\tprivate readonly sessionsEndedAt = new Map<string, number>();\n\n\tconstructor(config: SupabaseAuthProviderConfig) {\n\t\tthis.supabaseUrl = config.supabaseUrl;\n\t\tthis.anonKey = config.anonKey;\n\t\tthis.tokenVerification = config.tokenVerification ?? 'hybrid';\n\t\tthis.revalidateMs = config.revalidateMs ?? DEFAULT_REVALIDATE_MS;\n\t\tthis.logger = config.logger ?? new NoopLogger();\n\t\tthis.admin = createClient(config.supabaseUrl, config.serviceRoleKey, {\n\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t});\n\t\tthis.db = createClient(config.supabaseUrl, config.serviceRoleKey, {\n\t\t\tdb: { schema: DEFAULT_SCHEMA },\n\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t}) as SelvaSchemaClient;\n\t\tthis.anon = createClient(config.supabaseUrl, config.anonKey, {\n\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t});\n\t\tthis.passwordAuth = new SupabasePasswordAuth(\n\t\t\tthis.admin,\n\t\t\tthis.anon,\n\t\t\t(email, password) => this.signIn(email, password),\n\t\t\tconfig.enableSelfSignup ?? false,\n\t\t\t(user) => this.hydrate(user)\n\t\t);\n\t\tthis.sessionRefresh = new SupabaseSessionRefresh(\n\t\t\tthis.anon,\n\t\t\tthis.admin,\n\t\t\tthis.logger,\n\t\t\t(token) => {\n\t\t\t\tconst userId = unverifiedSubject(token);\n\t\t\t\tif (userId) this.markSessionsEnded(userId);\n\t\t\t}\n\t\t);\n\t\tthis.oauth = new SupabaseOAuthAuth(\n\t\t\tthis.anon,\n\t\t\t(user) => this.hydrate(user),\n\t\t\tconfig.oauthProviders ?? []\n\t\t);\n\t\tthis.emailLink = new SupabaseEmailLinkAuth(\n\t\t\tthis.anon,\n\t\t\t(user) => this.hydrate(user),\n\t\t\tconfig.allowEmailLinkSignup ?? true\n\t\t);\n\t\tthis.delegatedSession = new SupabaseDelegatedSession({\n\t\t\tsupabaseUrl: config.supabaseUrl,\n\t\t\tanonKey: config.anonKey,\n\t\t\t...(config.jwtSigningKey ? { signingKey: config.jwtSigningKey } : {}),\n\t\t\t...(config.jwtSecret ? { jwtSecret: config.jwtSecret } : {}),\n\t\t\t...(config.delegatedSessionTtlSeconds\n\t\t\t\t? { ttlSeconds: config.delegatedSessionTtlSeconds }\n\t\t\t\t: {}),\n\t\t\tlogger: this.logger\n\t\t});\n\t}\n\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tlogger?: ILogger,\n\t\toptions: Pick<SupabaseAuthProviderConfig, 'delegatedSessionTtlSeconds'> = {}\n\t): SupabaseAuthProvider {\n\t\t// Strict parsing: a sign-up control that read anything but \"false\" as on\n\t\t// let `=no` open sign-ups. A bad value now stops boot.\n\t\tconst v = resolveSupabaseEnv(env);\n\t\tconst jwtSigningKey = v.SUPABASE_JWT_SIGNING_KEY as string | undefined;\n\t\tconst jwtSecret = v.SUPABASE_JWT_SECRET as string | undefined;\n\t\treturn new SupabaseAuthProvider({\n\t\t\tsupabaseUrl: v.SUPABASE_URL as string,\n\t\t\tanonKey: v.SUPABASE_ANON_KEY as string,\n\t\t\tserviceRoleKey: v.SUPABASE_SERVICE_ROLE_KEY as string,\n\t\t\tenableSelfSignup: v.SUPABASE_ENABLE_SELF_SIGNUP as boolean,\n\t\t\toauthProviders: (v.SUPABASE_OAUTH_PROVIDERS as string[]).map((p) => p.toLowerCase()),\n\t\t\tallowEmailLinkSignup: v.SUPABASE_ALLOW_EMAIL_LINK_SIGNUP as boolean,\n\t\t\t...(logger ? { logger } : {}),\n\t\t\t...(jwtSigningKey ? { jwtSigningKey } : {}),\n\t\t\t...(jwtSecret ? { jwtSecret } : {}),\n\t\t\t...options\n\t\t});\n\t}\n\n\t/**\n\t * Verify a session JWT and return the user, or null if invalid/disabled.\n\t * Runs on every authenticated request, so the fast path avoids a network\n\t * round-trip.\n\t *\n\t * `'hybrid'` (default): `getClaims(token)` verifies the JWT locally with\n\t * asymmetric signing keys (the modern Supabase default — the SDK checks\n\t * against the cached JWKS via Web Crypto, no GoTrue call). A legacy\n\t * symmetric HS256 token can only be checked by GoTrue, so it gets one\n\t * `getUser` per call, as in `'strict'`. For an asymmetric token, a\n\t * local check can't see a server-side sign-out or `disabled` flip that\n\t * happened after the token was issued — the claims are a snapshot — so we\n\t * also re-check against GoTrue via `getUser`, at most once per\n\t * `revalidateMs` per session, bounding revocation latency to that window\n\t * while skipping the network call on most requests.\n\t *\n\t * `'strict'`: `getUser` on every request. Instant revocation, one round\n\t * trip per request.\n\t */\n\tasync verifyToken(token: string): Promise<AuthUser | null> {\n\t\tif (!token) return null;\n\n\t\t// A symmetric (HS256) token has no local check: `getClaims` would ask GoTrue, and the\n\t\t// recheck would ask again. One `getUser` answers both.\n\t\tif (this.tokenVerification === 'strict' || isSymmetricJwt(token)) {\n\t\t\treturn this.verifyViaGetUser(token);\n\t\t}\n\n\t\tconst claims = await this.getClaimsOrNull(token);\n\t\tif (!claims) return null;\n\t\tif ((claims.app_metadata as { disabled?: boolean } | undefined)?.disabled === true) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst sessionId = typeof claims.session_id === 'string' ? claims.session_id : claims.sub;\n\t\tif (this.shouldRevalidate(sessionId, claims.sub)) {\n\t\t\t// Stamped with the start: a session ended while GoTrue was answering must\n\t\t\t// still read as older than that end.\n\t\t\tconst startedAt = Date.now();\n\t\t\tconst fresh = await this.verifyViaGetUser(token);\n\t\t\tif (!fresh) {\n\t\t\t\tthis.lastRevalidatedAt.delete(sessionId);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthis.markRevalidated(sessionId, startedAt);\n\t\t\treturn fresh;\n\t\t}\n\n\t\treturn {\n\t\t\tid: claims.sub,\n\t\t\temail: typeof claims.email === 'string' ? claims.email : undefined,\n\t\t\tdisabled: false,\n\t\t\tmetadata: claims.user_metadata\n\t\t};\n\t}\n\n\t/** Full network verify against GoTrue. Also the `'strict'`-mode path. */\n\tprivate async verifyViaGetUser(token: string): Promise<AuthUser | null> {\n\t\tconst { data, error } = await this.anon.auth.getUser(token);\n\t\tif (error || !data.user) return null;\n\t\tif (isDisabled(data.user)) return null;\n\t\treturn this.hydrate(data.user);\n\t}\n\n\t/** Local JWT verification. Returns the claims, or null if invalid/expired. */\n\tprivate async getClaimsOrNull(token: string) {\n\t\ttry {\n\t\t\tconst { data, error } = await this.anon.auth.getClaims(token);\n\t\t\tif (error || !data) return null;\n\t\t\treturn data.claims;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate shouldRevalidate(sessionId: string, userId: string): boolean {\n\t\tconst last = this.lastRevalidatedAt.get(sessionId);\n\t\tif (last === undefined || Date.now() - last >= this.revalidateMs) return true;\n\t\tconst ended = this.sessionsEndedAt.get(userId);\n\t\treturn ended !== undefined && last <= ended;\n\t}\n\n\tprivate markSessionsEnded(userId: string): void {\n\t\tconst now = Date.now();\n\t\t// Past one window every session has rechecked on its own schedule.\n\t\tfor (const [id, at] of this.sessionsEndedAt) {\n\t\t\tif (now - at > this.revalidateMs) this.sessionsEndedAt.delete(id);\n\t\t}\n\t\tthis.sessionsEndedAt.set(userId, now);\n\t}\n\n\tprivate markRevalidated(sessionId: string, at: number): void {\n\t\tconst now = Date.now();\n\t\tthis.lastRevalidatedAt.set(sessionId, at);\n\t\t// Lazy sweep so a churn of distinct sessions can't grow the map without\n\t\t// bound. Anything older than two windows is definitely stale (it would\n\t\t// revalidate on next use anyway). Cheap: only runs when the map is large.\n\t\tif (this.lastRevalidatedAt.size > 10_000) {\n\t\t\tconst cutoff = now - this.revalidateMs * 2;\n\t\t\tfor (const [id, ts] of this.lastRevalidatedAt) {\n\t\t\t\tif (ts < cutoff) this.lastRevalidatedAt.delete(id);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getUser(id: string): Promise<AuthUser | null> {\n\t\tconst { data, error } = await this.admin.auth.admin.getUserById(id);\n\t\tif (error || !data.user) return null;\n\t\treturn this.hydrate(data.user);\n\t}\n\n\tasync listUsers(opts?: ListOptions): Promise<Page<AuthUser> | null> {\n\t\t// GoTrue paginates by page number, not offset — translate our cursor. It\n\t\t// accepts any perPage, answers 0 with a 500 and refuses negatives: clamp here.\n\t\tconst perPage = clampPageLimit(opts?.limit);\n\t\tconst requested = opts?.cursor ? parseInt(opts.cursor, 10) : 1;\n\t\tconst page = Number.isFinite(requested) && requested >= 1 ? requested : 1;\n\t\tconst { data, error } = await this.admin.auth.admin.listUsers({ page, perPage });\n\t\tif (error) throw error;\n\n\t\tconst users = data.users;\n\t\tconst hydrated = users.map((u) => this.hydrate(u));\n\t\tconst nextCursor = users.length >= perPage ? String(page + 1) : undefined;\n\t\treturn { items: hydrated, nextCursor };\n\t}\n\n\tasync createUser(email: string): Promise<AuthUser> {\n\t\t// No password — the user signs in via magic link or OAuth.\n\t\tconst { data, error } = await this.admin.auth.admin.createUser({\n\t\t\temail,\n\t\t\temail_confirm: true\n\t\t});\n\t\tif (error) throw error;\n\t\tif (!data.user) throw new Error('createUser returned no user');\n\t\treturn this.hydrate(data.user);\n\t}\n\n\tasync deleteUser(id: string): Promise<UserManagementResult> {\n\t\t// Identity-only: the sole-instance_admin invariant lives on\n\t\t// IPlatformPermissionStore, which callers must consult before this.\n\t\tconst { error } = await this.admin.auth.admin.deleteUser(id);\n\t\tif (error) {\n\t\t\t// GoTrue's 404 shows up as either a status code or a message string.\n\t\t\tconst e = error as unknown as { status?: number; message?: string };\n\t\t\tif (e.status === 404 || /not.?found/i.test(e.message ?? '')) return 'not_found';\n\t\t\tthrow error;\n\t\t}\n\t\tthis.markSessionsEnded(id);\n\t\treturn 'ok';\n\t}\n\n\tasync disableUser(id: string): Promise<UserManagementResult> {\n\t\tconst { data: existing, error: fetchError } = await this.admin.auth.admin.getUserById(id);\n\t\tif (fetchError || !existing.user) return 'not_found';\n\t\t// The ban makes GoTrue refuse sign-in and refresh; the flag goes to app_metadata, which\n\t\t// only the service role writes (a user rewrites their own user_metadata at will).\n\t\tconst { error } = await this.admin.auth.admin.updateUserById(id, {\n\t\t\tban_duration: BAN_FOREVER,\n\t\t\tapp_metadata: { ...(existing.user.app_metadata ?? {}), disabled: true }\n\t\t});\n\t\tif (error) {\n\t\t\tconst e = error as unknown as { status?: number; message?: string };\n\t\t\tif (e.status === 404 || /not.?found/i.test(e.message ?? '')) return 'not_found';\n\t\t\tthrow error;\n\t\t}\n\t\tthis.markSessionsEnded(id);\n\t\treturn 'ok';\n\t}\n\n\tasync touchLastLogin(id: string): Promise<void> {\n\t\t// Debounced in a single UPDATE: the WHERE clause skips the write when the\n\t\t// stamp is recent, so a login storm from one user costs one no-op\n\t\t// round-trip instead of a select + conditional update.\n\t\tconst cutoff = new Date(Date.now() - 60_000).toISOString();\n\t\t// Must use `this.db`, not `this.admin` — `user_profiles` lives in `selva`,\n\t\t// and an unpinned client resolves against `public`, where the table\n\t\t// doesn't exist. That relation-not-found error previously went to an\n\t\t// unchecked await and the stamp silently never landed.\n\t\tconst { error } = await this.db\n\t\t\t.from('user_profiles')\n\t\t\t.update({ last_login_at: new Date().toISOString() })\n\t\t\t.eq('user_id', id)\n\t\t\t.or(`last_login_at.is.null,last_login_at.lt.${cutoff}`);\n\t\t// Never throws — a failed stamp must not block auth — but it's logged\n\t\t// now instead of swallowed, so a regression here doesn't stay invisible.\n\t\tif (error) {\n\t\t\tthis.logger.warn('touchLastLogin failed', {\n\t\t\t\tuserId: id,\n\t\t\t\tcode: error.code,\n\t\t\t\tmessage: error.message\n\t\t\t});\n\t\t}\n\t}\n\n\t// ============================================================================\n\t// Internals\n\t// ============================================================================\n\t/** Kept on the provider class so it can call `hydrate` without plumbing it through. */\n\tprivate async signIn(\n\t\temail: string,\n\t\tpassword: string\n\t): Promise<{ user: AuthUser; sessionToken: string } | null> {\n\t\tconst { data, error } = await this.anon.auth.signInWithPassword({ email, password });\n\t\tif (error || !data.user || !data.session) return null;\n\t\tif (isDisabled(data.user)) return null;\n\t\treturn { user: this.hydrate(data.user), sessionToken: data.session.access_token };\n\t}\n\n\t/** Map a GoTrue `User` to our identity-only `AuthUser`. */\n\tprivate hydrate(user: User): AuthUser {\n\t\treturn {\n\t\t\tid: user.id,\n\t\t\temail: user.email ?? undefined,\n\t\t\tcreatedAt: user.created_at ?? undefined,\n\t\t\tlastLoginAt: user.last_sign_in_at ?? undefined,\n\t\t\tdisabled: isDisabled(user),\n\t\t\tmetadata: user.user_metadata\n\t\t};\n\t}\n\n\t/** Lets other code (storage provider, per-request client factories) build user-scoped clients without a second config read. */\n\tgetAnonClientConfig(): { supabaseUrl: string; anonKey: string } {\n\t\treturn { supabaseUrl: this.supabaseUrl, anonKey: this.anonKey };\n\t}\n}\n\n/** Whether a JWT's header names an HMAC algorithm. Unverified: it only picks the check. */\nfunction isSymmetricJwt(token: string): boolean {\n\ttry {\n\t\tconst header = JSON.parse(Buffer.from(token.split('.')[0] ?? '', 'base64url').toString('utf8'));\n\t\treturn typeof header?.alg === 'string' && header.alg.startsWith('HS');\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nclass SupabasePasswordAuth implements IPasswordAuth {\n\tconstructor(\n\t\tprivate readonly admin: SupabaseClient,\n\t\tprivate readonly anon: SupabaseClient,\n\t\tprivate readonly signIn: (\n\t\t\temail: string,\n\t\t\tpassword: string\n\t\t) => Promise<{ user: AuthUser; sessionToken: string } | null>,\n\t\tprivate readonly enableSelfSignup: boolean,\n\t\tprivate readonly hydrate: (user: User) => AuthUser\n\t) {}\n\n\tasync verifyLogin(email: string, password: string): Promise<LoginResult> {\n\t\tconst result = await this.signIn(email, password);\n\t\tif (!result) return { kind: 'failed', reason: 'invalid_credentials' };\n\t\treturn { kind: 'success', user: result.user, sessionToken: result.sessionToken };\n\t}\n\n\tasync createUserWithPassword(email: string, password: string): Promise<AuthUser> {\n\t\tconst { data, error } = await this.admin.auth.admin.createUser({\n\t\t\temail,\n\t\t\tpassword,\n\t\t\temail_confirm: true\n\t\t});\n\t\tif (error) throw error;\n\t\tif (!data.user) throw new Error('createUserWithPassword returned no user');\n\t\treturn this.hydrate(data.user);\n\t}\n\n\tasync registerUser(email: string, password: string): Promise<AuthUser | null> {\n\t\tif (!this.enableSelfSignup) return null;\n\t\tconst { data, error } = await this.anon.auth.signUp({ email, password });\n\t\tif (error || !data.user) return null;\n\t\treturn this.hydrate(data.user);\n\t}\n}\n\n/**\n * Supabase-backed `IOAuthAuth`. Thin wrapper over GoTrue's `signInWithOAuth`\n * / `exchangeCodeForSession` — mapping failures to null vs throw is the only logic.\n */\nclass SupabaseOAuthAuth implements IOAuthAuth {\n\tconstructor(\n\t\tprivate readonly anon: SupabaseClient,\n\t\tprivate readonly hydrate: (user: User) => AuthUser,\n\t\tprivate readonly providers: readonly string[]\n\t) {}\n\n\tlistProviders(): readonly string[] {\n\t\treturn this.providers;\n\t}\n\n\tasync getOAuthAuthorizationUrl(\n\t\tprovider: 'google' | 'github' | 'azure' | 'gitlab',\n\t\tredirectTo: string\n\t): Promise<string> {\n\t\tconst { data, error } = await this.anon.auth.signInWithOAuth({\n\t\t\tprovider,\n\t\t\toptions: { redirectTo, skipBrowserRedirect: true }\n\t\t});\n\t\tif (error || !data.url) throw error ?? new Error('signInWithOAuth returned no URL');\n\t\treturn data.url;\n\t}\n\n\tasync exchangeOAuthCode(code: string): Promise<{\n\t\tuser: AuthUser;\n\t\tsessionToken: string;\n\t\trefreshToken: string;\n\t} | null> {\n\t\tconst { data, error } = await this.anon.auth.exchangeCodeForSession(code);\n\t\tif (error || !data.user || !data.session) return null;\n\t\tif (isDisabled(data.user)) return null;\n\t\treturn {\n\t\t\tuser: this.hydrate(data.user),\n\t\t\tsessionToken: data.session.access_token,\n\t\t\trefreshToken: data.session.refresh_token\n\t\t};\n\t}\n}\n\nconst BAN_FOREVER = '876000h';\n\n/** Disabled by an admin: flagged in app_metadata or banned. Never `user_metadata`, which the user writes. */\nfunction isDisabled(user: Pick<User, 'app_metadata' | 'banned_until'>): boolean {\n\tif (user.app_metadata?.disabled === true) return true;\n\treturn user.banned_until ? Date.parse(user.banned_until) > Date.now() : false;\n}\n\n/** The `sub` of a JWT, unverified: only ever used to force a recheck, never to trust. */\nfunction unverifiedSubject(token: string): string | null {\n\ttry {\n\t\tconst payload = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString());\n\t\treturn typeof payload?.sub === 'string' ? payload.sub : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Supabase-backed `ISessionRefresh`. `refreshSession` uses the anon client —\n * a refresh token authenticates itself. `revokeSession` uses the service-role\n * client — revoking someone else's session is privileged.\n */\nclass SupabaseSessionRefresh implements ISessionRefresh {\n\tconstructor(\n\t\tprivate readonly anon: SupabaseClient,\n\t\tprivate readonly admin: SupabaseClient,\n\t\tprivate readonly logger: ILogger,\n\t\tprivate readonly onRevoked: (token: string) => void\n\t) {}\n\n\tasync refreshSession(refreshToken: string): Promise<{\n\t\tsessionToken: string;\n\t\trefreshToken: string;\n\t} | null> {\n\t\tconst { data, error } = await this.anon.auth.refreshSession({ refresh_token: refreshToken });\n\t\tif (error || !data.session) return null;\n\t\t// Refresh runs after verifyToken has already failed, so it's the last gate\n\t\t// on an expired-access-token request. Without this check, a disabled user\n\t\t// could mint fresh access tokens forever — verifyToken's revalidateMs\n\t\t// bound never gets a chance to apply. GoTrue returns the user alongside\n\t\t// the session, so the check is free.\n\t\tif (data.user !== null && isDisabled(data.user)) return null;\n\t\treturn {\n\t\t\tsessionToken: data.session.access_token,\n\t\t\trefreshToken: data.session.refresh_token\n\t\t};\n\t}\n\n\tasync revokeSession(token: string): Promise<boolean> {\n\t\t// 'global': sign out every session for this user, not just the one this\n\t\t// JWT names. Logout on a shared machine shouldn't leave a sibling session\n\t\t// alive, and a token that reached us at all may already be leaked.\n\t\tconst { error } = await this.admin.auth.admin.signOut(token, 'global');\n\t\t// Whatever GoTrue answered, this process stops trusting its last recheck.\n\t\tthis.onRevoked(token);\n\t\tif (!error) return true;\n\t\t// A token GoTrue no longer recognizes (already signed out, expired,\n\t\t// malformed) is the desired end state, not a failure — report success so\n\t\t// the caller doesn't log noise on every double-logout.\n\t\tconst e = error as unknown as { status?: number; message?: string };\n\t\tif (e.status === 401 || e.status === 403 || e.status === 404) return true;\n\t\t// Anything else (5xx, network, misconfigured service-role key) means the\n\t\t// session may still be live. Never throw — a failed revoke must not\n\t\t// block the user from logging out.\n\t\tthis.logger.warn('revokeSession failed', { status: e.status, message: e.message });\n\t\treturn false;\n\t}\n}\n\n/**\n * Supabase-backed `IEmailLinkAuth`. Wraps GoTrue's `signInWithOtp` (send)\n * and `verifyOtp` (verify on click).\n *\n * Supabase emails the user `{callbackUrl}?token_hash=…&type=…`. The `type`\n * param picks which OTP variant `verifyOtp` runs (signup vs returning-user\n * magic link vs invite acceptance), so we pass it through unchanged.\n */\nclass SupabaseEmailLinkAuth implements IEmailLinkAuth {\n\tconstructor(\n\t\tprivate readonly anon: SupabaseClient,\n\t\tprivate readonly hydrate: (user: User) => AuthUser,\n\t\tprivate readonly allowSignup: boolean\n\t) {}\n\n\tasync sendMagicLink(\n\t\temail: string,\n\t\tcallbackUrl: string\n\t): Promise<\n\t\t{ ok: true } | { ok: false; reason: 'rate_limited' | 'signup_disabled' | 'invalid_email' }\n\t> {\n\t\tconst { error } = await this.anon.auth.signInWithOtp({\n\t\t\temail,\n\t\t\toptions: {\n\t\t\t\temailRedirectTo: callbackUrl,\n\t\t\t\tshouldCreateUser: this.allowSignup\n\t\t\t}\n\t\t});\n\t\tif (!error) return { ok: true };\n\n\t\t// Anything we don't recognize, throw — the route returns 500 with a\n\t\t// stack trace instead of us swallowing a real bug as \"rate limited\".\n\t\tconst status = (error as { status?: number }).status;\n\t\tconst code = (error as { code?: string }).code;\n\t\tconst message = error.message ?? '';\n\t\tif (status === 429 || /rate.?limit/i.test(message))\n\t\t\treturn { ok: false, reason: 'rate_limited' };\n\t\tif (\n\t\t\tcode === 'otp_disabled' ||\n\t\t\tcode === 'signup_disabled' ||\n\t\t\t/signup.*disabled/i.test(message)\n\t\t) {\n\t\t\treturn { ok: false, reason: 'signup_disabled' };\n\t\t}\n\t\tif (code === 'validation_failed' || /invalid.*email|email.*invalid/i.test(message)) {\n\t\t\treturn { ok: false, reason: 'invalid_email' };\n\t\t}\n\t\tthrow error;\n\t}\n\n\tasync verifyMagicLink(rawCallbackUrl: string): Promise<{\n\t\tuser: AuthUser;\n\t\tsessionToken: string;\n\t\trefreshToken?: string;\n\t} | null> {\n\t\tconst params = parseCallbackParams(rawCallbackUrl);\n\t\tif (!params) return null;\n\t\tconst { tokenHash, type } = params;\n\n\t\tconst { data, error } = await this.anon.auth.verifyOtp({\n\t\t\ttoken_hash: tokenHash,\n\t\t\ttype\n\t\t});\n\t\tif (error || !data.user || !data.session) return null;\n\t\tif (isDisabled(data.user)) return null;\n\t\treturn {\n\t\t\tuser: this.hydrate(data.user),\n\t\t\tsessionToken: data.session.access_token,\n\t\t\trefreshToken: data.session.refresh_token\n\t\t};\n\t}\n}\n\n/**\n * Pull `token_hash` + `type` from either a full callback URL or a bare\n * `token_hash=…&type=…` query string. Tolerant of both shapes so the route\n * layer can pass whichever form is convenient.\n *\n * Returns null when the inputs aren't recognizable — the caller treats null\n * as \"send the user back to /login\".\n */\nfunction parseCallbackParams(\n\traw: string\n): { tokenHash: string; type: 'magiclink' | 'email' | 'signup' | 'invite' | 'recovery' } | null {\n\tlet search: URLSearchParams;\n\ttry {\n\t\tsearch = new URL(raw).searchParams;\n\t} catch {\n\t\tsearch = new URLSearchParams(raw.startsWith('?') ? raw.slice(1) : raw);\n\t}\n\tconst tokenHash = search.get('token_hash');\n\tconst type = search.get('type');\n\tif (!tokenHash) return null;\n\tconst allowed = new Set(['magiclink', 'email', 'signup', 'invite', 'recovery']);\n\tif (!type || !allowed.has(type)) return null;\n\treturn {\n\t\ttokenHash,\n\t\ttype: type as 'magiclink' | 'email' | 'signup' | 'invite' | 'recovery'\n\t};\n}\n","import { randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { ProviderError } from '@selvajs/platform';\n\n/**\n * Allowlist row. Identity-only — per-user app state (permissions, profile,\n * starred definitions) lives in `user-data.json` owned by whatever data\n * provider is paired with this auth provider.\n *\n * The UPN is the lookup key the upstream proxy will send back on every\n * subsequent request. `email` and `displayName` start empty when an admin\n * pre-allowlists; they get filled in on the user's first visit from the\n * matching headers (one-time materialization).\n */\nexport interface AllowlistEntry {\n\tid: string;\n\t/** User Principal Name — case-folded for storage and lookup. */\n\tupn: string;\n\temail?: string;\n\tdisplayName?: string;\n\tcreatedAt: string;\n\tlastLoginAt?: string;\n\tdisabled?: boolean;\n\t/**\n\t * The proxy UPN that last signed in to this row, case-folded. Only that UPN\n\t * gets in through the email fallback; a UPN equal to `upn` always gets in and\n\t * takes the claim. Unset on a row nobody has signed in to yet, and on rows from\n\t * before the field existed: their next sign-in sets it.\n\t */\n\tclaimedByUpn?: string;\n}\n\ninterface AllowlistFile {\n\tusers: AllowlistEntry[];\n}\n\nconst empty = (): AllowlistFile => ({ users: [] });\n\nconst LAST_LOGIN_DEBOUNCE_MS = 60_000;\n\nasync function readFile(filePath: string): Promise<AllowlistFile> {\n\ttry {\n\t\tconst raw = await fs.readFile(filePath, 'utf-8');\n\t\treturn JSON.parse(raw) as AllowlistFile;\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === 'ENOENT') return empty();\n\t\tthrow err;\n\t}\n}\n\nasync function writeFile(filePath: string, data: AllowlistFile): Promise<void> {\n\tawait fs.mkdir(path.dirname(filePath), { recursive: true });\n\tconst tmp = `${filePath}.tmp`;\n\tawait fs.writeFile(tmp, JSON.stringify(data, null, '\\t'), 'utf-8');\n\tawait fs.rename(tmp, filePath);\n}\n\nexport interface AllowlistStore {\n\tfindByUpn(upn: string): Promise<AllowlistEntry | null>;\n\t/**\n\t * Look up by email rather than UPN. Used as a fallback on first login when\n\t * the proxy forwards a UPN that differs from the email an admin used to\n\t * pre-allowlist the user (common on Entra: UPN `x@tenant.onmicrosoft.com`\n\t * vs mail `x@company.com`). Without this, the UPN miss orphans the\n\t * org-member row that was keyed to the allowlist UUID at provision time.\n\t */\n\tfindByEmail(email: string): Promise<AllowlistEntry | null>;\n\tfindById(id: string): Promise<AllowlistEntry | null>;\n\tlistUsers(): Promise<AllowlistEntry[]>;\n\tcreateUser(upn: string): Promise<AllowlistEntry>;\n\t/**\n\t * Mirror identity fields from upstream-proxy headers. The proxy/IdP is the\n\t * source of truth for email and display name: a stored value is replaced\n\t * whenever the forwarded header differs, so IdP-side renames — and fixes to\n\t * a misconfigured proxy that used to forward the wrong claim (e.g. the OIDC\n\t * `sub` as display name) — heal the row on the user's next visit. An absent\n\t * header leaves the stored value untouched; hand-edits to these two fields\n\t * in the allowlist JSON do not survive the user's next login.\n\t */\n\tsyncFromHeaders(id: string, fields: { email?: string; displayName?: string }): Promise<void>;\n\t/**\n\t * Record `upn` as the row's claimant if it has none, or over the current one\n\t * with `replace`, and return the claimant now stored (null for a missing row).\n\t * Concurrent first sign-ins resolve to whichever wrote first.\n\t */\n\tclaim(id: string, upn: string, opts?: { replace?: boolean }): Promise<string | null>;\n\t/**\n\t * Repoint a row's UPN and claimant — for an operator correcting an allowlist\n\t * entry after a directory-side rename. No-ops if the new UPN already belongs\n\t * to a different row (a collision means manual operator cleanup — never\n\t * silently merge). Never called from `identifyFromHeaders`: headers don't\n\t * get to rewrite a claimed identity.\n\t */\n\trebindUpn(id: string, upn: string): Promise<void>;\n\tsetDisabled(id: string, disabled: boolean): Promise<void>;\n\ttouchLastLogin(id: string): Promise<void>;\n\tdeleteUser(id: string): Promise<void>;\n}\n\nexport function createAllowlistStore(filePath: string): AllowlistStore {\n\tconst norm = (upn: string) => upn.trim().toLowerCase();\n\n\t// Every writer rewrites the whole file through one temp name, so two at once lose\n\t// an entry or fail the rename with ENOENT.\n\tlet queue: Promise<unknown> = Promise.resolve();\n\tfunction locked<T>(fn: () => Promise<T>): Promise<T> {\n\t\tconst next = queue.then(fn, fn);\n\t\tqueue = next.catch(() => {});\n\t\treturn next;\n\t}\n\n\treturn {\n\t\tasync findByUpn(upn) {\n\t\t\tconst { users } = await readFile(filePath);\n\t\t\tconst key = norm(upn);\n\t\t\treturn users.find((u) => u.upn === key) ?? null;\n\t\t},\n\n\t\tasync findByEmail(email) {\n\t\t\tconst { users } = await readFile(filePath);\n\t\t\tconst key = norm(email);\n\t\t\t// Admins pre-allowlist via `createUser(email)`, which stores the email\n\t\t\t// AS the upn. The `email` column is not searched: proxy headers write\n\t\t\t// it, so it would hand a reassigned address to the departed holder.\n\t\t\treturn users.find((u) => u.upn === key) ?? null;\n\t\t},\n\n\t\tasync findById(id) {\n\t\t\tconst { users } = await readFile(filePath);\n\t\t\treturn users.find((u) => u.id === id) ?? null;\n\t\t},\n\n\t\tasync listUsers() {\n\t\t\tconst { users } = await readFile(filePath);\n\t\t\treturn users;\n\t\t},\n\n\t\tcreateUser(upn) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst key = norm(upn);\n\t\t\t\tif (file.users.some((u) => u.upn === key)) {\n\t\t\t\t\tthrow new ProviderError(`User with UPN \"${upn}\" already exists`, 409);\n\t\t\t\t}\n\t\t\t\tconst entry: AllowlistEntry = {\n\t\t\t\t\tid: randomUUID(),\n\t\t\t\t\tupn: key,\n\t\t\t\t\tcreatedAt: new Date().toISOString()\n\t\t\t\t};\n\t\t\t\tfile.users.push(entry);\n\t\t\t\tawait writeFile(filePath, file);\n\t\t\t\treturn entry;\n\t\t\t});\n\t\t},\n\n\t\tsyncFromHeaders(id, fields) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\t\tif (!user) return;\n\t\t\t\tlet dirty = false;\n\t\t\t\tif (fields.email && user.email !== fields.email) {\n\t\t\t\t\tuser.email = fields.email;\n\t\t\t\t\tdirty = true;\n\t\t\t\t}\n\t\t\t\tif (fields.displayName && user.displayName !== fields.displayName) {\n\t\t\t\t\tuser.displayName = fields.displayName;\n\t\t\t\t\tdirty = true;\n\t\t\t\t}\n\t\t\t\tif (dirty) await writeFile(filePath, file);\n\t\t\t});\n\t\t},\n\n\t\tclaim(id, upn, opts) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\t\tif (!user) return null;\n\t\t\t\tconst key = norm(upn);\n\t\t\t\tif (!user.claimedByUpn || (opts?.replace && user.claimedByUpn !== key)) {\n\t\t\t\t\tuser.claimedByUpn = key;\n\t\t\t\t\tawait writeFile(filePath, file);\n\t\t\t\t}\n\t\t\t\treturn user.claimedByUpn;\n\t\t\t});\n\t\t},\n\n\t\trebindUpn(id, upn) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst key = norm(upn);\n\t\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\t\tif (!user || (user.upn === key && user.claimedByUpn === key)) return;\n\t\t\t\t// Don't merge into an existing row — a UPN collision is an operator\n\t\t\t\t// data issue, not something to paper over by reassigning identity.\n\t\t\t\tif (file.users.some((u) => u.id !== id && u.upn === key)) return;\n\t\t\t\tuser.upn = key;\n\t\t\t\tuser.claimedByUpn = key;\n\t\t\t\tawait writeFile(filePath, file);\n\t\t\t});\n\t\t},\n\n\t\tsetDisabled(id, disabled) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\t\tif (!user) throw new ProviderError(`User \"${id}\" not found`, 404);\n\t\t\t\tuser.disabled = disabled;\n\t\t\t\tawait writeFile(filePath, file);\n\t\t\t});\n\t\t},\n\n\t\ttouchLastLogin(id) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\t\tif (!user) return;\n\t\t\t\tconst now = Date.now();\n\t\t\t\tif (user.lastLoginAt) {\n\t\t\t\t\tconst prev = Date.parse(user.lastLoginAt);\n\t\t\t\t\tif (Number.isFinite(prev) && now - prev < LAST_LOGIN_DEBOUNCE_MS) return;\n\t\t\t\t}\n\t\t\t\tuser.lastLoginAt = new Date(now).toISOString();\n\t\t\t\tawait writeFile(filePath, file);\n\t\t\t});\n\t\t},\n\n\t\tdeleteUser(id) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst before = file.users.length;\n\t\t\t\tfile.users = file.users.filter((u) => u.id !== id);\n\t\t\t\tif (file.users.length === before) throw new ProviderError(`User \"${id}\" not found`, 404);\n\t\t\t\tawait writeFile(filePath, file);\n\t\t\t});\n\t\t}\n\t};\n}\n","import * as path from 'node:path';\nimport type {\n\tIAuthProvider,\n\tIProxyAuth,\n\tAuthUser,\n\tUserManagementResult,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport {\n\tNoopLogger,\n\tProviderError,\n\tclampPageLimit,\n\tdecodeOffsetCursor,\n\tencodeOffsetCursor,\n\ttype ILogger\n} from '@selvajs/platform';\nimport { createAllowlistStore } from './users.js';\nimport type { AllowlistStore, AllowlistEntry } from './users.js';\n\n// ============================================================================\n// HeaderAuthProvider — forward-auth via trusted upstream proxy\n// ============================================================================\n//\n// ⚠ TRUST BOUNDARY ⚠\n//\n// This provider trusts the headers it reads from incoming requests. That is\n// only safe when the deployment guarantees:\n//\n// 1. A reverse proxy (Caddy `forward_auth`, oauth2-proxy, Authelia, …) is\n// the ONLY network path to the app process. Bind to 127.0.0.1 or\n// firewall the port.\n// 2. The proxy authenticates against the upstream IdP before forwarding.\n// 3. The proxy STRIPS any client-supplied copies of the trusted headers\n// from inbound requests before adding its own.\n//\n// If any of those fails, anyone on the network can spoof the headers and\n// become anyone. The working Caddy config is in\n// docs/self-hosting/providers/header-auth-entra.md; the curl-based self-test\n// is in README.md.\n//\n// One of the three is partly self-detecting: a proxy that doesn't strip (3)\n// leaves two values in the UPN header, which `identifyFromHeaders` refuses\n// with a warning naming the cause. Nothing detects a breach of (1) — a\n// request reaching the process directly carries one clean header and is\n// indistinguishable from a proxied one. Closing that needs a shared secret\n// between proxy and app, deliberately not added: it is a second control over\n// the same failure, and an operator who misconfigured header stripping is no\n// likelier to have configured a secret correctly. Network isolation is the\n// control; the deployment IS the security boundary.\n// ============================================================================\n\ninterface HeaderNames {\n\tupn: string;\n\temail: string;\n\tdisplayName: string;\n}\n\nconst DEFAULT_HEADERS: HeaderNames = {\n\tupn: 'SELVA-UserPrincipalName',\n\temail: 'SELVA-Email',\n\tdisplayName: 'SELVA-DisplayName'\n};\n\n/**\n * Decides whether an unrecognized UPN coming through the proxy should be\n * auto-allowlisted as the bootstrap admin. Returning `true` lets the provider\n * create the allowlist row on the fly; returning `false` keeps the strict\n * \"must be pre-allowlisted\" behavior. The caller is responsible for narrowing\n * this to first-run + matching-email so the deployment can't be hijacked\n * after the initial setup.\n *\n * Pure: no I/O inside the callback. The hook layer that wires it up checks\n * `hasInstanceAdmin` and `BOOTSTRAP_INSTANCE_ADMIN_EMAIL` itself.\n */\nexport type BootstrapAllowlistPolicy = (params: {\n\tupn: string;\n\temail: string | undefined;\n}) => boolean | Promise<boolean>;\n\nexport interface HeaderAuthProviderConfig {\n\t/** Absolute path to the allowlist JSON file (e.g. `/data/header-allowlist.json`). */\n\tallowlistFilePath: string;\n\t/**\n\t * Header names the proxy sets. Defaults match the Caddyfile in\n\t * docs/self-hosting/providers/header-auth-entra.md\n\t * (`SELVA-UserPrincipalName`, `SELVA-Email`, `SELVA-DisplayName`). Override\n\t * to match a different proxy (e.g. oauth2-proxy sends the UPN as\n\t * `X-Auth-Request-Preferred-Username`; its `X-Auth-Request-User` is the OIDC `sub`).\n\t */\n\theaders?: Partial<HeaderNames>;\n\t/**\n\t * Optional bootstrap policy. When set AND the policy returns true for an\n\t * unrecognized UPN, the provider auto-allowlists that UPN before completing\n\t * identification. Used to break the chicken-and-egg on fresh deployments\n\t * where no admin exists yet. The caller must scope this tightly — see\n\t * `BootstrapAllowlistPolicy`.\n\t */\n\tbootstrapAllowlistPolicy?: BootstrapAllowlistPolicy;\n\t/**\n\t * Structured logger for proxy-misconfiguration diagnostics. Optional; defaults\n\t * to `NoopLogger` so this library stays silent unless the app wires one in.\n\t */\n\tlogger?: ILogger;\n}\n\nfunction toAuthUser(u: AllowlistEntry): AuthUser {\n\treturn {\n\t\tid: u.id,\n\t\t// Pre-first-login rows have no materialized email yet — the UPN is what\n\t\t// the admin typed when allowlisting (their email, for Entra/M365) and is\n\t\t// the only human-readable identifier available. Fall back so user lists\n\t\t// show an address instead of a bare UUID until the real email arrives\n\t\t// via header materialization.\n\t\temail: u.email ?? u.upn,\n\t\tmetadata: { upn: u.upn, displayName: u.displayName },\n\t\tcreatedAt: u.createdAt,\n\t\tlastLoginAt: u.lastLoginAt,\n\t\tdisabled: u.disabled\n\t};\n}\n\nclass HeaderProxyAuth implements IProxyAuth {\n\tprivate bootstrapPolicy: BootstrapAllowlistPolicy | undefined;\n\t// One-shot diagnostic flag. Flipped the first time we see a request that\n\t// carries none of the configured SELVA-* headers, so deploys with a\n\t// misconfigured proxy get a single loud warning in the logs without\n\t// spamming on every anonymous request. Reset is intentional — the\n\t// process restarts and you see the warning again next deploy.\n\tprivate missingHeadersWarned = false;\n\n\t// Same one-shot treatment for the opposite misconfiguration: identity\n\t// headers arriving more than once per request.\n\tprivate duplicateUpnWarned = false;\n\tprivate duplicateEmailWarned = false;\n\tprivate claimWriteWarned = false;\n\n\tconstructor(\n\t\tprivate readonly users: AllowlistStore,\n\t\tprivate readonly headers: HeaderNames,\n\t\tbootstrapPolicy: BootstrapAllowlistPolicy | undefined,\n\t\tprivate readonly logger: ILogger = new NoopLogger()\n\t) {\n\t\tthis.bootstrapPolicy = bootstrapPolicy;\n\t}\n\n\tsetBootstrapPolicy(policy: BootstrapAllowlistPolicy | null): void {\n\t\tthis.bootstrapPolicy = policy ?? undefined;\n\t}\n\n\t/**\n\t * Names of the configured identity headers, in priority order. Exposed so\n\t * the hook layer can emit per-page diagnostics (\"you hit /login without\n\t * these headers\") without having to know provider internals.\n\t */\n\tget configuredHeaderNames(): readonly string[] {\n\t\treturn [this.headers.upn, this.headers.email, this.headers.displayName];\n\t}\n\n\t/** True iff none of the configured identity headers are present. */\n\thasNoIdentityHeaders(headers: Headers): boolean {\n\t\treturn (\n\t\t\t!headers.get(this.headers.upn) &&\n\t\t\t!headers.get(this.headers.email) &&\n\t\t\t!headers.get(this.headers.displayName)\n\t\t);\n\t}\n\n\t/**\n\t * The email header, or undefined when it carries more than one value. Email\n\t * can select a row through the fallback, so a joined value (a proxy appending\n\t * its copy to the client's) is the same spoofing signal as on the UPN.\n\t */\n\tprivate singleValuedEmail(headers: Headers): string | undefined {\n\t\tconst email = headers.get(this.headers.email)?.trim() || undefined;\n\t\tif (!email?.includes(',')) return email;\n\t\tif (!this.duplicateEmailWarned) {\n\t\t\tthis.duplicateEmailWarned = true;\n\t\t\tthis.logger.warn(\n\t\t\t\t'Multiple values arrived in the email identity header on one request. The ' +\n\t\t\t\t\t'forward-auth proxy is not stripping client-supplied copies of the trusted ' +\n\t\t\t\t\t'headers. Ignoring the email header. Strip the configured headers at site ' +\n\t\t\t\t\t'scope, above forward_auth — see the @selvajs/header-auth-provider README.',\n\t\t\t\t{ component: 'HeaderAuth', header: this.headers.email }\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Claims the row, or returns null when the allowlist can't be written. A failed\n\t * claim must not fail the sign-in: that would lock every unclaimed user out of\n\t * a deployment whose allowlist is read-only or has the wrong owner. The row\n\t * then stays unclaimed, and the email fallback still admits any UPN to it.\n\t */\n\tprivate async tryClaim(id: string, upn: string, replace: boolean): Promise<string | null> {\n\t\ttry {\n\t\t\treturn await this.users.claim(id, upn, { replace });\n\t\t} catch (err) {\n\t\t\tif (!this.claimWriteWarned) {\n\t\t\t\tthis.claimWriteWarned = true;\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t'Could not record which UPN signed in to an allowlisted user: the allowlist ' +\n\t\t\t\t\t\t'file is not writable. Sign-in continues, but until it is writable the email ' +\n\t\t\t\t\t\t'header can still select any user whose UPN is an address.',\n\t\t\t\t\t{ component: 'HeaderAuth', userId: id, code: (err as NodeJS.ErrnoException).code }\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tasync identifyFromHeaders(headers: Headers): Promise<AuthUser | null> {\n\t\tconst upn = headers.get(this.headers.upn);\n\t\tif (!upn || !upn.trim()) {\n\t\t\t// Distinguish \"proxy never touched this request\" (no SELVA-* headers\n\t\t\t// at all → forward-auth misconfigured or being bypassed) from \"proxy\n\t\t\t// is here but didn't populate UPN\" (one of the other SELVA-* headers\n\t\t\t// arrived). The first case is the silent-failure mode operators\n\t\t\t// struggle to diagnose, so we log it once per process.\n\t\t\tif (!this.missingHeadersWarned && this.hasNoIdentityHeaders(headers)) {\n\t\t\t\tthis.missingHeadersWarned = true;\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t'No identity headers received on the first non-authed request. ' +\n\t\t\t\t\t\t'If you reach the app through your forward-auth proxy, this means the proxy is not ' +\n\t\t\t\t\t\t'forwarding the configured headers — check your forward_auth / copy_headers config. ' +\n\t\t\t\t\t\t\"If you're hitting the app directly (bypassing the proxy), bind the process to \" +\n\t\t\t\t\t\t'127.0.0.1 and only reach it through the proxy. See @selvajs/header-auth-provider README',\n\t\t\t\t\t{\n\t\t\t\t\t\tcomponent: 'HeaderAuth',\n\t\t\t\t\t\texpectedHeaders: [this.headers.upn, this.headers.email, this.headers.displayName]\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\t// A UPN header carrying more than one value means the proxy is not\n\t\t// stripping client-supplied copies before adding its own: `Headers.get`\n\t\t// joins repeats with \", \", so a spoofing attempt arrives as\n\t\t// \"attacker@x.com, real@y.com\". A UPN is a single directory identifier\n\t\t// and never contains a comma, so this can only be the duplicate case.\n\t\t//\n\t\t// The lookup below would miss anyway — no allowlisted UPN has a comma —\n\t\t// so refusing here changes no outcome. What it adds is a named cause in\n\t\t// the logs for a failure that otherwise looks like \"user not\n\t\t// allowlisted\", which is what makes this misconfiguration so hard to\n\t\t// diagnose. Checked on the UPN only: display names legitimately contain\n\t\t// commas (\"Doe, Jane\" is standard Entra formatting).\n\t\tif (upn.includes(',')) {\n\t\t\tif (!this.duplicateUpnWarned) {\n\t\t\t\tthis.duplicateUpnWarned = true;\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t'Multiple values arrived in the UPN identity header on one request. The ' +\n\t\t\t\t\t\t'forward-auth proxy is not stripping client-supplied copies of the trusted ' +\n\t\t\t\t\t\t'headers before setting its own, so a visitor can submit their own identity ' +\n\t\t\t\t\t\t'alongside the real one. Refusing to identify. Strip the configured headers at ' +\n\t\t\t\t\t\t'site scope, above forward_auth — see the @selvajs/header-auth-provider README.',\n\t\t\t\t\t{ component: 'HeaderAuth', header: this.headers.upn }\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\tconst email = this.singleValuedEmail(headers);\n\t\tconst displayName = headers.get(this.headers.displayName)?.trim() || undefined;\n\n\t\tlet entry = await this.users.findByUpn(upn);\n\t\tlet matchedByUpn = entry !== null;\n\n\t\t// Fallback: the proxy's UPN didn't match, but an admin may have\n\t\t// pre-allowlisted this person by EMAIL (Entra UPN ≠ mail is common).\n\t\t// Adopt that row so the org membership + permissions provisioned\n\t\t// against its UUID survive. The claim check below keeps this to the\n\t\t// UPN that claimed the row.\n\t\tif (!entry && email) {\n\t\t\tconst byEmail = await this.users.findByEmail(email);\n\t\t\tif (byEmail) entry = byEmail;\n\t\t}\n\n\t\t// Bootstrap path: when there's no allowlist row yet AND a bootstrap\n\t\t// policy is configured AND it green-lights this UPN, create the row.\n\t\t// The policy owner (the hook layer) is responsible for restricting\n\t\t// this to first-run + matching-email so the deployment can't be\n\t\t// hijacked once admin exists.\n\t\tif (!entry && this.bootstrapPolicy) {\n\t\t\tconst allowed = await this.bootstrapPolicy({ upn, email });\n\t\t\tif (allowed) {\n\t\t\t\ttry {\n\t\t\t\t\tentry = await this.users.createUser(upn);\n\t\t\t\t} catch {\n\t\t\t\t\t// Race: another concurrent request beat us to it. Re-read.\n\t\t\t\t\tentry = await this.users.findByUpn(upn);\n\t\t\t\t}\n\t\t\t\tmatchedByUpn = entry !== null;\n\t\t\t}\n\t\t}\n\n\t\tif (!entry || entry.disabled) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// A sign-in claims its row for its UPN, and the email fallback admits only\n\t\t// that UPN. Without this, the fallback would hand any row whose UPN is an\n\t\t// address (most of them, on Entra) to whoever presents that address in the\n\t\t// email header. A UPN equal to the row's own is the identity the operator\n\t\t// allowlisted, so it always gets in and takes the claim: that keeps a UPN\n\t\t// cleanup working, and evicts anyone who claimed the row with a spoofed email.\n\t\tconst presented = upn.trim().toLowerCase();\n\t\tlet claimant = entry.claimedByUpn;\n\t\tif (!claimant || (matchedByUpn && claimant !== presented)) {\n\t\t\tclaimant = (await this.tryClaim(entry.id, upn, matchedByUpn)) ?? undefined;\n\t\t}\n\t\t// Logged on every refusal, not once: each names a different locked-out user\n\t\t// or a probe of the email fallback, and the operator needs to see which.\n\t\tif (claimant && claimant !== presented) {\n\t\t\tthis.logger.warn(\n\t\t\t\t'Refused a sign-in to an allowlisted user already claimed by a different UPN. ' +\n\t\t\t\t\t\"If that user's UPN changed in the directory, set upn on their row in the \" +\n\t\t\t\t\t'allowlist file to the new one; their next sign-in claims it.',\n\t\t\t\t{ component: 'HeaderAuth', userId: entry.id }\n\t\t\t);\n\t\t\treturn null;\n\t\t}\n\n\t\t// Mirror email / display-name from the proxy whenever they drift. The\n\t\t// IdP is the source of truth, so IdP renames and corrected proxy\n\t\t// header mappings propagate on the next visit instead of the first\n\t\t// materialized value sticking forever.\n\t\tif ((email && entry.email !== email) || (displayName && entry.displayName !== displayName)) {\n\t\t\tawait this.users.syncFromHeaders(entry.id, { email, displayName }).catch(() => {});\n\t\t\tif (email) entry.email = email;\n\t\t\tif (displayName) entry.displayName = displayName;\n\t\t}\n\n\t\tawait this.users.touchLastLogin(entry.id).catch(() => {});\n\t\treturn toAuthUser(entry);\n\t}\n}\n\nexport class HeaderAuthProvider implements IAuthProvider {\n\tprivate readonly users: AllowlistStore;\n\tprivate readonly headers: HeaderNames;\n\n\treadonly name = 'Header (Forward Auth)';\n\treadonly proxyAuth: IProxyAuth;\n\n\tconstructor(config: HeaderAuthProviderConfig) {\n\t\tthis.users = createAllowlistStore(config.allowlistFilePath);\n\t\tthis.headers = { ...DEFAULT_HEADERS, ...config.headers };\n\t\tthis.proxyAuth = new HeaderProxyAuth(\n\t\t\tthis.users,\n\t\t\tthis.headers,\n\t\t\tconfig.bootstrapAllowlistPolicy,\n\t\t\tconfig.logger ?? new NoopLogger()\n\t\t);\n\t}\n\n\t/**\n\t * Late-bind a bootstrap-allowlist policy. Useful when the policy needs\n\t * runtime state the platform layer owns (e.g. `hasInstanceAdmin`) and\n\t * therefore can't be wired up at provider construction time. Pass `null`\n\t * to clear.\n\t */\n\tsetBootstrapAllowlistPolicy(policy: BootstrapAllowlistPolicy | null): void {\n\t\t(this.proxyAuth as HeaderProxyAuth).setBootstrapPolicy(policy);\n\t}\n\n\tstatic fromEnv(env: Record<string, string | undefined>, logger?: ILogger): HeaderAuthProvider {\n\t\tconst dir = env.HEADER_AUTH_DATA_DIR ?? env.DATA_PATH;\n\t\tif (!dir) {\n\t\t\tthrow new Error(\n\t\t\t\t'Missing required env var: HEADER_AUTH_DATA_DIR (or DATA_PATH as fallback). ' +\n\t\t\t\t\t'This directory holds header-allowlist.json — the pre-provisioned UPN list.'\n\t\t\t);\n\t\t}\n\t\treturn new HeaderAuthProvider({\n\t\t\tallowlistFilePath: path.join(dir, 'header-allowlist.json'),\n\t\t\theaders: {\n\t\t\t\tupn: env.HEADER_AUTH_UPN_HEADER ?? DEFAULT_HEADERS.upn,\n\t\t\t\temail: env.HEADER_AUTH_EMAIL_HEADER ?? DEFAULT_HEADERS.email,\n\t\t\t\tdisplayName: env.HEADER_AUTH_DISPLAY_NAME_HEADER ?? DEFAULT_HEADERS.displayName\n\t\t\t},\n\t\t\tlogger\n\t\t});\n\t}\n\n\t/**\n\t * No tokens are issued by this provider — identity rides on every request\n\t * via the trusted-proxy headers. Always returns null; the hook layer\n\t * falls through to `proxyAuth.identifyFromHeaders`.\n\t */\n\tasync verifyToken(_token: string): Promise<AuthUser | null> {\n\t\treturn null;\n\t}\n\n\tasync getUser(id: string): Promise<AuthUser | null> {\n\t\tconst u = await this.users.findById(id);\n\t\treturn u ? toAuthUser(u) : null;\n\t}\n\n\tasync listUsers(opts?: ListOptions): Promise<Page<AuthUser> | null> {\n\t\tconst all = await this.users.listUsers();\n\t\tconst limit = clampPageLimit(opts?.limit);\n\t\tconst offset = decodeOffsetCursor(opts?.cursor);\n\t\tconst slice = all.slice(offset, offset + limit).map(toAuthUser);\n\t\tconst nextOffset = offset + slice.length;\n\t\treturn {\n\t\t\titems: slice,\n\t\t\tnextCursor: nextOffset < all.length ? encodeOffsetCursor(nextOffset) : undefined\n\t\t};\n\t}\n\n\t/**\n\t * Allowlist a UPN. Admin POST `/api/admin/users` with `{ email }`; the\n\t * email IS the UPN for M365 / Entra deployments where they match. For\n\t * other IdPs, document the UPN format in your README/onboarding.\n\t */\n\tasync createUser(upn: string): Promise<AuthUser> {\n\t\treturn toAuthUser(await this.users.createUser(upn));\n\t}\n\n\tasync deleteUser(id: string): Promise<UserManagementResult> {\n\t\tconst target = await this.users.findById(id);\n\t\tif (!target) return 'not_found';\n\t\ttry {\n\t\t\tawait this.users.deleteUser(id);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync disableUser(id: string): Promise<UserManagementResult> {\n\t\tconst target = await this.users.findById(id);\n\t\tif (!target) return 'not_found';\n\t\ttry {\n\t\t\tawait this.users.setDisabled(id, true);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync touchLastLogin(id: string): Promise<void> {\n\t\tawait this.users.touchLastLogin(id);\n\t}\n}\n","import { randomUUID } from 'node:crypto';\nimport type {\n\tIDataProvider,\n\tIStorageProvider,\n\tRequestContext,\n\tDefinitionRecord,\n\tDefinitionFileExt,\n\tDefinitionVersion,\n\tDocumentInventory,\n\tUpdateMetadataInput,\n\tUISchema\n} from '@selvajs/platform';\nimport { summarizeInventory } from '@selvajs/schemas';\nimport {\n\tProviderError,\n\tdefinitionPaths,\n\ttoSourceDocumentId,\n\twithCacheBust\n} from '@selvajs/platform';\n\nconst inventoryFields = (inventory: DocumentInventory | null | undefined) =>\n\tinventory ? { inventory, inventorySummary: summarizeInventory(inventory) } : {};\n\n/**\n * Not the HTTP body — that's `CreateDefinitionInputSchema` in\n * `@selvajs/platform/definitions`, which has no guid/ownerId because those are\n * derived server-side.\n */\nexport interface CreateDefinitionRecord {\n\tguid: string;\n\tprojectId: string;\n\townerId: string;\n\tfileExt: DefinitionFileExt;\n\toriginalFilename?: string;\n\tdisplayName: string;\n\tdescription?: string;\n\tcategory?: string;\n\ttags?: string[];\n\tcoverImage?: string;\n\tcomputeServerId?: string;\n}\n\n/**\n * Orchestrates writes spanning IDataProvider + IStorageProvider. Application\n * orchestration, not platform contract — hence not in @selvajs/platform.\n *\n * Methods that write both metadata and blobs order the two so a mid-flight\n * failure leaves a state the API can still serve; those reasons sit inline at\n * each write. `publish` and `updateMeta` flip pointers/metadata only and touch\n * storage not at all.\n */\nexport class DefinitionService {\n\tconstructor(\n\t\tprivate data: IDataProvider,\n\t\tprivate storage: IStorageProvider\n\t) {}\n\n\tasync create(\n\t\tctx: RequestContext,\n\t\tinput: CreateDefinitionRecord,\n\t\tfile: Uint8Array,\n\t\tschema: UISchema,\n\t\tinventory?: DocumentInventory | null\n\t): Promise<{ record: DefinitionRecord; version: DefinitionVersion }> {\n\t\tconst now = new Date().toISOString();\n\t\tconst actor = ctx.userId || input.ownerId;\n\t\tconst record: DefinitionRecord = {\n\t\t\tguid: input.guid,\n\t\t\tprojectId: input.projectId,\n\t\t\townerId: input.ownerId,\n\t\t\tcreatedBy: actor,\n\t\t\tupdatedBy: actor,\n\t\t\tdisplayName: input.displayName,\n\t\t\tdescription: input.description,\n\t\t\tcategory: input.category,\n\t\t\ttags: input.tags,\n\t\t\tcoverImage: input.coverImage,\n\t\t\tcomputeServerId: input.computeServerId,\n\t\t\tstatus: 'pending',\n\t\t\tsolveCount: 0,\n\t\t\t// v1 is created below with versionNumber 1, so the next upload reserves 2.\n\t\t\tnextVersionNumber: 2,\n\t\t\tliveVersionId: null,\n\t\t\tdraftVersionId: null,\n\t\t\tsourceDocumentId: toSourceDocumentId(schema.documentId) ?? undefined,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t};\n\n\t\t// Metadata first — if this fails there's nothing to clean up.\n\t\tawait this.data.definitions.create(ctx, record);\n\n\t\t// If the blob write fails, the record stays 'pending' and is hidden from\n\t\t// default list queries.\n\t\tconst versionId = randomUUID();\n\t\tconst fileKey = definitionPaths.version(input.guid, 1, input.fileExt);\n\t\tawait this.storage.put(fileKey, file, 'application/octet-stream');\n\n\t\tconst version: DefinitionVersion = {\n\t\t\tid: versionId,\n\t\t\tdefinitionId: input.guid,\n\t\t\tversionNumber: 1,\n\t\t\tfileExt: input.fileExt,\n\t\t\tfileKey,\n\t\t\toriginalFilename: input.originalFilename,\n\t\t\tuploadedBy: actor,\n\t\t\tuploadedAt: now,\n\t\t\tschema,\n\t\t\tschemaExtractedAt: now,\n\t\t\t...inventoryFields(inventory)\n\t\t};\n\t\tawait this.data.definitions.createVersion(ctx, version);\n\n\t\t// Points both channels at v1 and flips status='draft' in ONE store\n\t\t// operation. Doing it as three writes leaves a partial state on failure:\n\t\t// status='draft' with null pointers, or 'pending' with pointers set.\n\t\tawait this.data.definitions.attachInitialVersion(ctx, input.guid, versionId);\n\n\t\treturn {\n\t\t\trecord: { ...record, status: 'draft', liveVersionId: versionId, draftVersionId: versionId },\n\t\t\tversion\n\t\t};\n\t}\n\n\t/**\n\t * Advances the draft pointer only — `live` is unchanged. Use `publish` to\n\t * promote.\n\t */\n\tasync uploadVersion(\n\t\tctx: RequestContext,\n\t\tguid: string,\n\t\tfile: Uint8Array,\n\t\text: DefinitionFileExt,\n\t\toriginalName: string,\n\t\tschema: UISchema,\n\t\tchangeNote?: string,\n\t\tinventory?: DocumentInventory | null\n\t): Promise<DefinitionVersion> {\n\t\tconst existing = await this.data.definitions.get(ctx, guid);\n\t\tif (!existing) throw new ProviderError(`Definition not found: ${guid}`, 404);\n\n\t\t// Monotonic counter, NOT max(existing)+1 — the latter reuses a number after\n\t\t// delete-latest and collides the `fileKey`, serving a stale blob for new\n\t\t// content.\n\t\tconst next = await this.data.definitions.reserveNextVersionNumber(ctx, guid);\n\n\t\tconst versionId = randomUUID();\n\t\tconst fileKey = definitionPaths.version(guid, next, ext);\n\t\tawait this.storage.put(fileKey, file, 'application/octet-stream');\n\n\t\tconst now = new Date().toISOString();\n\t\tconst actor = ctx.userId || existing.ownerId;\n\t\tconst version: DefinitionVersion = {\n\t\t\tid: versionId,\n\t\t\tdefinitionId: guid,\n\t\t\tversionNumber: next,\n\t\t\tfileExt: ext,\n\t\t\tfileKey,\n\t\t\toriginalFilename: originalName,\n\t\t\tuploadedBy: actor,\n\t\t\tuploadedAt: now,\n\t\t\tchangeNote: changeNote?.trim() || undefined,\n\t\t\tschema,\n\t\t\tschemaExtractedAt: now,\n\t\t\t...inventoryFields(inventory)\n\t\t};\n\t\tawait this.data.definitions.createVersion(ctx, version);\n\t\tawait this.data.definitions.setDraftVersion(ctx, guid, versionId);\n\t\t// A schema without a GUID leaves the old one: it says nothing about which file this is.\n\t\tconst sourceDocumentId = toSourceDocumentId(schema.documentId);\n\t\tif (sourceDocumentId && sourceDocumentId !== existing.sourceDocumentId) {\n\t\t\tawait this.data.definitions.update(ctx, guid, { sourceDocumentId });\n\t\t}\n\n\t\treturn version;\n\t}\n\n\t/**\n\t * Moves the live channel to `versionId`, or to the current draft if omitted.\n\t * Any version id is accepted, so this rolls backward as well as forward.\n\t */\n\tasync publish(ctx: RequestContext, guid: string, versionId?: string): Promise<DefinitionVersion> {\n\t\tconst existing = await this.data.definitions.get(ctx, guid);\n\t\tif (!existing) throw new ProviderError(`Definition not found: ${guid}`, 404);\n\n\t\tconst target = versionId ?? existing.draftVersionId;\n\t\tif (!target) throw new ProviderError('No version to publish', 400);\n\n\t\tconst version = await this.data.definitions.getVersion(ctx, target);\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tthrow new ProviderError(`Version '${target}' not found for this definition`, 404);\n\t\t}\n\n\t\tawait this.data.definitions.setLiveVersion(ctx, guid, target);\n\t\t// Flip status to 'published' the first time live moves off pending/draft.\n\t\tif (existing.status === 'draft' || existing.status === 'pending') {\n\t\t\tawait this.data.definitions.update(ctx, guid, { status: 'published' });\n\t\t}\n\t\treturn version;\n\t}\n\n\tasync deleteVersion(ctx: RequestContext, guid: string, versionId: string): Promise<void> {\n\t\tconst version = await this.data.definitions.getVersion(ctx, versionId);\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tthrow new ProviderError(`Version '${versionId}' not found for this definition`, 404);\n\t\t}\n\t\t// Store enforces the live/draft reference check; if it throws, blob stays.\n\t\tawait this.data.definitions.deleteVersion(ctx, versionId);\n\t\tawait this.storage.delete(version.fileKey);\n\t}\n\n\tasync updateMeta(ctx: RequestContext, guid: string, patch: UpdateMetadataInput): Promise<void> {\n\t\tawait this.data.definitions.update(ctx, guid, patch);\n\t}\n\n\tasync saveCoverImage(ctx: RequestContext, guid: string, imageData: Uint8Array): Promise<string> {\n\t\tconst path = definitionPaths.image(guid);\n\t\tawait this.storage.put(path, imageData, 'image/webp');\n\t\t// Same path every time, so a new cover needs a new URL or caches keep the old one.\n\t\tconst url = withCacheBust(this.storage.getPublicUrl(path), Date.now());\n\t\tawait this.data.definitions.update(ctx, guid, { coverImage: url });\n\t\treturn url;\n\t}\n\n\tasync delete(ctx: RequestContext, guid: string): Promise<void> {\n\t\t// Metadata is soft-deleted (audit trail, restorable by clearing\n\t\t// `deleted_at`); blobs are HARD-deleted.\n\t\t//\n\t\t// Metadata first, so the API hides the record immediately. A failed blob\n\t\t// wipe then leaves orphan storage that no reader can reach, for a\n\t\t// retention sweep to collect. The reverse order leaves the record alive\n\t\t// with its blobs gone — a 404 for any in-flight reader.\n\t\tawait this.data.definitions.delete(ctx, guid);\n\t\tawait this.storage.deletePrefix(definitionPaths.prefix(guid));\n\t}\n}\n","import { createHash } from 'node:crypto';\nimport type { IOrgStore, IStorageProvider, OrgAssetKind, RequestContext } from '@selvajs/platform';\nimport { orgPaths, ProviderError, withCacheBust } from '@selvajs/platform';\n\n/**\n * Orchestrates org-asset writes that span IStorageProvider + IOrgStore — one\n * service for every asset kind (logo, favicon, …).\n *\n * Every upload is rasterized to WebP by the shared transcoder inside\n * `IStorageProvider.put`, so the stored blob is always\n * `orgs/{id}/branding/{kind}.webp` (the `branding/` segment marks the public\n * asset class — see `classifyAssetPath`). SVG inputs are flattened to a raster\n * of at most 1200px — no vector blob is persisted, which keeps the served bytes\n * XSS-free without a sanitizer. Re-uploads overwrite in place. The org's\n * `assets` map is the source of truth for which kinds exist and their public\n * URLs; we read-merge-write it so concurrent edits to *different* kinds don't\n * clobber each other within a kind.\n *\n * Re-uploads overwrite the same path, so the stored URL would be identical\n * across replaces and a cached browser/CDN would keep serving the old bytes.\n * The content-derived `?v=` token (`withCacheBust`) gives a *different* image a\n * *different* URL, while an identical re-upload keeps its URL and stays cached.\n */\nexport class OrgAssetService {\n\tconstructor(\n\t\tprivate orgs: IOrgStore,\n\t\tprivate storage: IStorageProvider\n\t) {}\n\n\t/**\n\t * Store `kind`'s blob and point the org's `assets[kind]` at its public URL.\n\t * `contentType` must be the *original* upload type (e.g. `image/svg+xml`) so\n\t * the transcoder recognizes the bytes as an image. Returns the public URL.\n\t */\n\tasync saveAsset(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tkind: OrgAssetKind,\n\t\tdata: Uint8Array,\n\t\tcontentType: string\n\t): Promise<string> {\n\t\tconst path = orgPaths.asset(orgId, kind);\n\t\tawait this.storage.put(path, data, contentType);\n\t\t// Content-derived token, not a timestamp: an identical re-upload to the\n\t\t// same path keeps the same URL and stays cached; a changed image gets a\n\t\t// new URL and refetches immediately. 8 hex chars is enough to distinguish\n\t\t// versions without bloating the URL.\n\t\tconst token = createHash('sha256').update(data).digest('hex').slice(0, 8);\n\t\tconst url = withCacheBust(this.storage.getPublicUrl(path), token);\n\t\tawait this.orgs.updateOrg(ctx, orgId, {\n\t\t\tassets: await this.mergedAssets(ctx, orgId, kind, url)\n\t\t});\n\t\treturn url;\n\t}\n\n\t/** Remove `kind`'s blob and drop it from the org's `assets` map. No-op-safe. */\n\tasync removeAsset(ctx: RequestContext, orgId: string, kind: OrgAssetKind): Promise<void> {\n\t\tawait this.storage.delete(orgPaths.asset(orgId, kind));\n\t\tawait this.orgs.updateOrg(ctx, orgId, {\n\t\t\tassets: await this.mergedAssets(ctx, orgId, kind, undefined)\n\t\t});\n\t}\n\n\t/**\n\t * Read the org's current `assets` and return a copy with `kind` set to `url`\n\t * (or removed when `url` is undefined). Keeps the other kinds intact.\n\t */\n\tprivate async mergedAssets(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tkind: OrgAssetKind,\n\t\turl: string | undefined\n\t): Promise<Record<string, string>> {\n\t\tconst org = await this.orgs.getOrg(ctx, orgId);\n\t\tif (!org) throw new ProviderError(`Org '${orgId}' not found`, 404);\n\t\tconst next = { ...(org.assets ?? {}) } as Record<string, string>;\n\t\tif (url === undefined) delete next[kind];\n\t\telse next[kind] = url;\n\t\treturn next;\n\t}\n}\n","/**\n * What an error tracker may receive: identifiers, never payloads. Applied to Sentry-shaped\n * events (`beforeSend`, `beforeSendTransaction`, `beforeBreadcrumb`) without importing Sentry,\n * so a host wires them into whichever SDK it runs, server or browser.\n *\n * No cookie, auth header, API key, request body or query string leaves: a query carries share\n * tokens and search text, a body definitions and inputs. A user is its id. Console breadcrumbs\n * stay local, since they can quote any of the above.\n */\n\n/** The parts of a Sentry event these read. Structural, so any SDK version's events fit. */\nexport interface ScrubbableEvent {\n\trequest?: {\n\t\turl?: string;\n\t\tcookies?: unknown;\n\t\tdata?: unknown;\n\t\tquery_string?: unknown;\n\t\theaders?: Record<string, string>;\n\t};\n\tuser?: { id?: string | number } & Record<string, unknown>;\n\tbreadcrumbs?: ScrubbableBreadcrumb[];\n\ttransaction?: string;\n\tspans?: { description?: string; data?: Record<string, unknown> }[];\n}\n\nexport interface ScrubbableBreadcrumb {\n\tcategory?: string;\n\tdata?: Record<string, unknown>;\n}\n\n// Headers that say what the request was, never who sent it.\nconst KEPT_HEADERS = new Set(['accept', 'content-type', 'content-length', 'user-agent']);\nconst URL_KEYS = ['url', 'to', 'from', 'http.url', 'server.address.full'];\n\n/** `https://h/p?q=1#f` → `https://h/p`; a relative path likewise. Anything else as it was. */\nexport function withoutQuery(url: string): string {\n\tconst cut = url.search(/[?#]/);\n\treturn cut === -1 ? url : url.slice(0, cut);\n}\n\nfunction scrubData(data: Record<string, unknown> | undefined): void {\n\tif (!data) return;\n\tfor (const key of URL_KEYS) {\n\t\tconst value = data[key];\n\t\tif (typeof value === 'string') data[key] = withoutQuery(value);\n\t}\n\tdelete data['http.query'];\n\tdelete data['http.fragment'];\n}\n\nexport function scrubBreadcrumb<B extends ScrubbableBreadcrumb>(crumb: B): B | null {\n\tif (crumb.category === 'console') return null;\n\tscrubData(crumb.data);\n\treturn crumb;\n}\n\n/** For `beforeSend` and `beforeSendTransaction` alike. Mutates and returns `event`. */\nexport function scrubEvent<E extends ScrubbableEvent>(event: E): E {\n\tconst request = event.request;\n\tif (request) {\n\t\tdelete request.cookies;\n\t\tdelete request.data;\n\t\tdelete request.query_string;\n\t\tif (request.url) request.url = withoutQuery(request.url);\n\t\tif (request.headers) {\n\t\t\trequest.headers = Object.fromEntries(\n\t\t\t\tObject.entries(request.headers).filter(([k]) => KEPT_HEADERS.has(k.toLowerCase()))\n\t\t\t);\n\t\t}\n\t}\n\tif (event.user) event.user = event.user.id === undefined ? {} : { id: event.user.id };\n\tif (event.breadcrumbs) {\n\t\tevent.breadcrumbs = event.breadcrumbs.flatMap((b) => scrubBreadcrumb(b) ?? []);\n\t}\n\tfor (const span of event.spans ?? []) {\n\t\tif (span.description) span.description = withoutQuery(span.description);\n\t\tscrubData(span.data);\n\t}\n\tif (event.transaction) event.transaction = withoutQuery(event.transaction);\n\treturn event;\n}\n\n/** A sample-rate env value → 0–1; unset or unreadable is 0, out of range clamped. */\nexport function sampleRate(raw: string | undefined): number {\n\tconst rate = Number(raw);\n\treturn raw !== undefined && Number.isFinite(rate) ? Math.min(1, Math.max(0, rate)) : 0;\n}\n","import type { ErrorContext, IErrorReporter } from '@selvajs/platform';\nimport { sampleRate, scrubBreadcrumb, scrubEvent } from './scrub.js';\n\n/**\n * `IErrorReporter` backed by Sentry. `@sentry/node` is an OPTIONAL peer dependency: a\n * deployment without a DSN never loads it, so the surface below is narrowed to the calls used\n * here and the import stays dynamic — a static one would make the package mandatory.\n *\n * A host that already runs a Sentry SDK (a framework one that also traces requests) hands it\n * to `fromClient` instead, so Sentry is initialized once.\n */\nexport interface SentryLike {\n\tcaptureException(\n\t\terror: unknown,\n\t\tcontext?: {\n\t\t\ttags?: Record<string, string>;\n\t\t\tuser?: { id?: string };\n\t\t\tlevel?: 'fatal' | 'error' | 'warning';\n\t\t\tfingerprint?: string[];\n\t\t}\n\t): unknown;\n}\n\ninterface SentryNodeLike extends SentryLike {\n\tinit(options: {\n\t\tdsn: string;\n\t\tenvironment?: string;\n\t\trelease?: string;\n\t\ttracesSampleRate: number;\n\t\ttraceLifecycle?: 'static' | 'stream';\n\t\tbeforeSend: typeof scrubEvent;\n\t\tbeforeSendTransaction: typeof scrubEvent;\n\t\tbeforeBreadcrumb: typeof scrubBreadcrumb;\n\t}): void;\n}\n\nexport class SentryErrorReporter implements IErrorReporter {\n\tprivate constructor(private readonly sentry: SentryLike) {}\n\n\t/** A reporter over an SDK the host initialized itself; it should pass `scrub.ts`'s hooks. */\n\tstatic fromClient(sentry: SentryLike): SentryErrorReporter {\n\t\treturn new SentryErrorReporter(sentry);\n\t}\n\n\t/**\n\t * Initialize `@sentry/node` with the scrubbing hooks and return a reporter, or `null` when\n\t * it won't load. Never throws — a broken error-tracker must not take down boot.\n\t */\n\tstatic async create(opts: {\n\t\tdsn: string;\n\t\tenvironment?: string;\n\t\trelease?: string;\n\t\t/** `SENTRY_TRACES_SAMPLE_RATE` as read from env; unset is 0, error tracking only. */\n\t\ttracesSampleRate?: string | number;\n\t}): Promise<SentryErrorReporter | null> {\n\t\ttry {\n\t\t\t// `@vite-ignore` stops the bundler resolving an absent package at build\n\t\t\t// time. `@ts-ignore` rather than `@ts-expect-error` because the module\n\t\t\t// is a real dep in some installs and missing in others, so we can't\n\t\t\t// assert the error is always there for `expect-error` to consume.\n\t\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t\t// @ts-ignore -- optional dependency, may be absent at type-check time\n\t\t\tconst sentry = (await import(/* @vite-ignore */ '@sentry/node')) as unknown as SentryNodeLike;\n\t\t\tsentry.init({\n\t\t\t\tdsn: opts.dsn,\n\t\t\t\tenvironment: opts.environment,\n\t\t\t\trelease: opts.release,\n\t\t\t\ttracesSampleRate:\n\t\t\t\t\ttypeof opts.tracesSampleRate === 'number'\n\t\t\t\t\t\t? sampleRate(String(opts.tracesSampleRate))\n\t\t\t\t\t\t: sampleRate(opts.tracesSampleRate),\n\t\t\t\t// Streamed spans skip beforeSendTransaction, so the scrubber would never see them.\n\t\t\t\ttraceLifecycle: 'static',\n\t\t\t\tbeforeSend: scrubEvent,\n\t\t\t\tbeforeSendTransaction: scrubEvent,\n\t\t\t\tbeforeBreadcrumb: scrubBreadcrumb\n\t\t\t});\n\t\t\treturn new SentryErrorReporter(sentry);\n\t\t} catch (err) {\n\t\t\tconsole.error(\n\t\t\t\t'[ErrorReporter] A Sentry DSN is set but @sentry/node could not be loaded. ' +\n\t\t\t\t\t'Install it (`pnpm add @sentry/node`) or unset the DSN. Falling back to no-op.',\n\t\t\t\terr\n\t\t\t);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tcapture(error: unknown, context?: ErrorContext): void {\n\t\ttry {\n\t\t\tconst tags: Record<string, string> = { ...context?.tags };\n\t\t\tif (context?.method) tags.method = context.method;\n\t\t\tif (context?.route) tags.route = context.route;\n\t\t\tif (context?.orgId) tags.orgId = context.orgId;\n\t\t\tif (context?.kind) tags.kind = context.kind;\n\t\t\tthis.sentry.captureException(error, {\n\t\t\t\ttags,\n\t\t\t\tuser: context?.userId ? { id: context.userId } : undefined,\n\t\t\t\t...(context?.level && { level: context.level }),\n\t\t\t\t// One issue per fault kind, split as Sentry would split it by stack.\n\t\t\t\t...(context?.kind && { fingerprint: ['{{ default }}', context.kind] })\n\t\t\t});\n\t\t} catch (err) {\n\t\t\t// Best-effort, and this sits on the error path — letting a second\n\t\t\t// failure escape would mask the first.\n\t\t\tconsole.error('[ErrorReporter] Failed to capture error:', err);\n\t\t}\n\t}\n}\n","import { readBool } from '../compute/limits.js';\n\nexport interface SmtpConfig {\n\thost: string;\n\tport: number;\n\tsecure: boolean;\n\tauth?: { user: string; pass: string };\n\tfrom: string;\n}\n\n/** The env vars this provider reads. The app passes `process.env` or its framework equivalent. */\nexport interface SmtpEnv {\n\tSMTP_HOST?: string;\n\tSMTP_PORT?: string;\n\tSMTP_USER?: string;\n\tSMTP_PASS?: string;\n\tSMTP_FROM?: string;\n\tSMTP_SECURE?: string;\n\t// Callers hand over a whole env bag (`process.env`, `$env/dynamic/private`),\n\t// which carries far more than these keys. Without this, an env bag typed as a\n\t// bare index signature has no declared property in common with an all-optional\n\t// interface, and TS's weak-type check rejects it at every call site.\n\t[key: string]: string | undefined;\n}\n\nfunction parsePort(raw: string | undefined): number {\n\tconst n = Number(raw ?? 587);\n\treturn Number.isInteger(n) && n > 0 && n < 65536 ? n : 587;\n}\n\n/**\n * Read SMTP settings from an env bag. Taken as a parameter rather than read\n * from `process.env` directly: under `vite dev` the framework does not mirror\n * `.env` into `process.env`, so the app must hand over its own resolved env\n * (`$env/dynamic/private` in SvelteKit) or overrides silently fall back to\n * defaults.\n *\n * Returns null when mail is not configured — the caller treats that as \"no\n * mail\", not as an error.\n *\n * Throws only when `SMTP_HOST` is set but `SMTP_FROM` is missing: that\n * combination is a half-finished config, and failing loudly beats silently\n * never sending. Every message needs an envelope sender, and guessing one\n * produces mail that fails SPF at the recipient.\n */\nexport function readSmtpConfig(env: SmtpEnv): SmtpConfig | null {\n\tconst host = env.SMTP_HOST?.trim();\n\tif (!host) return null;\n\n\tconst from = env.SMTP_FROM?.trim();\n\tif (!from) {\n\t\tthrow new Error('SMTP_HOST is set but SMTP_FROM is missing — mail needs a sender address.');\n\t}\n\n\tconst port = parsePort(env.SMTP_PORT);\n\tconst user = env.SMTP_USER?.trim();\n\tconst pass = env.SMTP_PASS;\n\n\treturn {\n\t\thost,\n\t\tport,\n\t\t// Port 465 is implicit TLS; 587 and 25 start plaintext and upgrade via\n\t\t// STARTTLS, which nodemailer does on its own when `secure` is false. Parsed\n\t\t// with the manifest's boolean words, so what `selva config show` reports runs.\n\t\tsecure: readBool({ SMTP_SECURE: env.SMTP_SECURE }, 'SMTP_SECURE', port === 465),\n\t\tauth: user && pass ? { user, pass } : undefined,\n\t\tfrom\n\t};\n}\n","import { createHmac, randomBytes } from 'node:crypto';\nimport {\n\tNoopLogger,\n\ttype ILogger,\n\ttype INotificationProvider,\n\ttype OutboundMessage,\n\ttype SendResult\n} from '@selvajs/platform';\nimport { readSmtpConfig, type SmtpEnv } from './smtp-config.js';\n\n// Per process: the hash only has to match up within one run of the logs.\nconst RECIPIENT_HASH_KEY = randomBytes(32);\n\nfunction recipientHash(to: string): string {\n\treturn createHmac('sha256', RECIPIENT_HASH_KEY).update(to).digest('hex').slice(0, 16);\n}\n\n/**\n * SMTP transport. Any server works — a transactional provider, an internal\n * relay, or a mailbox with an app password.\n *\n * Settings are read per send rather than cached, so a restart is the only\n * thing needed to reconfigure and a rotated password takes effect without\n * anyone remembering there is a cache.\n */\nexport class SmtpNotificationProvider implements INotificationProvider {\n\treadonly name = 'SMTP';\n\n\tconstructor(private readonly env: SmtpEnv) {}\n\n\tasync send(message: OutboundMessage, log: ILogger = new NoopLogger()): Promise<SendResult> {\n\t\tlet config;\n\t\ttry {\n\t\t\tconfig = readSmtpConfig(this.env);\n\t\t} catch (err) {\n\t\t\tlog.error('SMTP is misconfigured', {\n\t\t\t\tcomponent: 'SmtpNotificationProvider',\n\t\t\t\terror: err instanceof Error ? err.message : String(err)\n\t\t\t});\n\t\t\treturn { status: 'failed', reason: 'misconfigured' };\n\t\t}\n\t\tif (!config) return { status: 'not-configured' };\n\n\t\ttry {\n\t\t\t// Lazy: an instance with no SMTP_HOST never pays to load nodemailer.\n\t\t\tconst { createTransport } = await import('nodemailer');\n\t\t\tconst transport = createTransport({\n\t\t\t\thost: config.host,\n\t\t\t\tport: config.port,\n\t\t\t\tsecure: config.secure,\n\t\t\t\tauth: config.auth\n\t\t\t});\n\n\t\t\tawait transport.sendMail({\n\t\t\t\tfrom: config.from,\n\t\t\t\tto: message.to,\n\t\t\t\tsubject: message.subject,\n\t\t\t\ttext: message.text,\n\t\t\t\thtml: message.html\n\t\t\t});\n\t\t\treturn { status: 'sent' };\n\t\t} catch (err) {\n\t\t\t// Never the raw message: an SMTP rejection quotes the address, and erasure\n\t\t\t// can't reach stdout. The keyed hash still matches up failures to one person.\n\t\t\tconst { code, responseCode } = err as { code?: string; responseCode?: number };\n\t\t\tlog.warn('Failed to send mail', {\n\t\t\t\tcomponent: 'SmtpNotificationProvider',\n\t\t\t\trecipient: recipientHash(message.to),\n\t\t\t\tkind: message.kind,\n\t\t\t\tcode,\n\t\t\t\tresponseCode\n\t\t\t});\n\t\t\treturn { status: 'failed', reason: code ?? 'send-failed' };\n\t\t}\n\t}\n\n\tisConfigured(): boolean {\n\t\ttry {\n\t\t\treturn readSmtpConfig(this.env) !== null;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n}\n","import { composeManifest, defineSetting } from '@selvajs/platform/config';\n\nconst header = (key: string, fallback: string, slot: string) =>\n\tdefineSetting({\n\t\tkey,\n\t\tlabel: `${slot[0].toUpperCase()}${slot.slice(1)} header`,\n\t\ttype: 'string',\n\t\tdefault: fallback,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: `Header the proxy puts the user's ${slot} in.`,\n\t\timpact: 'A name the proxy never sends signs nobody in. Override all three or none.'\n\t});\n\nexport const HEADER_AUTH_SETTINGS = composeManifest([\n\tdefineSetting({\n\t\tkey: 'HEADER_AUTH_DATA_DIR',\n\t\tlabel: 'Allowlist folder',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'Directory holding header-allowlist.json. Falls back to DATA_PATH.'\n\t}),\n\theader('HEADER_AUTH_UPN_HEADER', 'SELVA-UserPrincipalName', 'UPN'),\n\theader('HEADER_AUTH_EMAIL_HEADER', 'SELVA-Email', 'email'),\n\theader('HEADER_AUTH_DISPLAY_NAME_HEADER', 'SELVA-DisplayName', 'display name')\n]);\n","import { composeManifest, defineSetting } from '@selvajs/platform/config';\n\nexport const LOCAL_SETTINGS = composeManifest([\n\tdefineSetting({\n\t\tkey: 'DATA_PATH',\n\t\tlabel: 'Data folder',\n\t\ttype: 'string',\n\t\trequired: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'Folder on this server holding users, orgs, projects and uploads. Back it up.',\n\t\timpact: 'Pointing it elsewhere starts an empty instance; the old data stays where it was.'\n\t})\n]);\n","import {\n\tbuildConfigReport,\n\tcomposeManifest,\n\tpreviousKey,\n\treadSetting,\n\ttype KeyRotation,\n\tdefineSetting,\n\ttakeSnapshot,\n\ttype ConfigReport,\n\ttype ConfigSnapshot,\n\ttype EnvRecord,\n\ttype Manifest\n} from '@selvajs/platform/config';\nimport { ENGINE_SETTINGS } from '@selvajs/server/config';\nimport { HEADER_AUTH_SETTINGS } from '@selvajs/header-auth-provider/config';\nimport { LOCAL_SETTINGS } from '@selvajs/local-provider/config';\nimport { SUPABASE_SETTINGS } from '@selvajs/supabase-provider/config';\n\nconst COMPUTE_DEBUG = defineSetting({\n\tkey: 'SELVA_FLAG_COMPUTE_DEBUG',\n\tlabel: 'Compute debug logging',\n\ttype: 'string',\n\tdefault: 'off',\n\tonInvalid: 'default',\n\tclass: 'setting',\n\tdescription:\n\t\t'off, on (cache and timing lines per solve) or verbose (adds Compute’s raw error bodies).',\n\timpact: 'verbose can write what was solved to the log, which erasure cannot reach.'\n});\n\n/** `SELVA_FLAG_COMPUTE_DEBUG`: `verbose`, or on and off in the manifest's boolean words. */\nexport function computeDebugMode(env: EnvRecord): 'off' | 'on' | 'verbose' {\n\tif ((readSetting(COMPUTE_DEBUG, env) as string).toLowerCase() === 'verbose') return 'verbose';\n\treturn readSetting({ ...COMPUTE_DEBUG, type: 'bool', default: false }, env) ? 'on' : 'off';\n}\n\n/** Keys only this app reads. adapter-node's own keys are here too: they decide whether it works. */\nexport const APP_SETTINGS = composeManifest([\n\tdefineSetting({\n\t\tkey: 'ORIGIN',\n\t\tlabel: 'Public address',\n\t\ttype: 'url',\n\t\torigin: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'The URL people use to reach Selva, such as https://selva.example.com.',\n\t\timpact:\n\t\t\t'Wrong or unset behind a proxy: form posts fail the CSRF check and invite links carry an internal host.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'PORT',\n\t\tlabel: 'Port',\n\t\ttype: 'int',\n\t\tmin: 1,\n\t\tmax: 65535,\n\t\tdefault: 3000,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'Port the app listens on.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'HOST',\n\t\tlabel: 'Listen address',\n\t\ttype: 'string',\n\t\tdefault: '0.0.0.0',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription:\n\t\t\t'Which network address the app accepts connections on. 127.0.0.1 when a proxy sits in front.',\n\t\timpact: 'Under header auth, anything that reaches the port directly can claim to be any user.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'BODY_SIZE_LIMIT',\n\t\tlabel: 'Max request size',\n\t\ttype: 'string',\n\t\tdefault: '512K',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'Largest request the server accepts at all, uploads included (K, M or G suffix).',\n\t\timpact: 'Below COMPUTE_REQUEST_MAX_BYTES, uploads and file inputs fail with 413.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'ADDRESS_HEADER',\n\t\tlabel: 'Visitor IP header',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription:\n\t\t\t'Header your proxy uses to pass on the visitor’s IP address. Usually X-Forwarded-For.',\n\t\timpact: 'Unset behind a proxy: every client shares one rate-limit bucket.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'XFF_DEPTH',\n\t\tlabel: 'Proxies in front',\n\t\ttype: 'int',\n\t\tmin: 1,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'How many proxies sit between visitors and the app. Usually 1.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'PROTOCOL_HEADER',\n\t\tlabel: 'Protocol header',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'Header carrying the original protocol, when ORIGIN is unset.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'HOST_HEADER',\n\t\tlabel: 'Host header',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'Header carrying the original host, when ORIGIN is unset.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'NODE_ENV',\n\t\tlabel: 'Run mode',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'production in deployments: hides stack traces and makes cookies Secure.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'ALLOW_INSECURE_COOKIES',\n\t\tlabel: 'Allow sign-in over http',\n\t\ttype: 'bool',\n\t\tdefault: false,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'Drop the Secure cookie flag so sign-in works over plain http.',\n\t\tlegacy: { bool: 'exact-true' }\n\t}),\n\tdefineSetting({\n\t\tkey: 'INSTALL_DIR',\n\t\tlabel: 'Install folder',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription:\n\t\t\t'Deployment directory the admin updater runs in. Defaults to the working directory.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'NPM_CONFIG_REGISTRY',\n\t\tlabel: 'npm registry',\n\t\ttype: 'url',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription:\n\t\t\t'Registry updates are checked against and installed from. Defaults to registry.npmjs.org.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SELVA_EVENT_CALLBACK_ORIGIN',\n\t\tlabel: 'Solve event callback address',\n\t\ttype: 'url',\n\t\torigin: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription:\n\t\t\t'Origin Rhino.Compute posts live solve events to, when it differs from the browser’s.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'MCP_ALLOWED_ORIGINS',\n\t\tlabel: 'Extra MCP origins',\n\t\ttype: 'list',\n\t\tdefault: [],\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription: 'Browser origins /mcp accepts besides its own.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'MCP_PREVIEW_BROWSER',\n\t\tlabel: 'MCP preview browser',\n\t\ttype: 'string',\n\t\tdefault: '',\n\t\tonInvalid: 'default',\n\t\tclass: 'setting',\n\t\tdescription:\n\t\t\t\"Chromium or Chrome executable that selva_capture_preview renders with. Empty: Playwright's own Chromium, else an installed Chrome, Edge or distro Chromium.\"\n\t}),\n\tdefineSetting({\n\t\tkey: 'LOG_LEVEL',\n\t\tlabel: 'Log level',\n\t\ttype: 'enum',\n\t\tvalues: ['debug', 'info', 'warn', 'error'],\n\t\tonInvalid: 'default',\n\t\tclass: 'setting',\n\t\tdescription: 'Lowest severity written to the log. Default info (debug in development).'\n\t}),\n\tCOMPUTE_DEBUG,\n\tdefineSetting({\n\t\tkey: 'SENTRY_DSN',\n\t\tlabel: 'Sentry error reporting',\n\t\ttype: 'url',\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tdescription:\n\t\t\t'Ship unexpected server errors to Sentry, scrubbed of cookies, auth headers, bodies and query strings.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SENTRY_TRACES_SAMPLE_RATE',\n\t\tlabel: 'Sentry trace sampling',\n\t\ttype: 'string',\n\t\tdefault: '0',\n\t\tonInvalid: 'default',\n\t\tclass: 'tunable',\n\t\tdescription:\n\t\t\t'Share of requests traced to Sentry, 0–1 (out of range is clamped). 0 sends errors only.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SELVA_RELEASE',\n\t\tlabel: 'Release tag',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'tunable',\n\t\tdescription: 'Release tag on Sentry events and log records.'\n\t})\n]);\n\n/** Prefixes whose undeclared keys are reported as unknown (likely typos). */\nexport const WATCHED_PREFIXES = [\n\t'SELVA_',\n\t'SUPABASE_',\n\t'COMPUTE_',\n\t'SMTP_',\n\t'HEADER_AUTH_',\n\t'API_TOKEN_',\n\t'MAX_',\n\t'REMOTE_DEFINITION_',\n\t'SIGN_IN_',\n\t'BOOTSTRAP_'\n] as const;\n\n/** Read by tooling, not by the app: not unknown, not reported. */\nexport const EXTERNAL_KEYS = ['SELVA_REQUIRE_SUPABASE'] as const;\n\n/**\n * Keys no release reads any more, with what took their place. Boot and doctor\n * name them instead of calling them typos; `selva migrate` removes them.\n */\nexport const RETIRED_KEYS: Readonly<Record<string, string>> = {\n\tSELVA_FLAG_COMPUTE_DEBUG_VERBOSE: 'use SELVA_FLAG_COMPUTE_DEBUG=verbose',\n\tCOMPUTE_RATE_LIMIT_WINDOW_MS: 'fixed at 100 s',\n\tAPI_TOKEN_RATE_LIMIT_WINDOW_MS: 'fixed at 60 s',\n\tMAX_IMAGE_FILE_SIZE_BYTES: 'fixed at 10 MB',\n\tCOMPUTE_REQUEST_MAX_BYTES: 'fixed at 256 MB',\n\tCOMPUTE_RESPONSE_MAX_BYTES: 'fixed at 300 MB',\n\tREMOTE_DEFINITION_FETCH_TIMEOUT_MS: 'fixed at 30 s',\n\tREMOTE_DEFINITION_CACHE_TTL_MS: 'fixed at 5 min',\n\tDEFINITION_CACHE_TTL_MS: 'fixed at 5 min',\n\tSUPABASE_TOKEN_VERIFICATION: 'always hybrid',\n\tSUPABASE_REVALIDATE_MS: 'fixed at 60 s',\n\tSUPABASE_PRIVATE_URL_PREFIX: 'fixed at /api/files',\n\tCOMPUTE_SOLVE_DEADLINE_MS: 'set --timeout (RHINO_COMPUTE_TIMEOUT) on the compute server',\n\tMAX_SOLVE_DURATION_MS: 'set --timeout (RHINO_COMPUTE_TIMEOUT) on the compute server',\n\tCOMPUTE_REUSE_DEFINITION_CACHE: 'on whenever the compute server reports /limits',\n\tCOMPUTE_CACHE_ERRORED_SOLVES: 'removed'\n};\n\n/**\n * The manifest for this deployment: engine and app keys, plus the slices of\n * the providers it selects. A provider's required keys only apply when it is\n * in use, so slices are chosen here rather than all composed at once.\n */\nexport function deploymentManifest(env: EnvRecord): Manifest {\n\tconst chosen = new Set(\n\t\t(['SELVA_AUTH_PROVIDER', 'SELVA_DATA_PROVIDER', 'SELVA_STORAGE_PROVIDER'] as const).map((k) =>\n\t\t\t(env[k] ?? 'local').toLowerCase()\n\t\t)\n\t);\n\treturn composeManifest([\n\t\tENGINE_SETTINGS,\n\t\tAPP_SETTINGS,\n\t\t...(chosen.has('local') ? [LOCAL_SETTINGS] : []),\n\t\t...(chosen.has('supabase') ? [SUPABASE_SETTINGS] : []),\n\t\t...(chosen.has('header') ? [HEADER_AUTH_SETTINGS] : [])\n\t]);\n}\n\n/** Every key any slice declares, whichever providers are chosen. */\nexport const ALL_SETTINGS: Manifest = composeManifest([\n\tENGINE_SETTINGS,\n\tAPP_SETTINGS,\n\tLOCAL_SETTINGS,\n\tSUPABASE_SETTINGS,\n\tHEADER_AUTH_SETTINGS\n]);\n\n/** The report for this deployment. Keys of providers it doesn't use are known, not typos. */\nexport function deploymentReport(env: EnvRecord): ConfigReport {\n\tconst manifest = deploymentManifest(env);\n\tconst active = new Set(manifest.flatMap((s) => [s.key, ...(s.aliases ?? [])]));\n\tconst inactive = ALL_SETTINGS.flatMap((s) => [s.key, ...(s.aliases ?? [])]).filter(\n\t\t(k) => !active.has(k)\n\t);\n\treturn buildConfigReport(manifest, env, {\n\t\tprefixes: WATCHED_PREFIXES,\n\t\texternal: [...EXTERNAL_KEYS, ...Object.keys(RETIRED_KEYS), ...inactive]\n\t});\n}\n\n// Set by the process manager (pm2's ecosystem file), never by .env, so the CLI\n// comparing .env with the last boot would report it as drift forever.\nconst NOT_FROM_ENV_FILE = new Set(['NODE_ENV']);\n\n/** What the boot snapshot and the CLI's drift check compare. */\nexport function deploymentSnapshot(env: EnvRecord, salt?: string): ConfigSnapshot {\n\tconst manifest = deploymentManifest(env).filter((s) => !NOT_FROM_ENV_FILE.has(s.key));\n\treturn takeSnapshot(manifest, env, salt);\n}\n\n/** The rotation overlap of each root key: what the admin page and doctor count down. */\nexport function keyRotationStatus(env: EnvRecord, now: number = Date.now()): KeyRotation[] {\n\treturn (['SELVA_HMAC_KEY', 'SELVA_AT_REST_KEY'] as const).map((key) => {\n\t\tconst p = previousKey(env, key, now);\n\t\t// The previous key itself never leaves the server.\n\t\treturn {\n\t\t\tkey,\n\t\t\tstate: p.state,\n\t\t\t...('expires' in p ? { expires: p.expires } : {}),\n\t\t\t...('daysLeft' in p ? { daysLeft: p.daysLeft } : {})\n\t\t};\n\t});\n}\n","import { env } from '#lib/server/env.js';\nimport type {\n\tIErrorReporter,\n\tIEventSink,\n\tILogger,\n\tINotificationProvider,\n\tISolveMetricSink,\n\tLogFields,\n\tLogLevel,\n\tSelvaBranding,\n\tSelvaConfig,\n\tSelvaFlags,\n\tTenancyMode\n} from '@selvajs/platform';\nimport { NoopErrorReporter, NoopEventSink } from '@selvajs/platform';\nimport { createSelvaProviders, type ProviderRegistry } from '@selvajs/server/providers';\nimport * as local from '@selvajs/local-provider';\nimport * as supa from '@selvajs/supabase-provider';\nimport * as header from '@selvajs/header-auth-provider';\nimport { DefinitionService } from '@selvajs/server/definitions';\nimport { MAX_SOLVE_DEADLINE_MS } from '@selvajs/solve/server';\nimport { OrgAssetService } from '@selvajs/server/organizations';\nimport { SentryErrorReporter } from '@selvajs/server/errors';\nimport { SmtpNotificationProvider } from '@selvajs/server/notifications';\nimport { ConsoleLogger, createLogger, renderThrown } from '@selvajs/server/logging';\nimport { computeDebugMode } from '#lib/server/config/settings.js';\n\n// Provider wiring lives in `@selvajs/server/providers` (`createSelvaProviders`):\n// env-driven selection over the registry below, an external `selva.config.js`\n// override via SELVA_CONFIG_PATH, and lazy memoized instantiation (nothing\n// touches provider secrets at import/build time). This file is the app's\n// composition root: bundled provider implementations, service singletons,\n// and error reporting.\n\n// Forwards to whatever the root logger currently is, rather than capturing it.\n// `_logger` starts as a console placeholder and is swapped for pino once its\n// async load resolves (see Logging below); a provider handed `getLogger()`\n// directly at construction would pin the placeholder for the process's whole\n// life, so long-lived providers get this indirection instead.\nexport const lazyLogger: ILogger = {\n\tdebug: (m: string, f?: LogFields) => getLogger().debug(m, f),\n\tinfo: (m: string, f?: LogFields) => getLogger().info(m, f),\n\twarn: (m: string, f?: LogFields) => getLogger().warn(m, f),\n\terror: (m: string, f?: LogFields) => getLogger().error(m, f),\n\tchild: (f: LogFields) => getLogger().child(f)\n};\n\n/** The provider implementations bundled with the Selva app. */\nconst registry: ProviderRegistry = {\n\tauth: {\n\t\tlocal: (e) => local.LocalAuthProvider.fromEnv(e),\n\t\tsupabase: (e) =>\n\t\t\tsupa.SupabaseAuthProvider.fromEnv(e, lazyLogger, {\n\t\t\t\t// The session minted for an API-token request must outlive its solve, whichever\n\t\t\t\t// server runs it.\n\t\t\t\tdelegatedSessionTtlSeconds: MAX_SOLVE_DEADLINE_MS / 1000 + 60\n\t\t\t}),\n\t\theader: (e) => header.HeaderAuthProvider.fromEnv(e, lazyLogger)\n\t},\n\tdata: {\n\t\tlocal: (e) => local.LocalDataProvider.fromEnv(e),\n\t\t// `events` (2nd param) stays defaulted — the app wires its event sink\n\t\t// separately, see getEventSink below.\n\t\tsupabase: (e) => supa.SupabaseDataProvider.fromEnv(e, undefined, lazyLogger)\n\t},\n\tstorage: {\n\t\tlocal: (e) => local.LocalStorageProvider.fromEnv(e),\n\t\tsupabase: (e) => supa.SupabaseStorageProvider.fromEnv(e)\n\t}\n};\n\nconst runtime = await createSelvaProviders(env, {\n\tregistry,\n\tconfigPath: env.SELVA_CONFIG_PATH,\n\tlogger: lazyLogger\n});\n\n// Memoized: first call instantiates providers from env (may throw if\n// required secrets are missing) and later calls return the cached config.\n// Importing this module has no side effects — init happens lazily on the\n// first request, never at build time.\nexport function resolveProviders(): SelvaConfig {\n\treturn runtime.resolve();\n}\n\n/**\n * @deprecated Prefer {@link resolveProviders}. Kept as a property accessor so\n * existing `import { providers }` call sites resolve lazily instead of at\n * import time.\n */\nexport const providers = new Proxy({} as SelvaConfig, {\n\tget(_t, prop) {\n\t\treturn Reflect.get(resolveProviders(), prop);\n\t}\n});\n\nexport function getTenancy(): TenancyMode {\n\treturn runtime.tenancy();\n}\n\n// Every field has a default so the UI never has to null-check. Override via SELVA_BRAND_* env vars.\nexport function getBranding(): Required<SelvaBranding> {\n\treturn runtime.branding();\n}\n\n// Use this rather than reading flags directly — omitted flags resolve to false.\nexport function flag(name: keyof SelvaFlags): boolean {\n\treturn runtime.flag(name);\n}\n\nlet _definitionService: DefinitionService | undefined;\nexport function getDefinitionService(): DefinitionService {\n\tif (!_definitionService) {\n\t\tconst p = resolveProviders();\n\t\t_definitionService = new DefinitionService(p.data, p.storage);\n\t}\n\treturn _definitionService;\n}\n\nlet _orgAssetService: OrgAssetService | undefined;\nexport function getOrgAssetService(): OrgAssetService {\n\tif (!_orgAssetService) {\n\t\tconst p = resolveProviders();\n\t\t_orgAssetService = new OrgAssetService(p.data.orgs, p.storage);\n\t}\n\treturn _orgAssetService;\n}\n\nexport function getAuthProvider() {\n\treturn resolveProviders().auth;\n}\n\nexport function getStorageProvider() {\n\treturn resolveProviders().storage;\n}\n\nexport function getDataProvider() {\n\treturn resolveProviders().data;\n}\n\nexport function getOrganizationProvider() {\n\treturn resolveProviders().data.orgs;\n}\n\nexport function getProjectProvider() {\n\treturn resolveProviders().data.projects;\n}\n\nexport function getDefinitionMeta() {\n\treturn resolveProviders().data.definitions;\n}\n\nexport function getComputeServerConfigStore() {\n\treturn resolveProviders().data.computeServer;\n}\n\nexport function getUserProfileStore() {\n\treturn resolveProviders().data.userProfile;\n}\n\nexport function getShareLinkStore() {\n\treturn resolveProviders().data.shareLinks;\n}\n\nexport function getInviteStore() {\n\treturn resolveProviders().data.invites;\n}\n\nexport function getPermissionStore() {\n\treturn resolveProviders().data.permissions;\n}\n\nexport function getPlatformProjectGrantStore() {\n\treturn resolveProviders().data.platformProjectGrants;\n}\n\n// Defaults to `NoopSolveMetricSink` when the config omits `solveMetrics`, so the compute route always records unconditionally.\nexport function getSolveMetricSink(): ISolveMetricSink {\n\treturn runtime.solveMetricSink();\n}\n\n// Null on deployments where the audit log isn't queryable (local-provider\n// stays on `NoopEventSink`). Callers must handle null and degrade their UI.\nexport function getAuditQuery() {\n\treturn providers.data.auditQuery ?? null;\n}\n\nconst noopEventSink = new NoopEventSink();\n\n// Write-side sink for routes with no store mutation to piggyback on (e.g.\n// self-update lifecycle events). Prefers SelvaConfig.events, then the data\n// provider's own sink, then a no-op.\nexport function getEventSink(): IEventSink {\n\tconst p = resolveProviders();\n\treturn p.events ?? p.data.events ?? noopEventSink;\n}\n\n// ============================================================================\n// Logging\n// ============================================================================\n\n// Same eager-init-then-swap shape as the error reporter below, but the\n// placeholder here is a real ConsoleLogger, never a no-op: logging must not\n// have a window where warnings vanish while an operator is debugging a boot\n// failure. Records written before pino resolves land on the console; the\n// swap only upgrades the formatting.\nconst LOG_LEVEL: LogLevel = parseLogLevel(env.LOG_LEVEL);\n\nlet _logger: ILogger = new ConsoleLogger({}, LOG_LEVEL);\n\n// Pino-backed when `pino` is installed (ships with the app; the base\n// `@selvajs/server` install treats it as an optional peer and falls back to\n// console). Prefer a request-scoped child (`event.locals.log`) in route\n// handlers so records carry `requestId`/`route` — use this root logger for\n// boot, shutdown, and background work with no request.\nexport function getLogger(): ILogger {\n\treturn _logger;\n}\n\nlet _notifications: INotificationProvider | null = null;\n\n// SMTP-backed; sends nothing when `SMTP_HOST` is unset, which is a supported\n// deployment — callers fall back to sharing links by hand. `env` is passed\n// rather than read inside the provider: under `vite dev`, Vite doesn't\n// mirror `.env` into `process.env`, so reading it directly would silently\n// ignore every override.\nexport function getNotificationProvider(): INotificationProvider {\n\t_notifications ??= new SmtpNotificationProvider(env);\n\treturn _notifications;\n}\n\n// `LOG_LEVEL` is operator input — an unrecognized value must not crash boot\n// or silently disable logging. Defaults to `info`, `debug` in dev.\nfunction parseLogLevel(raw: string | undefined): LogLevel {\n\tconst value = raw?.trim().toLowerCase();\n\tif (value === 'debug' || value === 'info' || value === 'warn' || value === 'error') return value;\n\t// An operator who set SELVA_FLAG_COMPUTE_DEBUG asked for debug output in so\n\t// many words — honor it without also requiring LOG_LEVEL=debug, since the\n\t// flag would otherwise silently do nothing in production.\n\tif (computeDebugMode(env) !== 'off') return 'debug';\n\treturn env.NODE_ENV === 'development' ? 'debug' : 'info';\n}\n\n// Eager, fire-and-forget: `getLogger()` stays sync for the same reason\n// `getErrorReporter()` does below — callers (hooks, process handlers) can't await.\nvoid createLogger({\n\tlevel: LOG_LEVEL,\n\t// Pretty in dev, newline-delimited JSON in production. `pino-pretty` is a\n\t// devDependency, so this degrades to JSON if it's absent.\n\tpretty: env.NODE_ENV === 'development',\n\tbase: { service: 'selva', release: env.SELVA_RELEASE }\n}).then((logger) => {\n\t_logger = logger;\n});\n\n// ============================================================================\n// Error reporting\n// ============================================================================\n\n// Starts as the no-op reporter, swapped for a Sentry-backed one once async\n// init resolves. `getErrorReporter()` is synchronous — called from\n// `handleError` and process error hooks, which can't await — so reports go\n// to the no-op during the sub-second boot window before Sentry loads.\n// Acceptable: only errors thrown in that window are lost.\nlet _errorReporter: IErrorReporter = new NoopErrorReporter();\n\n// Ships errors off-box (Sentry) only when `SENTRY_DSN` is configured;\n// otherwise a no-op, so self-hosters opt in via env and the base install\n// carries no error-tracking dependency. Only genuinely unexpected errors\n// reach here — see `handleError` in hooks.server.ts for what's filtered out.\nexport function getErrorReporter(): IErrorReporter {\n\treturn _errorReporter;\n}\n\n// Eager, fire-and-forget init at module load. Kept out of `getErrorReporter()`\n// so the getter stays sync and allocation-free on the hot error path.\nif (env.SENTRY_DSN) {\n\tvoid SentryErrorReporter.create({\n\t\tdsn: env.SENTRY_DSN,\n\t\tenvironment: env.NODE_ENV,\n\t\trelease: env.SELVA_RELEASE,\n\t\ttracesSampleRate: env.SENTRY_TRACES_SAMPLE_RATE\n\t}).then((reporter) => {\n\t\tif (reporter) {\n\t\t\t_errorReporter = reporter;\n\t\t\tgetLogger().info('Sentry error tracking enabled', { component: 'ErrorReporter' });\n\t\t}\n\t});\n}\n\n// Process-level safety net. `handleError` only sees errors on the request\n// path; a rejected promise with no awaiter, or a throw outside any request,\n// bypasses it and would otherwise vanish. Report both, then let Node's\n// default behavior stand (logs uncaughtException and exits — we don't\n// swallow it and pretend the process is healthy). Guarded so repeated module\n// evaluation in dev/HMR doesn't stack duplicate listeners.\nconst ERROR_HOOKS_FLAG = '__selvaProcessErrorHooksRegistered';\nif (!(globalThis as Record<string, unknown>)[ERROR_HOOKS_FLAG]) {\n\t(globalThis as Record<string, unknown>)[ERROR_HOOKS_FLAG] = true;\n\tprocess.on('unhandledRejection', (reason) => {\n\t\tgetLogger().error('Unhandled promise rejection', {\n\t\t\tcomponent: 'process',\n\t\t\torigin: 'unhandledRejection',\n\t\t\terr: renderThrown(reason)\n\t\t});\n\t\tgetErrorReporter().capture(reason, { tags: { origin: 'unhandledRejection' } });\n\t});\n\tprocess.on('uncaughtException', (error) => {\n\t\t// Also write straight to the console here: Node is about to exit, and a\n\t\t// buffered/async log transport may never flush. The duplicate line is a\n\t\t// cheap price for not losing the record that explains the crash.\n\t\t// Rendered, not raw — handing the object to stdout would print whatever\n\t\t// a provider adapter stashed on `cause` (connection details, sometimes a\n\t\t// DSN) where pino's redaction never runs.\n\t\tconsole.error('[uncaughtException]', renderThrown(error));\n\t\tgetLogger().error('Uncaught exception', {\n\t\t\tcomponent: 'process',\n\t\t\torigin: 'uncaughtException',\n\t\t\terr: renderThrown(error)\n\t\t});\n\t\tgetErrorReporter().capture(error, { tags: { origin: 'uncaughtException' } });\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,kBACf,UACA,KACA,UAA0B,CAAC,GACZ;CACf,MAAM,WAAW,cAAc,UAAU,KAAK,OAAO;CACrD,MAAM,OAAoB,SAAS,KAAK,SAAS;EAChD,MAAM,IAAI,SAAS,KAAK,KAAK;EAC7B,OAAO;GACN,KAAK,KAAK;GACV,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CA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D,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,SAAS;EACT,WAAW;EACX,OAAO;EACP,SAAS;EACT,aACC;EACD,QAAQ;CACT,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,SAAS;EACT,WAAW;EACX,OAAO;EACP,SAAS;EACT,aAAa;EACb,QAAQ;CACT,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,SAAS;EACT,aACC;EACD,QAAQ;CACT,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,KAAK;EACL,WAAW;EACX,OAAO;EACP,SAAS;EACT,aAAa;CACd,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aAAa;CACd,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aAAa;CACd,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aAAa;CACd,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,SAAS;EACT,WAAW;EACX,OAAO;EACP,aAAa;EACb,QAAQ,EAAE,MAAM,aAAa;CAC9B,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aACC;CACF,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aACC;CACF,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,QAAQ;EACR,WAAW;EACX,OAAO;EACP,aACC;CACF,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,SAAS,CAAC;EACV,WAAW;EACX,OAAO;EACP,aAAa;CACd,CAAC;CACD,cAAc;EACb,K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D,QAAQ,GAAG,sBAAsB,UAAU;EAO1C,QAAQ,MAAM,uBAAuB,aAAa,KAAK,CAAC;EACxD,UAAU,CAAC,CAAC,MAAM,sBAAsB;GACvC,WAAW;GACX,QAAQ;GACR,KAAK,aAAa,KAAK;EACxB,CAAC;EACD,iBAAiB,CAAC,CAAC,QAAQ,OAAO,EAAE,MAAM,EAAE,QAAQ,oBAAoB,EAAE,CAAC;CAC5E,CAAC;AACF"}
|
|
1
|
+
{"version":3,"file":"providers.server.js","names":["prefix","resolvePath","fs","path","LAST_LOGIN_DEBOUNCE_MS","empty","toAuthUser","path","empty","path","empty","isLive","path","empty","bindingOf","path","empty","path","isLive","path","empty","path","empty","path","empty","path","path","path","path","fs","mapError","readFile","fs","writeFile","path","path"],"sources":["../../../../platform/src/config/report.ts","../../../../platform/src/config/snapshot.ts","../../../../platform/src/errors/interface.ts","../../../../platform/src/data/interface.ts","../../../../platform/src/storage/safeKey.ts","../../../../platform/src/definitions/paths.ts","../../../../platform/src/events/interface.ts","../../../../platform/src/organizations/paths.ts","../../../../platform/src/permissions/guards.ts","../../../../platform/src/storage/image.ts","../../../../platform/src/storage/assetClasses.ts","../../../../platform/src/storage/cacheBust.ts","../../../../platform/src/userProfile/types.ts","../../../../platform/src/userProfile/guards.ts","../../../../platform/src/utils/audit.ts","../../../../platform/src/metrics/interface.ts","../../../../server/src/providers/create-selva-providers.ts","../../../../providers/local/src/auth/hmac.ts","../../../../providers/local/src/data/fsJson.ts","../../../../providers/local/src/auth/users.ts","../../../../providers/local/src/data/pagination.ts","../../../../providers/local/src/auth/LocalAuthProvider.ts","../../../../providers/local/src/data/LocalInviteStore.ts","../../../../providers/local/src/data/LocalApiTokenStore.ts","../../../../platform/src/computeServer/secrets.ts","../../../../providers/local/src/data/LocalComputeServerStore.ts","../../../../providers/local/src/data/LocalPlatformProjectGrantStore.ts","../../../../providers/local/src/data/LocalOrgStore.ts","../../../../providers/local/src/data/LocalProjectStore.ts","../../../../providers/local/src/data/LocalDefinitionStore.ts","../../../../providers/local/src/data/LocalShareLinkStore.ts","../../../../providers/local/src/data/userData.ts","../../../../providers/local/src/userProfile/LocalUserProfileProvider.ts","../../../../providers/local/src/permissions/LocalPlatformPermissionStore.ts","../../../../providers/local/src/data/LocalDataProvider.ts","../../../../providers/local/src/storage/LocalStorageProvider.ts","../../../../providers/supabase/src/storage/SupabaseStorageProvider.ts","../../../../providers/supabase/src/data/errors.ts","../../../../providers/supabase/src/data/SupabasePlatformProjectGrantStore.ts","../../../../providers/supabase/src/data/pagination.ts","../../../../providers/supabase/src/data/rowStamp.ts","../../../../providers/supabase/src/data/SupabaseOrgStore.ts","../../../../providers/supabase/src/data/SupabaseProjectStore.ts","../../../../providers/supabase/src/data/SupabaseDefinitionStore.ts","../../../../providers/supabase/src/data/SupabaseInviteStore.ts","../../../../providers/supabase/src/data/SupabaseComputeServerStore.ts","../../../../providers/supabase/src/data/SupabaseShareLinkStore.ts","../../../../providers/supabase/src/data/SupabaseApiTokenStore.ts","../../../../providers/supabase/src/data/migrationHead.ts","../../../../providers/supabase/src/data/client.ts","../../../../providers/supabase/src/data/SupabaseEventSink.ts","../../../../providers/supabase/src/data/SupabaseSolveMetricSink.ts","../../../../providers/supabase/src/data/SupabaseAuditQuery.ts","../../../../providers/supabase/src/userProfile/SupabaseUserProfileProvider.ts","../../../../providers/supabase/src/permissions/SupabasePlatformPermissionStore.ts","../../../../providers/supabase/src/data/SupabaseDataProvider.ts","../../../../providers/supabase/src/auth/SupabaseDelegatedSession.ts","../../../../providers/supabase/src/config.ts","../../../../providers/supabase/src/auth/SupabaseAuthProvider.ts","../../../../providers/header-auth/src/users.ts","../../../../providers/header-auth/src/HeaderAuthProvider.ts","../../../../server/src/definitions/definition-service.ts","../../../../server/src/organizations/org-asset-service.ts","../../../../server/src/errors/scrub.ts","../../../../server/src/errors/SentryErrorReporter.ts","../../../../server/src/notifications/smtp-config.ts","../../../../server/src/notifications/smtp-provider.ts","../../../../providers/header-auth/src/config.ts","../../../../providers/local/src/config.ts","../../../src/lib/server/config/settings.ts","../../../src/lib/server/providers.server.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { IntUnit, Manifest, SettingClass, SettingSpec } from './manifest.js';\nimport {\n\tresolveConfig,\n\ttype EnvRecord,\n\ttype KeyReport,\n\ttype KeyStatus,\n\ttype ResolveOptions,\n\ttype UnknownKey,\n\ttype ValueSource\n} from './resolve.js';\nimport { rawValue } from './raw-value.js';\n\nexport interface ReportRow {\n\tkey: string;\n\tlabel?: string;\n\ttype: SettingSpec['type'];\n\trequired: boolean;\n\t/** What 0 means for an int whose 0 is a sentinel. */\n\tzero?: string;\n\tunit?: IntUnit;\n\tclass: SettingClass;\n\tsummary: boolean;\n\tdescription: string;\n\timpact?: string;\n\tsource: ValueSource;\n\tstatus: KeyStatus;\n\t/** Safe to print: secrets are a fingerprint or \"set\", never the value. */\n\tdisplay: string;\n\tproblem?: string;\n\talias?: string;\n}\n\nexport interface ConfigReport {\n\t/** Summary rows first, then the rest, each in manifest order. */\n\trows: ReportRow[];\n\t/** Rows whose value failed its rule. */\n\tproblems: ReportRow[];\n\tunknown: UnknownKey[];\n}\n\n/**\n * What `selva config show` and the admin page render. Pure, and free of\n * secret values, so the result can go to a browser or a terminal as is.\n */\nexport function buildConfigReport(\n\tmanifest: Manifest,\n\tenv: EnvRecord,\n\toptions: ResolveOptions = {}\n): ConfigReport {\n\tconst resolved = resolveConfig(manifest, env, options);\n\tconst rows: ReportRow[] = manifest.map((spec) => {\n\t\tconst k = resolved.keys[spec.key];\n\t\treturn {\n\t\t\tkey: spec.key,\n\t\t\t...(spec.label ? { label: spec.label } : {}),\n\t\t\ttype: spec.type,\n\t\t\trequired: spec.required === true,\n\t\t\t...(spec.type === 'int' && spec.zero ? { zero: spec.zero } : {}),\n\t\t\t...(spec.type === 'int' && spec.unit ? { unit: spec.unit } : {}),\n\t\t\tclass: spec.class,\n\t\t\tsummary: spec.summary === true,\n\t\t\tdescription: spec.description,\n\t\t\t...(spec.impact ? { impact: spec.impact } : {}),\n\t\t\tsource: k.source,\n\t\t\tstatus: k.status,\n\t\t\tdisplay: display(spec, k, rawValue(spec, env)?.raw),\n\t\t\t...(k.problem ? { problem: k.problem } : {}),\n\t\t\t...(k.alias ? { alias: k.alias } : {})\n\t\t};\n\t});\n\treturn {\n\t\trows: [...rows.filter((r) => r.summary), ...rows.filter((r) => !r.summary)],\n\t\tproblems: rows.filter((r) => r.status !== 'ok'),\n\t\tunknown: resolved.unknown\n\t};\n}\n\n/** `raw` is the env text the value came from, undefined when it is the default. */\nfunction display(spec: SettingSpec, k: KeyReport, raw: string | undefined): string {\n\tif (k.source === 'unset') return '';\n\tif (spec.sensitive) {\n\t\t// A fingerprint of a 256-bit random key reveals nothing; of a password it\n\t\t// would be an offline guessing oracle.\n\t\treturn raw !== undefined && spec.generated ? fingerprint(raw) : 'set';\n\t}\n\treturn raw === undefined ? formatValue(k.value) : raw.trim();\n}\n\nfunction formatValue(value: unknown): string {\n\tif (Array.isArray(value)) return value.join(',');\n\treturn value === undefined ? '' : String(value);\n}\n\n/** Short, stable id for a generated key, so two machines can be compared. */\nexport function fingerprint(value: string): string {\n\treturn `sha256:${createHash('sha256').update(value.trim()).digest('hex').slice(0, 8)}`;\n}\n","import { createHmac, randomBytes } from 'node:crypto';\nimport type { Manifest } from './manifest.js';\nimport type { EnvRecord } from './resolve.js';\nimport { rawValue } from './raw-value.js';\n\n/**\n * The set keys of one boot, written beside `.env` so the next boot, and the\n * CLI, can say what changed. The file must not become a second copy of the\n * secrets: a generated key is stored as a salted HMAC, any other sensitive\n * value as a fixed marker, since a digest of a password or an email address\n * can be guessed back with the salt beside it.\n */\nexport interface ConfigSnapshot {\n\tversion: 1;\n\tsalt: string;\n\tvalues: Record<string, string>;\n\t/** Keys whose `values` entry is a digest or the marker, not the value. */\n\tsensitive: string[];\n}\n\nexport interface ConfigChange {\n\tkey: string;\n\tchange: 'added' | 'removed' | 'changed';\n\t/** Absent for sensitive keys. */\n\tfrom?: string;\n\tto?: string;\n}\n\nconst SENSITIVE_MARKER = 'set';\n\nexport function takeSnapshot(manifest: Manifest, env: EnvRecord, salt?: string): ConfigSnapshot {\n\t// A JS caller passes the previous file's salt as parsed; anything else starts afresh.\n\tconst key = typeof salt === 'string' && salt !== '' ? salt : randomBytes(16).toString('hex');\n\tconst values: Record<string, string> = {};\n\tconst sensitive: string[] = [];\n\tfor (const spec of manifest) {\n\t\tconst found = rawValue(spec, env);\n\t\tif (!found) continue;\n\t\tconst raw = found.raw.trim();\n\t\tif (spec.sensitive) {\n\t\t\tvalues[spec.key] = spec.generated\n\t\t\t\t? createHmac('sha256', key).update(raw).digest('hex').slice(0, 16)\n\t\t\t\t: SENSITIVE_MARKER;\n\t\t\tsensitive.push(spec.key);\n\t\t} else {\n\t\t\tvalues[spec.key] = raw;\n\t\t}\n\t}\n\treturn { version: 1, salt: key, values, sensitive };\n}\n\n/**\n * What changed since `before`, the previous snapshot as read from disk; anything\n * that is not a snapshot counts as none. Take `after` with `before.salt`, or every\n * generated key reads as changed.\n */\nexport function diffSnapshots(before: unknown, after: ConfigSnapshot): ConfigChange[] {\n\tif (!isSnapshot(before)) return [];\n\tconst secret = new Set([...before.sensitive, ...after.sensitive]);\n\tconst changes: ConfigChange[] = [];\n\tconst plain = (key: string, from?: string, to?: string) =>\n\t\tsecret.has(key)\n\t\t\t? {}\n\t\t\t: { ...(from !== undefined ? { from } : {}), ...(to !== undefined ? { to } : {}) };\n\n\tfor (const [key, to] of Object.entries(after.values)) {\n\t\tconst from = before.values[key];\n\t\tif (from === undefined) changes.push({ key, change: 'added', ...plain(key, undefined, to) });\n\t\telse if (from !== to) changes.push({ key, change: 'changed', ...plain(key, from, to) });\n\t}\n\tfor (const [key, from] of Object.entries(before.values)) {\n\t\tif (!(key in after.values)) changes.push({ key, change: 'removed', ...plain(key, from) });\n\t}\n\treturn changes;\n}\n\nfunction isSnapshot(value: unknown): value is ConfigSnapshot {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst { version, salt, values, sensitive } = value as Record<string, unknown>;\n\treturn (\n\t\tversion === 1 &&\n\t\ttypeof salt === 'string' &&\n\t\tsalt !== '' &&\n\t\ttypeof values === 'object' &&\n\t\tvalues !== null &&\n\t\t!Array.isArray(values) &&\n\t\tObject.values(values).every((v) => typeof v === 'string') &&\n\t\tArray.isArray(sensitive) &&\n\t\tsensitive.every((k) => typeof k === 'string')\n\t);\n}\n","/**\n * Structured context attached to a reported error. All fields optional — a\n * report can fire before any request context is built (e.g. an\n * `unhandledRejection` with no active request). Deliberately NOT a\n * `RequestContext`: reporters must never receive the opaque `adapterContext`, so\n * only non-sensitive routing/identity fields are surfaced here.\n */\nexport interface ErrorContext {\n\tmethod?: string;\n\t/** Never the query string — it can carry share tokens. */\n\troute?: string;\n\tuserId?: string;\n\torgId?: string;\n\ttags?: Record<string, string>;\n\t/** How urgent the report is. Default `error`; `warning` for a handled fault worth watching. */\n\tlevel?: 'fatal' | 'error' | 'warning';\n\t/**\n\t * Groups reports of one fault across messages (`compute-auth`, `compute-unreachable`), so\n\t * a fault whose message varies still reads as one issue.\n\t */\n\tkind?: string;\n}\n\n/**\n * Sink for unexpected server errors, including unhandled rejections and uncaught\n * exceptions.\n *\n * MUST NOT throw — reporting is best-effort and sits on the error path, where a\n * second failure would mask the first. Implementations catch and log their own\n * failures. MAY be fire-and-forget.\n */\nexport interface IErrorReporter {\n\t/**\n\t * `error` is whatever was thrown/rejected — often an `Error`, but adapters\n\t * occasionally reject with a plain object, so implementations must render\n\t * defensively.\n\t */\n\tcapture(error: unknown, context?: ErrorContext): void;\n}\n\n/**\n * Default `IErrorReporter` — discards every report, so call sites can report\n * unconditionally when no error-tracking backend is configured.\n */\nexport class NoopErrorReporter implements IErrorReporter {\n\tcapture(_error: unknown, _context?: ErrorContext): void {}\n}\n","/**\n * Composition root bundling every store an adapter implements. Individual\n * interfaces (`IOrgStore`, `IProjectStore`, …) live next to their types in\n * their own subdirs.\n *\n * Every store method takes a `RequestContext` first. **The query itself is\n * the security boundary** — adapters MUST scope reads/writes by `ctx`. An\n * unauthorized caller sees an empty page, `null`, or a `ProviderError`.\n *\n * Access-control predicates live in `@selvajs/platform/access`, not here.\n */\n\nimport type { IOrgStore } from '../organizations/interface.js';\nimport type { IProjectStore } from '../projects/interface.js';\nimport type { IDefinitionStore } from '../definitions/interface.js';\nimport type { IComputeServerStore } from '../computeServer/interface.js';\nimport type { IShareLinkStore } from '../shareLinks/interface.js';\nimport type { IPlatformProjectGrantStore } from '../platformProjects/interface.js';\nimport type { IInviteStore } from '../invites/interface.js';\nimport type { IApiTokenStore } from '../apiTokens/interface.js';\nimport type { IUserProfileStore } from '../userProfile/interface.js';\nimport type { IPlatformPermissionStore } from '../permissions/interface.js';\nimport type { IAuditQuery } from '../events/audit.js';\nimport type { IEventSink } from '../events/interface.js';\nimport type { RequestContext } from '../context.js';\n\n/**\n * Result of the app↔DB schema handshake. `expected` is the migration head\n * the running app was built against; `actual` is what the database reports\n * (`null` when the database can't even answer — e.g. the handshake function\n * itself was never migrated in).\n */\nexport interface SchemaVersionReport {\n\tok: boolean;\n\texpected: string;\n\tactual: string | null;\n\t/** Operator-facing explanation + recovery hint: why not ok, or, when ok, what is still pending. */\n\tmessage?: string;\n}\n\n/** Extra identifiers {@link IDataProvider.onUserDeleted} needs but can't derive from userId alone. */\nexport interface UserErasureOptions {\n\t/** The deleted user's email, for scrubbing invite/audit rows keyed by it. */\n\temail?: string;\n}\n\n/**\n * Written to `solve_metrics.actor_id` when a user is erased, so capacity/billing\n * aggregates survive without identifying the person. Distinct from `'system'`,\n * which marks solves never attributed to a user (share-link / server flows).\n */\nexport const ERASED_ACTOR_ID = 'deleted';\n\nexport interface IDataProvider {\n\torgs: IOrgStore;\n\tprojects: IProjectStore;\n\tdefinitions: IDefinitionStore;\n\tcomputeServer: IComputeServerStore;\n\tinvites: IInviteStore;\n\tshareLinks: IShareLinkStore;\n\tuserProfile: IUserProfileStore;\n\tpermissions: IPlatformPermissionStore;\n\tplatformProjectGrants: IPlatformProjectGrantStore;\n\t/**\n\t * Optional: a provider without it has API tokens switched off, and token\n\t * requests get 503 `API_TOKENS_UNAVAILABLE`. A provider whose stores scope\n\t * by a user JWT must also implement `IAuthProvider.delegatedSession`.\n\t */\n\tapiTokens?: IApiTokenStore;\n\t/**\n\t * Read-side for the persisted event log. Optional — providers whose event\n\t * sink is a noop (local-provider) leave this undefined and the\n\t * `/admin/audit` UI degrades to its \"no backend wired\" state.\n\t */\n\tauditQuery?: IAuditQuery;\n\t/**\n\t * Write-side event sink this provider's stores emit into. Optional — lets app\n\t * code with no store mutation to piggyback on (e.g. a self-update route) emit\n\t * domain events into the same log. Callers fall back to `NoopEventSink` when absent.\n\t */\n\tevents?: IEventSink;\n\n\t/**\n\t * Optional — only adapters whose schema migrates out-of-band (Supabase:\n\t * `supabase db push` is a manual operator step) need this. Boot health calls\n\t * it and drives `/api/health` to 503 when the database is behind the app,\n\t * so schema skew surfaces as a health check instead of per-request store errors.\n\t *\n\t * MUST NOT throw: report failure via `ok: false`.\n\t */\n\tverifySchemaVersion?(): Promise<SchemaVersionReport>;\n\n\t/**\n\t * Idempotently registers a user in the data layer. Called by `hooks.server.ts`\n\t * after `verifyToken` succeeds, so the data layer always has a row for the\n\t * authenticated user regardless of which auth provider issued the ID.\n\t *\n\t * Adapters with a DB-side trigger that auto-seeds on auth signup (Supabase)\n\t * make this a no-op. Adapters owning a separate user-data table without a\n\t * trigger (local-provider) upsert here.\n\t *\n\t * MUST be safe to call concurrently and on every request. MUST NOT throw on\n\t * a duplicate userId.\n\t */\n\tensureUser(ctx: RequestContext, userId: string): Promise<void>;\n\n\t/**\n\t * Cascade + erasure hook called after the auth provider deletes a user.\n\t * Removes or anonymizes data-layer rows tied to that user.\n\t *\n\t * Most user-owned rows die via FK cascade / `set null` against `auth.users`\n\t * (Supabase) or explicit membership cleanup (local). Some personal data is\n\t * NOT reachable by those FKs and MUST be scrubbed here:\n\t * - audit rows keyed by a plain-text `actor_id` (no FK),\n\t * - invites addressed to the user's `email`, and that email embedded in\n\t * `invite.created` audit payloads,\n\t * - `solve_metrics`, deliberately not FK-cascaded — anonymized (actor\n\t * tombstoned), not deleted.\n\t *\n\t * `opts.email` is the deleted user's email; the CALLER must capture it\n\t * BEFORE `deleteUser` runs (the auth user is already gone by the time this\n\t * hook fires). When absent, email-keyed scrubs are skipped.\n\t *\n\t * MUST tolerate a missing user and missing rows (idempotent — caller may retry).\n\t */\n\tonUserDeleted(ctx: RequestContext, userId: string, opts?: UserErasureOptions): Promise<void>;\n\n\t/**\n\t * Deletes audit events and solve metrics recorded before the given cutoffs.\n\t * Absent on a provider that keeps neither. MUST be idempotent: a janitor\n\t * calls it on a timer and retries after a failure.\n\t */\n\tpurgeExpired?(ctx: RequestContext, cutoffs: RetentionCutoffs): Promise<PurgeResult>;\n}\n\n/** An omitted cutoff keeps that table whole. */\nexport interface RetentionCutoffs {\n\tauditEventsBefore?: Date;\n\tsolveMetricsBefore?: Date;\n}\n\n/** Rows deleted per table. */\nexport interface PurgeResult {\n\tauditEvents: number;\n\tsolveMetrics: number;\n}\n","/** Alphabet of one storage path segment, as regex source. Covers GUIDs and sanitized refs. */\nexport const SAFE_SEGMENT = String.raw`[A-Za-z0-9._-]+`;\n\nconst SAFE_SEGMENT_ONLY = new RegExp(`^${SAFE_SEGMENT}$`);\n\n/**\n * Blocks traversal, separators, NUL and empty segments, so a malicious id can't\n * escape its prefix. The alphabet admits `.` and `..`, so those need their own check.\n */\nexport function assertSafeKey(value: string, label: string): void {\n\tif (!value || !SAFE_SEGMENT_ONLY.test(value) || value === '.' || value === '..') {\n\t\tthrow new Error(`Unsafe ${label}: ${JSON.stringify(value)}`);\n\t}\n}\n","import { assertSafeKey } from '../storage/safeKey.js';\nimport type { DefinitionFileExt } from './types.js';\n\nfunction prefix(guid: string): string {\n\tassertSafeKey(guid, 'guid');\n\treturn `definitions/${guid}/`;\n}\n\nexport const definitionPaths = {\n\tversion: (guid: string, versionNumber: number, ext: DefinitionFileExt) => {\n\t\tconst dir = prefix(guid);\n\t\tif (!Number.isInteger(versionNumber) || versionNumber < 1) {\n\t\t\tthrow new Error(`Unsafe versionNumber: ${versionNumber}`);\n\t\t}\n\t\treturn `${dir}versions/v${versionNumber}.${ext}`;\n\t},\n\timage: (guid: string) => `${prefix(guid)}cover.webp`,\n\tprefix\n} as const;\n","import type { ApiTokenRevokeReason } from '../apiTokens/types.js';\n\ntype DomainEventBody =\n\t| { type: 'org.created'; orgId: string; actorId: string }\n\t| { type: 'org.deleted'; orgId: string; actorId: string }\n\t| { type: 'org_member.added'; orgId: string; userId: string; actorId: string }\n\t| { type: 'org_member.removed'; orgId: string; userId: string; actorId: string }\n\t// Offboarding that left projects with no owner. Removal doesn't wait for a new\n\t// owner, so this event is the only signal that someone needs to reclaim them.\n\t| {\n\t\t\ttype: 'org_member.removed_orphaning_projects';\n\t\t\torgId: string;\n\t\t\tuserId: string;\n\t\t\tprojectIds: readonly string[];\n\t\t\tactorId: string;\n\t }\n\t| {\n\t\t\ttype: 'org_member.role_changed';\n\t\t\torgId: string;\n\t\t\tuserId: string;\n\t\t\trole: string;\n\t\t\tactorId: string;\n\t }\n\t| {\n\t\t\ttype: 'org_member.permissions_changed';\n\t\t\torgId: string;\n\t\t\tuserId: string;\n\t\t\tpermissions: readonly string[];\n\t\t\tactorId: string;\n\t }\n\t| { type: 'project.created'; projectId: string; orgId: string; actorId: string }\n\t| { type: 'project.deleted'; projectId: string; actorId: string }\n\t| { type: 'project_member.added'; projectId: string; userId: string; actorId: string }\n\t// Org leadership forcing its way into a project it holds no membership in.\n\t// Distinct from `project_member.added` because the two are otherwise\n\t// indistinguishable in the log, and the escalation is permitted precisely\n\t// on the strength of being auditable afterwards.\n\t| {\n\t\t\ttype: 'project.reclaimed';\n\t\t\tprojectId: string;\n\t\t\torgId: string;\n\t\t\tactorId: string;\n\t\t\tpriorVisibility: string;\n\t }\n\t| { type: 'project_member.removed'; projectId: string; userId: string; actorId: string }\n\t| {\n\t\t\ttype: 'project_member.role_changed';\n\t\t\tprojectId: string;\n\t\t\tuserId: string;\n\t\t\trole: string;\n\t\t\tactorId: string;\n\t }\n\t| { type: 'definition.created'; definitionId: string; projectId: string; actorId: string }\n\t| { type: 'definition.deleted'; definitionId: string; actorId: string }\n\t| { type: 'definition.published'; definitionId: string; versionId: string; actorId: string }\n\t| {\n\t\t\ttype: 'definition_version.created';\n\t\t\tversionId: string;\n\t\t\tdefinitionId: string;\n\t\t\tactorId: string;\n\t }\n\t| { type: 'definition_version.deleted'; versionId: string; actorId: string }\n\t| { type: 'share_link.minted'; linkId: string; definitionId: string; actorId: string }\n\t| { type: 'share_link.revoked'; linkId: string; actorId: string }\n\t| {\n\t\t\ttype: 'invite.created';\n\t\t\tinviteId: string;\n\t\t\torgId: string;\n\t\t\t/** Plain text, unlike every other identifier here — redacted on erasure via `redact_audit_event_email`. */\n\t\t\temail: string;\n\t\t\tactorId: string;\n\t }\n\t| { type: 'invite.accepted'; inviteId: string; orgId: string; userId: string; actorId: string }\n\t| { type: 'invite.revoked'; inviteId: string; orgId: string; actorId: string }\n\t// Ids only: the token name is free text people fill with personal detail.\n\t| {\n\t\t\ttype: 'api_token.created';\n\t\t\tapiTokenId: string;\n\t\t\torgId: string;\n\t\t\tuserId: string;\n\t\t\tactorId: string;\n\t }\n\t| {\n\t\t\ttype: 'api_token.revoked';\n\t\t\tapiTokenId: string;\n\t\t\torgId: string;\n\t\t\treason: ApiTokenRevokeReason;\n\t\t\tactorId: string;\n\t }\n\t// Platform scope. `instance_admin` reaches every tenant's data, so a change\n\t// to it is the one grant whose history has to survive the admin who made it —\n\t// including the self-elevate/act/revoke sequence, which leaves no other trace.\n\t| { type: 'user.created'; userId: string; actorId: string }\n\t| { type: 'user.deleted'; userId: string; actorId: string }\n\t| { type: 'user.disabled'; userId: string; actorId: string }\n\t| {\n\t\t\ttype: 'platform_permissions.changed';\n\t\t\tuserId: string;\n\t\t\t/** Post-change set. The prior set is not recorded — read the preceding event of this type. */\n\t\t\tpermissions: readonly string[];\n\t\t\tactorId: string;\n\t }\n\t// `started` is emitted by the process that launches the update; the app\n\t// restarts mid-update, so the terminal event comes from post-restart\n\t// reconciliation of the persisted update log, not the launching process.\n\t| { type: 'system.update.started'; channel: string; fromVersion?: string; actorId: string }\n\t| {\n\t\t\ttype: 'system.update.finished';\n\t\t\tfromVersion?: string;\n\t\t\ttoVersion?: string;\n\t\t\tdetail?: string;\n\t\t\tactorId: string;\n\t }\n\t| {\n\t\t\ttype: 'system.update.rolled_back';\n\t\t\tfromVersion?: string;\n\t\t\ttoVersion?: string;\n\t\t\tdetail?: string;\n\t\t\tactorId: string;\n\t }\n\t| {\n\t\t\ttype: 'system.update.failed';\n\t\t\tfromVersion?: string;\n\t\t\ttoVersion?: string;\n\t\t\tdetail?: string;\n\t\t\tactorId: string;\n\t };\n\n/**\n * `tokenId` is set on any event written during an API-token request, so a\n * key's actions can be told apart from the same person's browser actions.\n * Spread {@link actorOf} rather than setting it by hand.\n */\nexport type DomainEvent = DomainEventBody & { tokenId?: string };\n\nexport type DomainEventType = DomainEvent['type'];\n\n/**\n * What every event a sink accepts carries. A host writes its own events beside Selva's\n * through an `IEventSink<DomainEvent | HostEvent>`, which still satisfies Selva's\n * `IEventSink`. Prefix host `type`s so they can't collide with a later Selva event.\n */\nexport interface BaseEvent {\n\ttype: string;\n\tactorId: string;\n\ttokenId?: string;\n}\n\n/**\n * A durable sink (e.g. Supabase `audit_events.event_version`) stamps every row\n * with this so a reader dispatches on an explicit version instead of\n * inferring the shape. Bump when the union's persisted form changes in a\n * non-additive way.\n */\nexport const AUDIT_EVENT_VERSION = 1;\n\nexport interface IEventSink<E extends BaseEvent = DomainEvent> {\n\t/**\n\t * Stores call this AFTER a successful mutation; a failed write does not\n\t * emit.\n\t *\n\t * MUST NOT throw — an exception here would surface as a failed write even\n\t * though the mutation already committed. Implementations must catch\n\t * network errors, queue overflows, and other failures internally and log\n\t * them; the caller only ever sees a fulfilled promise.\n\t *\n\t * MAY be fire-and-forget: the contract is best-effort durable recording,\n\t * not synchronous persistence. Adapters that queue and flush\n\t * asynchronously are fine as long as they preserve event ordering per\n\t * `actorId`.\n\t */\n\temit(event: E): Promise<void>;\n}\n\n/**\n * `ctx.userId === ''` is the `SYSTEM_CONTEXT` convention for a server-internal\n * caller (bootstrap, janitors, migrations), which resolves to `'system'` here.\n */\nexport function actorFrom(ctx: {\n\tuserId: string;\n\t/** @deprecated Never read: an empty `userId` alone marks a system caller. */\n\tsystem?: boolean;\n}): string {\n\treturn ctx.userId || 'system';\n}\n\n/** `actorId` plus, for an API-token request, `tokenId`. Spread into an event. */\nexport function actorOf(ctx: {\n\tuserId: string;\n\t/** @deprecated Never read: an empty `userId` alone marks a system caller. */\n\tsystem?: boolean;\n\tapiScope?: { tokenId: string };\n}): { actorId: string; tokenId?: string } {\n\tconst actorId = actorFrom(ctx);\n\treturn ctx.apiScope ? { actorId, tokenId: ctx.apiScope.tokenId } : { actorId };\n}\n\n/** Discards every event. Used when `SelvaConfig.events` is omitted. */\nexport class NoopEventSink<E extends BaseEvent = DomainEvent> implements IEventSink<E> {\n\tasync emit(_event: E): Promise<void> {}\n}\n","import { assertSafeKey } from '../storage/safeKey.js';\nimport type { OrgAssetKind } from './schemas.js';\n\nfunction prefix(id: string): string {\n\tassertSafeKey(id, 'orgId');\n\treturn `orgs/${id}/`;\n}\n\n/**\n * Every branding asset is stored as `.webp` (uploads go through the shared\n * transcoder), so the path per kind is fixed and a re-upload overwrites in\n * place via `IStorageProvider.put`'s upsert.\n *\n * Branding lives under `orgs/{id}/branding/` because it's a *public* asset\n * class — anyone, including logged-out viewers, may read a company logo.\n * `classifyAssetPath` / `ASSET_CLASSES` decide visibility from these prefixes.\n */\nexport const orgPaths = {\n\tasset: (id: string, kind: OrgAssetKind) => {\n\t\tassertSafeKey(kind, 'assetKind');\n\t\treturn `${prefix(id)}branding/${kind}.webp`;\n\t},\n\tprefix\n} as const;\n","import { assertNotShareContext, hasPermission, type RequestContext } from '../context.js';\nimport { ProviderError } from '../errors/index.js';\n\n// For `IPlatformPermissionStore` adapters whose backing store is too coarse to enforce\n// these themselves. Reading one row and reading many agree, and read access is not\n// authority: `set` stays `instance_admin`-only.\n\n/** May `ctx` read `userId`'s platform permissions? Throws `ProviderError(403)` if not. */\nexport function assertCanReadPermissions(ctx: RequestContext, userId: string): void {\n\tassertNotShareContext(ctx, 'read permissions');\n\tif (ctx.userId === userId || hasPermission(ctx, 'manage_instance_users')) return;\n\tthrow new ProviderError('Forbidden: cannot read another user’s permissions', 403);\n}\n\n/** May `ctx` read several users' platform permissions? Throws `ProviderError(403)` if not. */\nexport function assertCanReadPermissionsBatch(ctx: RequestContext): void {\n\tassertNotShareContext(ctx, 'read permissions');\n\tif (hasPermission(ctx, 'manage_instance_users')) return;\n\tthrow new ProviderError('Forbidden: instance admin or manage_instance_users required', 403);\n}\n\n/** May `ctx` change platform permissions? Throws `ProviderError(403)` if not. */\nexport function assertCanManagePermissions(ctx: RequestContext): void {\n\tassertNotShareContext(ctx, 'manage permissions');\n\tif (hasPermission(ctx, 'instance_admin')) return;\n\tthrow new ProviderError('Forbidden: instance admin required', 403);\n}\n","/**\n * Shared image-transcoding helper for `IStorageProvider` implementations.\n * Normalizes uploads to WebP (at most 1200px on either side, quality 85) so\n * storage, bandwidth, and the viewer path stay predictable.\n *\n * `sharp` is a dynamic import, not a hard dependency of this package —\n * providers that need transcoding install it themselves.\n */\n\nimport { ProviderError } from '../errors/index.js';\n\nexport const IMAGE_MAX_WIDTH = 1200;\nexport const IMAGE_WEBP_QUALITY = 85;\n\n// A small upload can decode to gigabytes or burn seconds of CPU: the size cap on\n// the request says nothing about either. 60 MP covers a phone camera's full frame.\nconst MAX_INPUT_PIXELS = 60_000_000;\n// Area alone lets a 1 x 59,000,000 strip through, which decodes past the timeout.\nconst MAX_INPUT_SIDE = 16_384;\nconst TRANSCODE_TIMEOUT_SECONDS = 10;\nexport const MAX_CONCURRENT_TRANSCODES = 2;\nexport const MAX_WAITING_TRANSCODES = 8;\n// Two worst-case transcodes ahead of a waiter; past that the client should retry.\nconst TRANSCODE_WAIT_MS = 2 * TRANSCODE_TIMEOUT_SECONDS * 1000;\n\n// librsvg can draw for minutes without sharp's timeout firing: a filter, nested\n// `<use>`, masks or markers, a fine dash pattern. A declared SVG has to be cheap\n// before it reaches sharp.\nconst SVG_MAX_BYTES = 1024 * 1024;\nconst SVG_MAX_ELEMENTS = 10_000;\n// Encodings that spell markup in plain ASCII bytes, so the checks can see it.\nconst SVG_ENCODINGS = new Set(['utf-8', 'us-ascii', 'iso-8859-1']);\n\ntype ImageFormat = 'jpeg' | 'png' | 'gif' | 'webp' | 'tiff' | 'svg';\n\nexport interface TranscodeResult {\n\tdata: Uint8Array;\n\tcontentType: string;\n\t/** Possibly-rewritten path (non-webp inputs become `.webp`). */\n\tpath: string;\n}\n\n/** True if the input is an image to process. The content type decides, unless it says nothing. */\nexport function isImageUpload(contentType: string | undefined, storagePath: string): boolean {\n\tconst type = mediaType(contentType);\n\tif (type && type !== 'application/octet-stream') {\n\t\treturn type.startsWith('image/');\n\t}\n\treturn /\\.(webp|png|jpe?g|gif|tif?f|svg)$/i.test(storagePath);\n}\n\n/**\n * Rewrites a path's extension to `.webp`; unchanged for non-image extensions.\n * SVG is rasterized like any other input, so no vector blob is ever\n * persisted — served bytes stay XSS-free without a sanitizer.\n */\nexport function toWebpPath(storagePath: string): string {\n\treturn storagePath.replace(/\\.(png|jpe?g|gif|tif?f|svg)$/i, '.webp');\n}\n\n/**\n * Transcodes images to WebP; passes non-images through unchanged, so\n * providers can call this unconditionally before `put`.\n *\n * Throws `ProviderError(422)` for bytes it won't process, `ProviderError(503)`\n * when too many transcodes are queued, and a plain error if `sharp` isn't\n * installed, which is a config problem rather than a bad upload.\n */\nexport async function transcodeImageIfNeeded(\n\tdata: Uint8Array,\n\tcontentType: string | undefined,\n\tstoragePath: string\n): Promise<TranscodeResult> {\n\tif (!isImageUpload(contentType, storagePath)) {\n\t\treturn { data, contentType: contentType ?? 'application/octet-stream', path: storagePath };\n\t}\n\n\tconst input = Buffer.from(data);\n\tconst format = checkFormat(input, contentType, storagePath);\n\tconst sharp = await loadSharp();\n\tconst compressed = await withTranscodeSlot(() => rasterize(sharp, input, format));\n\n\treturn {\n\t\tdata: new Uint8Array(compressed),\n\t\tcontentType: 'image/webp',\n\t\tpath: toWebpPath(storagePath)\n\t};\n}\n\nfunction mediaType(contentType: string | undefined): string {\n\treturn (contentType ?? '').split(';')[0].trim().toLowerCase();\n}\n\n/** Refuses what sharp should never parse, from the bytes alone. */\nfunction checkFormat(\n\tinput: Buffer,\n\tcontentType: string | undefined,\n\tstoragePath: string\n): ImageFormat {\n\tconst format = sniffFormat(input);\n\tif (!format) throw new ProviderError('Unsupported image format', 422);\n\tif (format === 'svg') {\n\t\t// SVG is the expensive format, so it has to be asked for: a route that only\n\t\t// checks the declared type must not let one in as a PNG.\n\t\tconst declared = mediaType(contentType) === 'image/svg+xml' || /\\.svg$/i.test(storagePath);\n\t\tif (!declared) throw new ProviderError('SVG content needs the image/svg+xml type', 422);\n\t\tcheckSvg(input);\n\t}\n\treturn format;\n}\n\nfunction sniffFormat(input: Buffer): ImageFormat | null {\n\tconst head = input.subarray(0, 12).toString('latin1');\n\tif (head.startsWith('\\xFF\\xD8\\xFF')) return 'jpeg';\n\tif (head.startsWith('\\x89PNG\\r\\n\\x1A\\n')) return 'png';\n\tif (head.startsWith('GIF87a') || head.startsWith('GIF89a')) return 'gif';\n\tif (head.startsWith('RIFF') && head.slice(8, 12) === 'WEBP') return 'webp';\n\tif (head.startsWith('II*\\0') || head.startsWith('MM\\0*')) return 'tiff';\n\tif (/^(?:\\xEF\\xBB\\xBF)?[\\t\\n\\r ]*</.test(input.subarray(0, 1024).toString('latin1')))\n\t\treturn 'svg';\n\treturn null;\n}\n\n/**\n * Refuses an SVG that could draw slowly, or pull in one that does: a `data:` URL\n * (librsvg follows it to another SVG or stylesheet) or an entity (which can spell\n * anything). librsvg decodes character references and CSS escapes, and joins\n * `<style>` text across comments and child elements, so the checks read the text\n * the same way.\n */\nfunction checkSvg(input: Buffer): void {\n\tconst refuse = (why: string) => new ProviderError(`SVG ${why}`, 422);\n\tif (input.length > SVG_MAX_BYTES) throw refuse(`is larger than ${SVG_MAX_BYTES / 1024} KB`);\n\tconst text = input.toString('latin1');\n\t// A NUL byte means UTF-16 or similar, where markup is not spelled in ASCII.\n\tif (input.includes(0) || !SVG_ENCODINGS.has(declaredEncoding(text))) {\n\t\tthrow refuse('must be UTF-8');\n\t}\n\tif (/<!ENTITY/i.test(text)) throw refuse('may not declare entities');\n\tlet elements = 0;\n\tfor (const _ of text.matchAll(/<[A-Za-z_:]/g)) {\n\t\tif (++elements > SVG_MAX_ELEMENTS) throw refuse(`has more than ${SVG_MAX_ELEMENTS} elements`);\n\t}\n\tfor (const seen of [unescapeSvg(text), unescapeSvg(textContent(text))]) {\n\t\tif (/filter/i.test(seen) || /<(?:[\\w.-]+:)?fe[A-Z]/.test(seen)) {\n\t\t\tthrow refuse('filters are not accepted');\n\t\t}\n\t\tif (/<(?:[\\w.-]+:)?use\\b/.test(seen) || /mask|marker|dasharray/i.test(seen)) {\n\t\t\tthrow refuse('<use>, masks, markers and dash patterns are not accepted');\n\t\t}\n\t\t// A URL parser drops tabs and newlines, so `da	ta:` is `data:`.\n\t\tif (/d[\\t\\n\\r]*a[\\t\\n\\r]*t[\\t\\n\\r]*a[\\t\\n\\r]*:/i.test(seen)) {\n\t\t\tthrow refuse('may not embed data: URLs');\n\t\t}\n\t}\n}\n\nfunction declaredEncoding(text: string): string {\n\tconst decl = /^(?:\\xEF\\xBB\\xBF)?<\\?xml[^>]*\\bencoding\\s*=\\s*[\"']([^\"']*)[\"']/.exec(text);\n\treturn decl ? decl[1].toLowerCase() : 'utf-8';\n}\n\nfunction unescapeSvg(text: string): string {\n\treturn text\n\t\t.replace(/&#(?:x([0-9a-f]+)|(\\d+));/gi, (_, hex: string | undefined, dec: string | undefined) =>\n\t\t\tcodePoint(hex ? parseInt(hex, 16) : Number(dec))\n\t\t)\n\t\t.replace(\n\t\t\t/\\\\(?:([0-9a-f]{1,6})[\\t\\n\\r ]?|([^\\n]))/gi,\n\t\t\t(_, hex: string | undefined, ch: string) => (hex ? codePoint(parseInt(hex, 16)) : ch)\n\t\t);\n}\n\nfunction codePoint(n: number): string {\n\treturn n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : '';\n}\n\n/** Character data only: comments, tags and processing instructions dropped, CDATA kept. */\nfunction textContent(text: string): string {\n\tlet out = '';\n\tlet i = 0;\n\t// indexOf, not a regex: an unterminated `<!--` would make a lazy regex quadratic.\n\twhile (i < text.length) {\n\t\tif (text.startsWith('<!--', i)) {\n\t\t\tconst end = text.indexOf('-->', i + 4);\n\t\t\ti = end < 0 ? text.length : end + 3;\n\t\t} else if (text.startsWith('<![CDATA[', i)) {\n\t\t\tconst end = text.indexOf(']]>', i + 9);\n\t\t\tout += text.slice(i + 9, end < 0 ? text.length : end);\n\t\t\ti = end < 0 ? text.length : end + 3;\n\t\t} else if (text[i] === '<') {\n\t\t\tconst end = text.indexOf('>', i + 1);\n\t\t\ti = end < 0 ? text.length : end + 1;\n\t\t} else {\n\t\t\tconst end = text.indexOf('<', i);\n\t\t\tout += text.slice(i, end < 0 ? text.length : end);\n\t\t\ti = end < 0 ? text.length : end;\n\t\t}\n\t}\n\treturn out;\n}\n\nasync function rasterize(sharp: SharpFn, input: Buffer, format: ImageFormat): Promise<Buffer> {\n\ttry {\n\t\t// Unlimited here: this only reads the header, and sharp's own limit would hide\n\t\t// the reason from the checks below.\n\t\tconst header = sharp(input, { limitInputPixels: false });\n\t\tconst meta = await header.metadata();\n\t\tif (meta.format !== format) {\n\t\t\tthrow new ProviderError(`Unsupported image format: ${meta.format}`, 422);\n\t\t}\n\t\tconst { width = 0, height = 0 } = meta;\n\t\tif (width > MAX_INPUT_SIDE || height > MAX_INPUT_SIDE) {\n\t\t\tthrow new ProviderError(`Image is more than ${MAX_INPUT_SIDE} pixels on a side`, 422);\n\t\t}\n\t\tif (width * height > MAX_INPUT_PIXELS) {\n\t\t\tthrow new ProviderError('Image has too many pixels', 422);\n\t\t}\n\t\treturn await sharp(input, { limitInputPixels: MAX_INPUT_PIXELS })\n\t\t\t.autoOrient()\n\t\t\t.resize({\n\t\t\t\twidth: IMAGE_MAX_WIDTH,\n\t\t\t\theight: IMAGE_MAX_WIDTH,\n\t\t\t\tfit: 'inside',\n\t\t\t\twithoutEnlargement: true\n\t\t\t})\n\t\t\t.webp({ quality: IMAGE_WEBP_QUALITY })\n\t\t\t.timeout({ seconds: TRANSCODE_TIMEOUT_SECONDS })\n\t\t\t.toBuffer();\n\t} catch (err) {\n\t\tif (err instanceof ProviderError) throw err;\n\t\t// libvips words it \"timeout: 40% complete\".\n\t\tif (err instanceof Error && /^timeout:/m.test(err.message)) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`The image took more than ${TRANSCODE_TIMEOUT_SECONDS} seconds to process`,\n\t\t\t\t422\n\t\t\t);\n\t\t}\n\t\tthrow new ProviderError('The image could not be read', 422);\n\t}\n}\n\nlet activeTranscodes = 0;\nconst waitingTranscodes: (() => void)[] = [];\n\n/**\n * Runs `fn` when a slot is free. A finishing transcode hands its slot straight to\n * the next. Throws `ProviderError(503)` when the queue is full or the wait runs out.\n */\nexport async function withTranscodeSlot<T>(fn: () => Promise<T>): Promise<T> {\n\tif (activeTranscodes < MAX_CONCURRENT_TRANSCODES) {\n\t\tactiveTranscodes += 1;\n\t} else {\n\t\tawait waitForSlot();\n\t}\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\tconst next = waitingTranscodes.shift();\n\t\tif (next) next();\n\t\telse activeTranscodes -= 1;\n\t}\n}\n\nfunction waitForSlot(): Promise<void> {\n\tconst busy = () =>\n\t\tnew ProviderError('Too many images are being processed. Try again shortly.', 503);\n\tif (waitingTranscodes.length >= MAX_WAITING_TRANSCODES) return Promise.reject(busy());\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\twaitingTranscodes.splice(waitingTranscodes.indexOf(start), 1);\n\t\t\treject(busy());\n\t\t}, TRANSCODE_WAIT_MS);\n\t\tconst start = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve();\n\t\t};\n\t\twaitingTranscodes.push(start);\n\t});\n}\n\ntype SharpFn = typeof import('sharp').default;\n// Not a literal: a browser build of the root barrel would try to resolve it.\nconst SHARP_MODULE = 'sharp';\nlet cachedSharp: SharpFn | null = null;\n\nasync function loadSharp(): Promise<SharpFn> {\n\tif (cachedSharp) return cachedSharp;\n\ttry {\n\t\tconst mod = (await import(/* @vite-ignore */ SHARP_MODULE)) as unknown as { default: SharpFn };\n\t\t// A bundler can hand back the CommonJS export itself rather than a namespace.\n\t\tcachedSharp = mod.default ?? (mod as unknown as SharpFn);\n\t\treturn cachedSharp;\n\t} catch (err) {\n\t\tthrow new Error(\n\t\t\t'Image transcoding requires `sharp` to be installed. Add it as a dependency in your provider package.',\n\t\t\t{ cause: err }\n\t\t);\n\t}\n}\n","import { ALL_ORG_ASSET_KINDS } from '../organizations/schemas.js';\nimport { UUID_REGEX } from '../definitions/schemas.js';\nimport { SAFE_SEGMENT } from './safeKey.js';\n\n/**\n * How a stored asset is allowed to be read. A property of the asset *class*\n * (its path prefix), never of the individual file — a new asset type is one\n * entry in {@link ASSET_CLASSES} rather than a new route.\n *\n * - `public` — anyone, including logged-out visitors (branding: logo, favicon).\n * - `project` — members of the owning project only; route resolves the\n * definition guid to its project (cover images, per-definition blobs).\n */\nexport type AssetVisibility = 'public' | 'project';\n\n/**\n * What scope id the route must authorize against. `none` for public assets\n * (no scope to check); `project` carries the guid extracted from the path.\n */\nexport type AssetScope = 'none' | 'project';\n\nexport interface AssetClass {\n\t/** Stable identifier — for logging and tests, not user-facing. */\n\treadonly id: string;\n\treadonly visibility: AssetVisibility;\n\treadonly scope: AssetScope;\n\t/**\n\t * Anchored matcher for this class's storage paths. Capture group 1 (when\n\t * present) is the scope id the route authorizes against.\n\t */\n\treadonly pattern: RegExp;\n}\n\nexport interface AssetMatch {\n\treadonly class: AssetClass;\n\t/** The scope id from the path, or null for `scope: 'none'` classes. */\n\treadonly scopeId: string | null;\n}\n\n// Built from the schema enum so a new branding kind extends this pattern automatically.\nconst BRANDING_KINDS = ALL_ORG_ASSET_KINDS.join('|');\n\nconst GUID = UUID_REGEX.source.slice(1, -1);\n\n/**\n * The closed registry of servable asset classes. Patterns are mutually\n * exclusive by prefix, order doesn't matter. Anything matching no class is\n * unservable (the route 404s) — default-deny, so a new blob type is opt-in.\n */\nexport const ASSET_CLASSES: readonly AssetClass[] = [\n\t{\n\t\tid: 'org-branding',\n\t\tvisibility: 'public',\n\t\tscope: 'none',\n\t\tpattern: new RegExp(\n\t\t\tString.raw`^orgs\\/(${SAFE_SEGMENT})\\/branding\\/(?:${BRANDING_KINDS})\\.webp$`\n\t\t)\n\t},\n\t{\n\t\tid: 'definition-cover',\n\t\tvisibility: 'project',\n\t\tscope: 'project',\n\t\t// `put` transcodes every cover and `definitionPaths.image` names it, so this is\n\t\t// the only cover that can exist.\n\t\tpattern: new RegExp(String.raw`^definitions\\/(${GUID})\\/cover\\.webp$`, 'i')\n\t}\n];\n\n/**\n * Rejects traversal, empty, or backslash segments before a path can match a\n * class. The permissive segment alphabet (`[A-Za-z0-9._-]+`) admits a bare\n * `.` or `..` as a whole segment, which would otherwise let\n * `orgs/../branding/logo.webp` classify as public branding with `..`\n * captured as the orgId. Mirrors `assertSafeKey` on the write side, so a path\n * that can't be written can't be read either.\n */\nfunction hasUnsafeSegment(storagePath: string): boolean {\n\tif (storagePath.includes('\\\\')) return true;\n\tfor (const segment of storagePath.split('/')) {\n\t\tif (segment === '' || segment === '.' || segment === '..') return true;\n\t}\n\treturn false;\n}\n\n/**\n * Classifies a storage path into its asset class and scope id, or null when\n * no class matches (or the path is unsafe). `getPublicUrl` and the serving\n * route both consult this so URL generation and authorization never drift\n * apart.\n *\n * `scopeId` is null for `scope: 'none'` classes even when the pattern\n * captures an id (e.g. `org-branding` captures orgId but is public).\n */\nexport function classifyAssetPath(storagePath: string): AssetMatch | null {\n\tif (hasUnsafeSegment(storagePath)) return null;\n\tfor (const cls of ASSET_CLASSES) {\n\t\tconst m = cls.pattern.exec(storagePath);\n\t\tif (!m) continue;\n\t\treturn { class: cls, scopeId: cls.scope === 'none' ? null : (m[1] ?? null) };\n\t}\n\treturn null;\n}\n","/**\n * Appends a cache-busting token to a stored-asset URL.\n *\n * `IStorageProvider.put` upserts, so a re-upload keeps the same storage path\n * and public URL — a browser/CDN caching the old bytes under that URL keeps\n * serving them past the TTL, which reads as \"the replace didn't work.\"\n * Appending a token that only changes with the content gives each version a\n * distinct URL, forcing a refetch, while unchanged assets stay cached.\n *\n * Generic over asset kind — pass whatever tracks the blob's version (content\n * hash, `updatedAt`, a counter). The serving route ignores the query string\n * (SvelteKit's `[...path]` param never includes it), so this needs no route\n * support.\n *\n * Empty/whitespace tokens return the URL unchanged, so a missing token\n * degrades to \"no cache-bust\" rather than `?v=`.\n */\nexport function withCacheBust(url: string, token: string | number | undefined | null): string {\n\tif (token === undefined || token === null) return url;\n\tconst value = String(token).trim();\n\tif (value === '') return url;\n\tconst hash = url.indexOf('#');\n\tconst base = hash === -1 ? url : url.slice(0, hash);\n\tconst fragment = hash === -1 ? '' : url.slice(hash);\n\tconst sep = base.includes('?') ? '&' : '?';\n\treturn `${base}${sep}v=${encodeURIComponent(value)}${fragment}`;\n}\n","/** How many entries `recordRun` keeps per user. */\nexport const MAX_RECENT_RUNS = 20;\n\nexport interface RecentRun {\n\tdefinitionId: string;\n\trunId: string;\n\tdefinitionName: string;\n\ttimestamp: string;\n}\n\n/** Mutable per-user profile state, owned by `IUserProfileStore`. */\nexport interface UserProfile {\n\tuserId: string;\n\tdisplayName?: string;\n\t/** Definition GUIDs pinned by this user. */\n\tstarredDefinitions: string[];\n\t/** Last N solve runs, newest first. Capped by the adapter. */\n\trecentRuns: RecentRun[];\n}\n\nexport function emptyProfile(userId: string): UserProfile {\n\treturn { userId, starredDefinitions: [], recentRuns: [] };\n}\n","import { assertNotShareContext, hasPermission, type RequestContext } from '../context.js';\nimport { ProviderError } from '../errors/index.js';\n\n/**\n * For provider authors: may `ctx` read or change `userId`'s profile? Throws\n * `ProviderError(403)` if not.\n */\nexport function assertCanAccessProfile(ctx: RequestContext, userId: string): void {\n\tassertNotShareContext(ctx, 'access user profiles');\n\tif (ctx.userId === userId || hasPermission(ctx, 'instance_admin')) return;\n\tthrow new ProviderError('Forbidden: cannot access another user’s profile', 403);\n}\n","import type { RequestContext } from '../context.js';\n\n/**\n * Audit-field stamping helpers. Every mutable entity carries `createdAt` /\n * `createdBy` / `updatedAt` / `updatedBy` / `deletedAt`.\n *\n * `createdAt` / `createdBy` are stamped by the consumer when constructing\n * the record. `updatedAt` / `updatedBy` and `deletedAt` are stamped by\n * stores on every mutation.\n *\n * `fallbackActor` is used when `ctx.userId` is empty (system contexts) —\n * pass the record's prior `updatedBy` (or `ownerId` / `createdBy` if unset).\n */\n\nconst nowIso = (): string => new Date().toISOString();\n\nexport interface AuditUpdate {\n\tupdatedAt: string;\n\tupdatedBy: string;\n}\n\nexport function auditUpdate(\n\tctx: RequestContext,\n\tfallbackActor: string | null | undefined\n): AuditUpdate {\n\treturn {\n\t\tupdatedAt: nowIso(),\n\t\tupdatedBy: ctx.userId || fallbackActor || ''\n\t};\n}\n\nexport interface AuditSoftDelete extends AuditUpdate {\n\tdeletedAt: string;\n}\n\nexport function auditSoftDelete(\n\tctx: RequestContext,\n\tfallbackActor: string | null | undefined\n): AuditSoftDelete {\n\tconst now = nowIso();\n\treturn {\n\t\tdeletedAt: now,\n\t\tupdatedAt: now,\n\t\tupdatedBy: ctx.userId || fallbackActor || ''\n\t};\n}\n","import type { RequestContext } from '../context.js';\n\n/**\n * Why a solve did not produce a usable result. `ok` means the solve completed\n * (it may still carry Grasshopper runtime errors — see `errorCount`). Each\n * kind mirrors an HTTP status the compute route already distinguishes.\n */\nexport type SolveFailureKind =\n\t/** Solve completed; the response was returned to the client. */\n\t| 'ok'\n\t/** Scheduler deadline exceeded (HTTP 504). */\n\t| 'timeout'\n\t/** Client disconnected mid-solve; the request signal aborted (HTTP 499). */\n\t| 'client_abort'\n\t/** Rejected by the per-key rate limiter before solving (HTTP 429). */\n\t| 'rate_limited'\n\t/** Share-link solve cap reached before solving (HTTP 429). */\n\t| 'share_cap'\n\t/** Result exceeded the response size limit (HTTP 413). */\n\t| 'too_large'\n\t/** The compute server refused the request body as too large, before solving (HTTP 413). */\n\t| 'request_too_large'\n\t/**\n\t * Rejected by scheduler backpressure — the per-server queue was full, or the\n\t * solve sat queued past its wait deadline, so it never executed\n\t * (HTTP 503 + Retry-After). Distinct from `compute_error`: no compute ran.\n\t */\n\t| 'shed'\n\t/** Compute server unreachable or the solve threw for any other reason. */\n\t| 'compute_error';\n\n/**\n * One solve's timing and outcome, recorded once per attempt — including\n * attempts rejected before `scheduler.solve()` runs (rate limit, share cap).\n */\nexport interface SolveMetric {\n\t/** Definition the solve ran against. `local:<guid>` or a remote URL. */\n\tdefinitionUrl: string;\n\t/** Local definition id (the `local:` guid), or null for remote-URL solves. */\n\tdefinitionId: string | null;\n\t/** Exact version solved, or null for remote-URL solves and attempts rejected before the version resolved. */\n\tversionId: string | null;\n\t/** Channel solved, mirroring the compute request. */\n\tchannel: 'live' | 'draft';\n\t/** Org whose compute pool served the solve, or null for remote definitions. */\n\torgId: string | null;\n\t/**\n\t * Wall time around the Rhino.Compute solve call only — excludes definition\n\t * loading, auth, schema work, and result serialization. 0 if never started.\n\t */\n\tdurationMs: number;\n\t/** Must equal `failureKind === 'ok'`; readers should prefer `failureKind`. */\n\tok: boolean;\n\t/** Why the solve did not return a result; `'ok'` when it did. */\n\tfailureKind: SolveFailureKind;\n\t/**\n\t * Grasshopper runtime errors in the solve response. A solve can be `ok`\n\t * yet still report component-level errors. 0 when no response returned.\n\t */\n\terrorCount: number;\n\t/** Grasshopper runtime warnings in the solve response. */\n\twarningCount: number;\n}\n\n/**\n * Sink for per-solve timing telemetry, called once per attempt after the\n * solve resolves or rejects.\n *\n * MUST NOT throw — recording is best-effort and sits on the hot path of every\n * solve. Implementations catch and log their own failures.\n */\nexport interface ISolveMetricSink {\n\trecord(ctx: RequestContext, metric: SolveMetric): Promise<void>;\n}\n\n/** Default `ISolveMetricSink` — discards every metric. Used when `SelvaConfig.solveMetrics` is omitted. */\nexport class NoopSolveMetricSink implements ISolveMetricSink {\n\tasync record(_ctx: RequestContext, _metric: SolveMetric): Promise<void> {}\n}\n","// Configurable provider wiring — the reusable core of an app's composition\n// root.\n//\n// Provider IMPLEMENTATIONS are not bundled: the caller passes a\n// `ProviderRegistry` mapping choice names (the `SELVA_*_PROVIDER` env values)\n// to `fromEnv`-style factories. That keeps this package free of dependencies on\n// `@selvajs/local-provider` / `@selvajs/supabase-provider` — a consuming app\n// registers exactly the providers it ships.\n//\n// Two wiring modes:\n//\n// Default — providers picked from env vars (SELVA_AUTH_PROVIDER etc.) via the\n// registry. New deployments need only a .env file.\n//\n// Override — `configPath` points at an external `selva.config.js` (absolute\n// or CWD-relative), loaded dynamically at boot, replacing the env-driven\n// wiring entirely. It must be an actual `.js` file — there's no TS compiler\n// at runtime.\n\nimport { pathToFileURL } from 'node:url';\nimport { resolve as resolvePath } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport type {\n\tIAuthProvider,\n\tIDataProvider,\n\tIStorageProvider,\n\tISolveMetricSink,\n\tSelvaBranding,\n\tSelvaConfig,\n\tSelvaConfigFactory,\n\tSelvaFlags,\n\tTenancyMode\n} from '@selvajs/platform';\nimport { isFlagEnabled, NoopSolveMetricSink, NoopLogger, type ILogger } from '@selvajs/platform';\nimport { readBool, type EnvRecord } from '../compute/limits.js';\n\nexport type ProviderFactory<T> = (env: EnvRecord) => T;\n\n/** Keyed by the lowercased `SELVA_{AUTH,DATA,STORAGE}_PROVIDER` value. */\nexport interface ProviderRegistry {\n\tauth: Record<string, ProviderFactory<IAuthProvider>>;\n\tdata: Record<string, ProviderFactory<IDataProvider>>;\n\tstorage: Record<string, ProviderFactory<IStorageProvider>>;\n}\n\nexport interface CreateSelvaProvidersOptions {\n\tregistry: ProviderRegistry;\n\t/** Fallback choice per slot when the env var is unset. Default: `'local'`. */\n\tdefaults?: Partial<Record<'auth' | 'data' | 'storage', string>>;\n\t/**\n\t * Override module (absolute or CWD-relative); its default export is a\n\t * `SelvaConfig` or a factory.\n\t */\n\tconfigPath?: string;\n\t/**\n\t * Boot-summary sink, called once on first `resolve()` — for callers that want\n\t * the rendered string. Default: none, and the summary goes to `logger`\n\t * instead, so this library never writes to stdout unbidden.\n\t */\n\tonBoot?: (summary: string) => void;\n\t/**\n\t * Receives the boot summary as fields when `onBoot` is unset. Defaults to\n\t * `NoopLogger`.\n\t */\n\tlogger?: ILogger;\n}\n\nexport interface SelvaProviderRuntime {\n\t/**\n\t * Memoized wiring. The first call instantiates providers from env and throws\n\t * if a required secret is missing, or if `ENABLE_PLATFORM_PROJECTS` is on\n\t * over a grant store marked `unsupported` — never call it at build time.\n\t */\n\tresolve(): SelvaConfig;\n\t/** Defaults to `'single'` when the config omits it. */\n\ttenancy(): TenancyMode;\n\t/** Every field defaulted, so the UI never null-checks. */\n\tbranding(): Required<SelvaBranding>;\n\t/** Omitted flags resolve to false. */\n\tflag(name: keyof SelvaFlags): boolean;\n\t/** `NoopSolveMetricSink` when the config omits one. */\n\tsolveMetricSink(): ISolveMetricSink;\n}\n\n// Every SelvaFlags key, read from `SELVA_FLAG_<KEY>`. The `satisfies` plus the\n// exhaustiveness check below make adding a platform flag without listing it\n// here a compile error.\nconst FLAG_KEYS = [\n\t'ALLOW_CROSS_ORG_PUBLIC',\n\t'ALLOW_ORG_COMPUTE_OVERRIDE',\n\t'ALLOW_ORG_CREATION',\n\t'ENABLE_PLATFORM_PROJECTS',\n\t'ENABLE_SHARING'\n] as const satisfies readonly (keyof SelvaFlags)[];\n\ntype AllFlagsListed =\n\tExclude<keyof SelvaFlags, (typeof FLAG_KEYS)[number]> extends never ? true : never;\n\nconst _allFlagsListed: AllFlagsListed = true;\n\nfunction pick<T>(\n\tenv: EnvRecord,\n\tenvVar: string,\n\tslot: Record<string, ProviderFactory<T>>,\n\tfallback: string\n): T {\n\tconst choice = (env[envVar] ?? fallback).toLowerCase();\n\tconst factory = slot[choice];\n\tif (!factory) {\n\t\tthrow new Error(`Unknown ${envVar}=\"${choice}\". Expected: ${Object.keys(slot).join(' | ')}.`);\n\t}\n\treturn factory(env);\n}\n\nfunction pickTenancy(env: EnvRecord): TenancyMode {\n\tconst choice = (env.SELVA_TENANCY ?? 'single').toLowerCase();\n\tif (choice !== 'single' && choice !== 'multi') {\n\t\tthrow new Error(`Unknown SELVA_TENANCY=\"${choice}\". Expected: single | multi.`);\n\t}\n\treturn choice;\n}\n\n/**\n * Supabase's data provider carries a `solveMetrics` sink built from its own\n * client bundle — reuse it so timings persist without a second client. Backends\n * with no metrics table return undefined, and `solveMetricSink()` falls back to\n * `NoopSolveMetricSink`.\n */\nfunction pickSolveMetrics(data: IDataProvider): ISolveMetricSink | undefined {\n\tconst candidate = (data as { solveMetrics?: unknown }).solveMetrics;\n\tif (candidate && typeof (candidate as { record?: unknown }).record === 'function') {\n\t\treturn candidate as ISolveMetricSink;\n\t}\n\treturn undefined;\n}\n\nfunction buildDefaultFactory(options: CreateSelvaProvidersOptions): SelvaConfigFactory {\n\tconst { registry, defaults } = options;\n\treturn (env) => {\n\t\tconst data = pick(env, 'SELVA_DATA_PROVIDER', registry.data, defaults?.data ?? 'local');\n\t\treturn {\n\t\t\ttenancy: pickTenancy(env),\n\t\t\tflags: Object.fromEntries(\n\t\t\t\tFLAG_KEYS.map((key) => [key, readBool(env, `SELVA_FLAG_${key}`, false)])\n\t\t\t),\n\t\t\tbranding: {\n\t\t\t\tname: env.SELVA_BRAND_NAME,\n\t\t\t\tcopyrightName: env.SELVA_BRAND_COPYRIGHT_NAME,\n\t\t\t\ttagline: env.SELVA_BRAND_TAGLINE,\n\t\t\t\tdescription: env.SELVA_BRAND_DESCRIPTION\n\t\t\t},\n\t\t\tauth: pick(env, 'SELVA_AUTH_PROVIDER', registry.auth, defaults?.auth ?? 'local'),\n\t\t\tdata,\n\t\t\tstorage: pick(env, 'SELVA_STORAGE_PROVIDER', registry.storage, defaults?.storage ?? 'local'),\n\t\t\tsolveMetrics: pickSolveMetrics(data)\n\t\t};\n\t};\n}\n\nasync function loadConfigSource(\n\toptions: CreateSelvaProvidersOptions\n): Promise<SelvaConfig | SelvaConfigFactory> {\n\tif (!options.configPath) {\n\t\treturn buildDefaultFactory(options);\n\t}\n\tconst abs = resolvePath(process.cwd(), options.configPath);\n\tif (!existsSync(abs)) {\n\t\tthrow new Error(\n\t\t\t`Config override path ${options.configPath} resolved to ${abs} which does not exist.`\n\t\t);\n\t}\n\t// @vite-ignore: a bundler must not pre-resolve this specifier at build time.\n\t// pathToFileURL keeps Windows absolute paths valid as ESM specifiers.\n\tconst mod = (await import(/* @vite-ignore */ pathToFileURL(abs).href)) as {\n\t\tdefault: SelvaConfig | SelvaConfigFactory;\n\t};\n\treturn mod.default;\n}\n\n/**\n * Loading the config source (default factory, or the `configPath` module) is\n * cheap and secret-free. The factory is deliberately NOT invoked here: that\n * runs the registry's `fromEnv` factories, which validate required secrets, so\n * calling it at import time would make merely building the app require a full\n * runtime env. Providers are instantiated on the first `resolve()`.\n */\nexport async function createSelvaProviders(\n\tenv: EnvRecord,\n\toptions: CreateSelvaProvidersOptions\n): Promise<SelvaProviderRuntime> {\n\tconst raw = await loadConfigSource(options);\n\tconst logger = options.logger ?? new NoopLogger();\n\n\tlet config: SelvaConfig | undefined;\n\tlet solveMetricSink: ISolveMetricSink | undefined;\n\n\tfunction resolve(): SelvaConfig {\n\t\tif (config) return config;\n\t\tconst candidate = typeof raw === 'function' ? raw(env) : raw;\n\t\tif (\n\t\t\tisFlagEnabled(candidate, 'ENABLE_PLATFORM_PROJECTS') &&\n\t\t\tcandidate.data.platformProjectGrants.unsupported\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`ENABLE_PLATFORM_PROJECTS is on, but ${candidate.data.constructor.name} cannot store ` +\n\t\t\t\t\t'platform-project grants. Turn SELVA_FLAG_ENABLE_PLATFORM_PROJECTS off.'\n\t\t\t);\n\t\t}\n\t\tconfig = candidate;\n\n\t\t// Boot summary so operators can confirm what got wired without grepping\n\t\t// env vars. Auth exposes a `name` field; data/storage adapters don't, so\n\t\t// their names come from the constructor.\n\t\tconst wiring = {\n\t\t\tcomponent: 'selva',\n\t\t\tauth: config.auth.name,\n\t\t\tdata: config.data.constructor.name,\n\t\t\tstorage: config.storage.constructor.name,\n\t\t\ttenancy: config.tenancy ?? 'single',\n\t\t\t...(options.configPath ? { configPath: options.configPath } : {})\n\t\t};\n\n\t\tif (options.onBoot) {\n\t\t\toptions.onBoot(\n\t\t\t\t`[selva] providers wired: ` +\n\t\t\t\t\t`auth=${wiring.auth} ` +\n\t\t\t\t\t`data=${wiring.data} ` +\n\t\t\t\t\t`storage=${wiring.storage} ` +\n\t\t\t\t\t`tenancy=${wiring.tenancy}` +\n\t\t\t\t\t(options.configPath ? ` config=${options.configPath}` : '')\n\t\t\t);\n\t\t} else {\n\t\t\tlogger.info('Providers wired', wiring);\n\t\t}\n\n\t\treturn config;\n\t}\n\n\treturn {\n\t\tresolve,\n\t\ttenancy: () => resolve().tenancy ?? 'single',\n\t\tbranding: () => {\n\t\t\tconst brand = resolve().branding ?? {};\n\t\t\tconst name = brand.name?.trim() || 'Selva';\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tcopyrightName: brand.copyrightName?.trim() || name,\n\t\t\t\ttagline: brand.tagline?.trim() || '',\n\t\t\t\tdescription:\n\t\t\t\t\tbrand.description?.trim() ||\n\t\t\t\t\t`Build and deploy interactive web applications powered by Grasshopper definitions with ${name}.`\n\t\t\t};\n\t\t},\n\t\tflag: (name) => isFlagEnabled(resolve(), name),\n\t\tsolveMetricSink: () => {\n\t\t\tif (!solveMetricSink) {\n\t\t\t\tsolveMetricSink = resolve().solveMetrics ?? new NoopSolveMetricSink();\n\t\t\t}\n\t\t\treturn solveMetricSink;\n\t\t}\n\t};\n}\n","import { timingSafeEqual, createHmac } from 'node:crypto';\n\nconst DEFAULT_MAX_AGE_MS = 8 * 60 * 60 * 1000;\n\n/**\n * Token format: base64url(userId + ':' + expiry) + '.' + hmac(payload)\n *\n * The userId is embedded so verifyToken can look up the live user record\n * (and therefore always reflect the current permissions, not stale ones\n * baked into the token at login time).\n */\nexport function signHmacToken(\n\tsecret: string,\n\tuserId: string,\n\tmaxAgeMs = DEFAULT_MAX_AGE_MS\n): string {\n\tconst expiry = Date.now() + maxAgeMs;\n\tconst payload = Buffer.from(`${userId}:${expiry}`).toString('base64url');\n\tconst sig = createHmac('sha256', secret).update(payload).digest('base64url');\n\treturn `${payload}.${sig}`;\n}\n\nexport interface HmacTokenPayload {\n\tuserId: string;\n\tvalid: boolean;\n}\n\n/**\n * Verify an HMAC token. Returns the userId if valid and unexpired, or\n * { valid: false } if the signature is wrong or the token has expired.\n */\nexport function verifyHmacToken(token: string, secret: string): HmacTokenPayload {\n\tconst dot = token.lastIndexOf('.');\n\tif (dot === -1) return { userId: '', valid: false };\n\n\tconst payload = token.slice(0, dot);\n\tconst sig = token.slice(dot + 1);\n\tconst expectedSig = createHmac('sha256', secret).update(payload).digest('base64url');\n\n\tconst a = Buffer.from(sig);\n\tconst b = Buffer.from(expectedSig);\n\tif (a.length !== b.length || !timingSafeEqual(a, b)) return { userId: '', valid: false };\n\n\tconst decoded = Buffer.from(payload, 'base64url').toString();\n\tconst colon = decoded.lastIndexOf(':');\n\tif (colon === -1) return { userId: '', valid: false };\n\n\tconst userId = decoded.slice(0, colon);\n\tconst expiry = parseInt(decoded.slice(colon + 1), 10);\n\tif (!Number.isFinite(expiry) || Date.now() >= expiry) return { userId: '', valid: false };\n\n\treturn { userId, valid: true };\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { randomUUID } from 'node:crypto';\n\nconst fileQueues = new Map<string, Promise<unknown>>();\n\n/**\n * Runs a read-modify-write of `filePath` alone in this process, so two writers\n * can't both start from the same snapshot and lose one's change.\n */\nexport function withFileLock<T>(filePath: string, fn: () => Promise<T>): Promise<T> {\n\t// Chain onto the tail however the previous write settled, so one rejection\n\t// can't wedge the queue.\n\tconst next = (fileQueues.get(filePath) ?? Promise.resolve()).then(fn, fn);\n\tconst tail = next.catch(() => {});\n\tfileQueues.set(filePath, tail);\n\tvoid tail.then(() => {\n\t\tif (fileQueues.get(filePath) === tail) fileQueues.delete(filePath);\n\t});\n\treturn next;\n}\n\n/** Returns `fallback` if the file doesn't exist. Other errors propagate. */\nexport async function readJsonFile<T>(filePath: string, fallback: T): Promise<T> {\n\ttry {\n\t\tconst raw = await fs.readFile(filePath, 'utf-8');\n\t\treturn JSON.parse(raw) as T;\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === 'ENOENT') return fallback;\n\t\tthrow err;\n\t}\n}\n\nconst RENAME_RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);\n\n/**\n * `rename` over a file another handle has open fails on Windows with EPERM, EACCES or\n * EBUSY until that handle closes, so a write racing a read would fail. Readers here\n * close fast; retry briefly, as graceful-fs does. POSIX never hits these codes.\n */\nexport async function renameReplacing(from: string, to: string): Promise<void> {\n\tfor (let attempt = 0; ; attempt++) {\n\t\ttry {\n\t\t\treturn await fs.rename(from, to);\n\t\t} catch (err) {\n\t\t\tconst code = (err as NodeJS.ErrnoException).code;\n\t\t\tif (attempt >= 20 || !code || !RENAME_RETRY_CODES.has(code)) throw err;\n\t\t\tawait new Promise((r) => setTimeout(r, Math.min(10 * (attempt + 1), 100)));\n\t\t}\n\t}\n}\n\n/**\n * Writes to a sibling temp file, then renames into place, so a crash mid-write\n * can't corrupt the target. The temp name is random per call: a shared name would\n * let one writer's rename pull the file out from under another. A read-modify-write\n * caller still needs {@link withFileLock}.\n *\n * Owner-only permissions are not optional here: this helper is the sole writer\n * for `auth-users.json` (email addresses + PBKDF2 password hashes) and\n * `compute.config.json`. Under a default umask those land 0644, and any other\n * local user or co-tenant service on the host can copy the hashes and crack\n * them offline. The mode goes on the temp file, not the target — `rename`\n * keeps the temp file's bits, so a post-rename `chmod` would leave a readable\n * window. No-op on Windows.\n */\nexport async function writeJsonFile<T>(filePath: string, data: T): Promise<void> {\n\tawait fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });\n\tconst tmp = `${filePath}.${randomUUID()}.tmp`;\n\ttry {\n\t\tawait fs.writeFile(tmp, JSON.stringify(data, null, '\\t'), { encoding: 'utf-8', mode: 0o600 });\n\t\tawait renameReplacing(tmp, filePath);\n\t} catch (err) {\n\t\tawait fs.rm(tmp, { force: true }).catch(() => {});\n\t\tthrow err;\n\t}\n}\n\n/**\n * A JSON file read once and kept in memory, where the provider is the sole writer\n * in a single process. Callers mutate what `get` returns, then pass it to `write`.\n */\nexport class CachedJsonFile<T> {\n\tprivate cache: T | null = null;\n\tprivate loading: Promise<T> | null = null;\n\n\tconstructor(\n\t\treadonly filePath: string,\n\t\tprivate readonly fallback: () => T\n\t) {}\n\n\t/** Concurrent first callers share one read, so they mutate the same object. */\n\tasync get(): Promise<T> {\n\t\tif (this.cache) return this.cache;\n\t\tthis.loading ??= readJsonFile<T>(this.filePath, this.fallback())\n\t\t\t.then((data) => {\n\t\t\t\tthis.cache = data;\n\t\t\t\treturn data;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tthis.loading = null;\n\t\t\t});\n\t\treturn this.loading;\n\t}\n\n\t/**\n\t * Writes run one at a time and stringify when their turn comes, so the newest\n\t * state lands last. A failed write drops the cache: it holds a change the disk\n\t * never took.\n\t */\n\tasync write(data: T): Promise<void> {\n\t\tthis.cache = data;\n\t\ttry {\n\t\t\tawait withFileLock(this.filePath, () => writeJsonFile(this.filePath, data));\n\t\t} catch (err) {\n\t\t\tthis.cache = null;\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n","import * as crypto from 'node:crypto';\nimport { randomUUID } from 'node:crypto';\nimport { ProviderError } from '@selvajs/platform';\nimport { CachedJsonFile } from '../data/fsJson.js';\n\n/**\n * Identity-only on-disk shape. Per-user app state (permissions, profile,\n * starred definitions, recent runs) lives in `user-data.json`, owned by\n * `LocalDataProvider`. The split lets `LocalAuthProvider` pair with any data\n * provider, and any auth provider pair with `LocalDataProvider`, without one\n * stepping on the other.\n */\nexport interface StoredAuthUser {\n\tid: string;\n\temail: string;\n\t/**\n\t * \"pbkdf2:sha256:<iterations>:<salt>:<hash>\", binary values base64url encoded.\n\t * Null for OAuth-only users (allowlisted email, no password stored).\n\t */\n\tpasswordHash: string | null;\n\tcreatedAt: string; // ISO 8601\n\t/** ISO 8601, most recent successful login. */\n\tlastLoginAt?: string;\n\t/** True means the provider refuses to authenticate this user. */\n\tdisabled?: boolean;\n}\n\n/** Debounce window for lastLoginAt writes — skip if prior stamp is newer than this. */\nconst LAST_LOGIN_DEBOUNCE_MS = 60_000;\n\nexport interface AuthUsersFile {\n\tusers: StoredAuthUser[];\n}\n\n// ============================================================================\n// PBKDF2 password hashing\n// ============================================================================\nconst PBKDF2_ITERATIONS = 100_000;\nconst PBKDF2_KEYLEN = 32;\nconst PBKDF2_DIGEST = 'sha256';\n\nexport async function hashPassword(password: string): Promise<string> {\n\tconst salt = crypto.randomBytes(16).toString('base64url');\n\tconst hash = await new Promise<Buffer>((resolve, reject) =>\n\t\tcrypto.pbkdf2(password, salt, PBKDF2_ITERATIONS, PBKDF2_KEYLEN, PBKDF2_DIGEST, (err, key) =>\n\t\t\terr ? reject(err) : resolve(key)\n\t\t)\n\t);\n\treturn `pbkdf2:${PBKDF2_DIGEST}:${PBKDF2_ITERATIONS}:${salt}:${hash.toString('base64url')}`;\n}\n\nexport async function verifyPasswordHash(password: string, storedHash: string): Promise<boolean> {\n\tconst parts = storedHash.split(':');\n\tif (parts.length !== 5 || parts[0] !== 'pbkdf2') return false;\n\tconst [, digest, iterStr, salt, expectedHashB64] = parts;\n\tconst iterations = parseInt(iterStr, 10);\n\tif (!Number.isFinite(iterations) || iterations <= 0) return false;\n\n\tconst expected = Buffer.from(expectedHashB64, 'base64url');\n\tconst actual = await new Promise<Buffer>((resolve, reject) =>\n\t\tcrypto.pbkdf2(password, salt, iterations, PBKDF2_KEYLEN, digest, (err, key) =>\n\t\t\terr ? reject(err) : resolve(key)\n\t\t)\n\t);\n\n\tif (actual.length !== expected.length) return false;\n\treturn crypto.timingSafeEqual(actual, expected);\n}\n\n// ============================================================================\n// CRUD\n// ============================================================================\n// Fresh object per call — `readJsonFile` returns its fallback by reference\n// when the file is missing, so a shared singleton would let one test (or\n// one process write) mutate state visible to the next read.\nconst empty = (): AuthUsersFile => ({ users: [] });\n\nexport interface LocalAuthUserStore {\n\tfindByEmail(email: string): Promise<StoredAuthUser | null>;\n\tfindById(id: string): Promise<StoredAuthUser | null>;\n\tlistUsers(): Promise<Omit<StoredAuthUser, 'passwordHash'>[]>;\n\t/** password null = OAuth allowlist entry (no password stored) */\n\tcreateUser(email: string, password: string | null): Promise<StoredAuthUser>;\n\tsetDisabled(id: string, disabled: boolean): Promise<void>;\n\ttouchLastLogin(id: string): Promise<void>;\n\tdeleteUser(id: string): Promise<void>;\n}\n\nexport function createLocalAuthUserStore(usersFilePath: string): LocalAuthUserStore {\n\t// Load-once, write-through cache, same pattern as `LocalOrgStoreLoader`:\n\t// reading and parsing the whole file on every call is the hot-path cost,\n\t// since `auth-users.json` is read on every authenticated request. The\n\t// provider is the sole writer in single-process local mode, so the\n\t// in-memory copy stays authoritative — every mutation updates the cache and\n\t// persists via temp+rename. Concurrent first callers share one in-flight\n\t// load so writes stack on the same array.\n\tconst store = new CachedJsonFile<AuthUsersFile>(usersFilePath, empty);\n\tconst load = () => store.get();\n\tconst persist = (file: AuthUsersFile) => store.write(file);\n\n\treturn {\n\t\tasync findByEmail(email) {\n\t\t\tconst { users } = await load();\n\t\t\treturn users.find((u) => u.email.toLowerCase() === email.toLowerCase()) ?? null;\n\t\t},\n\n\t\tasync findById(id) {\n\t\t\tconst { users } = await load();\n\t\t\treturn users.find((u) => u.id === id) ?? null;\n\t\t},\n\n\t\tasync listUsers() {\n\t\t\tconst { users } = await load();\n\t\t\treturn users.map(({ passwordHash: _ph, ...rest }) => rest);\n\t\t},\n\n\t\tasync createUser(email, password) {\n\t\t\t// Hash first: nothing may await between the uniqueness check and the push, or\n\t\t\t// a double submit gets past the check twice.\n\t\t\tconst passwordHash = password !== null ? await hashPassword(password) : null;\n\t\t\tconst file = await load();\n\t\t\tif (file.users.some((u) => u.email.toLowerCase() === email.toLowerCase())) {\n\t\t\t\tthrow new ProviderError(`User with email \"${email}\" already exists`, 409);\n\t\t\t}\n\t\t\tconst user: StoredAuthUser = {\n\t\t\t\tid: randomUUID(),\n\t\t\t\temail,\n\t\t\t\tpasswordHash,\n\t\t\t\tcreatedAt: new Date().toISOString()\n\t\t\t};\n\t\t\tfile.users.push(user);\n\t\t\tawait persist(file);\n\t\t\treturn user;\n\t\t},\n\n\t\tasync setDisabled(id, disabled) {\n\t\t\tconst file = await load();\n\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\tif (!user) throw new ProviderError(`User \"${id}\" not found`, 404);\n\t\t\tuser.disabled = disabled;\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync touchLastLogin(id) {\n\t\t\tconst file = await load();\n\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\tif (!user) return;\n\t\t\tconst now = Date.now();\n\t\t\tif (user.lastLoginAt) {\n\t\t\t\tconst prev = Date.parse(user.lastLoginAt);\n\t\t\t\tif (Number.isFinite(prev) && now - prev < LAST_LOGIN_DEBOUNCE_MS) return;\n\t\t\t}\n\t\t\tuser.lastLoginAt = new Date(now).toISOString();\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync deleteUser(id) {\n\t\t\tconst file = await load();\n\t\t\tconst before = file.users.length;\n\t\t\tfile.users = file.users.filter((u) => u.id !== id);\n\t\t\tif (file.users.length === before) throw new ProviderError(`User \"${id}\" not found`, 404);\n\t\t\tawait persist(file);\n\t\t}\n\t};\n}\n","import {\n\tclampPageLimit,\n\tdecodeOffsetCursor,\n\tencodeOffsetCursor,\n\ttype ListOptions,\n\ttype DefinitionListOptions,\n\ttype Page\n} from '@selvajs/platform';\n\ntype AnyListOptions = ListOptions | DefinitionListOptions;\n\n/**\n * In-memory pagination for filesystem-backed adapters.\n * Cursor is an offset encoded as a string. Good enough for single-node local use.\n */\nexport function paginate<T>(items: T[], opts?: AnyListOptions): Page<T> {\n\tconst limit = clampPageLimit(opts?.limit);\n\tconst offset = decodeOffsetCursor(opts?.cursor);\n\tconst slice = items.slice(offset, offset + limit);\n\tconst nextOffset = offset + slice.length;\n\treturn {\n\t\titems: slice,\n\t\tnextCursor: nextOffset < items.length ? encodeOffsetCursor(nextOffset) : undefined\n\t};\n}\n\n/**\n * Sort a list in place per ListOptions. Mutates the input.\n * Pass `keyFn` to customize how the comparison value is derived (e.g. nested\n * fields, case-folded strings).\n */\nexport function applyOrder<T>(\n\titems: T[],\n\topts?: AnyListOptions,\n\tkeyFn: (item: T, field: string) => unknown = (item, field) =>\n\t\t(item as Record<string, unknown>)[field]\n): T[] {\n\tconst field = opts?.orderBy ?? 'createdAt';\n\tconst dir = opts?.orderDir ?? 'desc';\n\tconst mul = dir === 'asc' ? 1 : -1;\n\titems.sort((a, b) => {\n\t\tconst av = (keyFn(a, field) ?? '') as string | number;\n\t\tconst bv = (keyFn(b, field) ?? '') as string | number;\n\t\tif (av < bv) return -1 * mul;\n\t\tif (av > bv) return 1 * mul;\n\t\treturn 0;\n\t});\n\treturn items;\n}\n","import * as path from 'node:path';\nimport type {\n\tIAuthProvider,\n\tIPasswordAuth,\n\tAuthUser,\n\tLoginResult,\n\tUserManagementResult,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { ProviderError } from '@selvajs/platform';\nimport { previousKey } from '@selvajs/platform/config';\nimport { signHmacToken, verifyHmacToken } from './hmac.js';\nimport { verifyPasswordHash, createLocalAuthUserStore } from './users.js';\nimport type { LocalAuthUserStore, StoredAuthUser } from './users.js';\nimport { paginate } from '../data/pagination.js';\n\nconst SESSION_MAX_AGE_MS = 8 * 60 * 60 * 1000;\n\n// Mirrors `MIN_TOKEN_SECRET_LENGTH` (share/invite tokens) and the 32-byte\n// `SELVA_AT_REST_KEY` rule so a weak session secret can't reach prod. Duplicated\n// rather than imported — the local provider has no `@selvajs/server` dependency.\nconst MIN_HMAC_SECRET_LENGTH = 32;\n\n// The `.env.example` placeholder is 41 chars, so it clears the length guard\n// above. An operator who copies the file without rotating boots with a signing\n// key that is public in the repo — every session token forgeable. `selva\n// doctor` catches it, but nothing forces anyone to run doctor.\nexport const PLACEHOLDER_SECRET = 'replace-this-with-a-random-32-byte-hex-key';\n\nfunction toAuthUser(\n\tu: Pick<StoredAuthUser, 'id' | 'email' | 'createdAt' | 'lastLoginAt' | 'disabled'>\n): AuthUser {\n\treturn {\n\t\tid: u.id,\n\t\temail: u.email,\n\t\tcreatedAt: u.createdAt,\n\t\tlastLoginAt: u.lastLoginAt,\n\t\tdisabled: u.disabled\n\t};\n}\n\nexport interface LocalAuthProviderConfig {\n\t/** HMAC signing secret. Pass from env (SELVA_HMAC_KEY). */\n\thmacSecret: string;\n\t/** The secret before the last rotation. Sessions it signed stay valid until they expire. */\n\tpreviousHmacSecret?: string;\n\t/** Epoch ms after which `previousHmacSecret` is no longer accepted. */\n\tpreviousHmacSecretExpiresAt?: number;\n\t/** Absolute path to auth-users.json. Omit for stateless (no-DATA_PATH) mode. */\n\tusersFilePath?: string;\n}\n\nclass LocalPasswordAuth implements IPasswordAuth {\n\tconstructor(\n\t\tprivate readonly users: LocalAuthUserStore | undefined,\n\t\tprivate readonly mintToken: (user: AuthUser) => string\n\t) {}\n\n\tasync verifyLogin(email: string, password: string): Promise<LoginResult> {\n\t\tif (!this.users) return { kind: 'failed', reason: 'invalid_credentials' };\n\t\tconst user = await this.users.findByEmail(email);\n\t\tif (!user) return { kind: 'failed', reason: 'invalid_credentials' };\n\t\tif (user.disabled) return { kind: 'failed', reason: 'disabled' };\n\t\tif (!user.passwordHash || !(await verifyPasswordHash(password, user.passwordHash))) {\n\t\t\treturn { kind: 'failed', reason: 'invalid_credentials' };\n\t\t}\n\t\tawait this.users.touchLastLogin(user.id).catch(() => {});\n\t\tconst auth = toAuthUser(user);\n\t\treturn { kind: 'success', user: auth, sessionToken: this.mintToken(auth) };\n\t}\n\n\tasync createUserWithPassword(email: string, password: string): Promise<AuthUser> {\n\t\tif (!this.users) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t'createUserWithPassword requires a users.json backend (DATA_PATH)',\n\t\t\t\t500\n\t\t\t);\n\t\t}\n\t\t// Permissions and the user-data row are seeded separately, via\n\t\t// `IDataProvider.ensureUser` + `IPlatformPermissionStore.set`.\n\t\treturn toAuthUser(await this.users.createUser(email, password));\n\t}\n\n\tasync registerUser(email: string, password: string): Promise<AuthUser | null> {\n\t\tif (!this.users) return null;\n\t\treturn toAuthUser(await this.users.createUser(email, password));\n\t}\n}\n\nexport class LocalAuthProvider implements IAuthProvider {\n\tprivate readonly hmacSecret: string;\n\tprivate readonly previousHmacSecret?: string;\n\tprivate readonly previousHmacSecretExpiresAt?: number;\n\tprivate readonly users?: LocalAuthUserStore;\n\n\treadonly name = 'Local';\n\treadonly passwordAuth: IPasswordAuth;\n\n\tconstructor(config: LocalAuthProviderConfig) {\n\t\tthis.hmacSecret = config.hmacSecret;\n\t\tthis.previousHmacSecret = config.previousHmacSecret;\n\t\tthis.previousHmacSecretExpiresAt = config.previousHmacSecretExpiresAt;\n\t\tif (config.usersFilePath) {\n\t\t\tthis.users = createLocalAuthUserStore(config.usersFilePath);\n\t\t}\n\t\tthis.passwordAuth = new LocalPasswordAuth(this.users, (user) =>\n\t\t\tsignHmacToken(this.hmacSecret, user.id, SESSION_MAX_AGE_MS)\n\t\t);\n\t}\n\n\t/**\n\t * The underlying identity store, or undefined in stateless (no-DATA_PATH)\n\t * mode. Exposed so callers needing direct seed/read access (tests, advanced\n\t * wiring) share this provider's store — and its cache — instead of\n\t * constructing a second store on the same file, which would diverge from it.\n\t */\n\tget userStore(): LocalAuthUserStore | undefined {\n\t\treturn this.users;\n\t}\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalAuthProvider {\n\t\tconst hmacSecret = env.SELVA_HMAC_KEY;\n\t\tif (!hmacSecret) throw new Error('Missing required env var: SELVA_HMAC_KEY');\n\t\tif (hmacSecret === PLACEHOLDER_SECRET) {\n\t\t\tthrow new Error(\n\t\t\t\t'SELVA_HMAC_KEY is still the .env.example placeholder — every session token ' +\n\t\t\t\t\t'would be forgeable by anyone with the repo. Generate one with: openssl rand -hex 32'\n\t\t\t);\n\t\t}\n\t\tif (hmacSecret.length < MIN_HMAC_SECRET_LENGTH) {\n\t\t\tthrow new Error(\n\t\t\t\t`SELVA_HMAC_KEY must be at least ${MIN_HMAC_SECRET_LENGTH} characters ` +\n\t\t\t\t\t`(got ${hmacSecret.length}). Generate one with: openssl rand -base64 32`\n\t\t\t);\n\t\t}\n\t\tconst previous = previousKey(env, 'SELVA_HMAC_KEY');\n\t\treturn new LocalAuthProvider({\n\t\t\thmacSecret,\n\t\t\t...(previous.key ? { previousHmacSecret: previous.key } : {}),\n\t\t\t...(previous.state === 'active'\n\t\t\t\t? { previousHmacSecretExpiresAt: Date.parse(previous.expires) }\n\t\t\t\t: {}),\n\t\t\tusersFilePath: env.DATA_PATH ? path.join(env.DATA_PATH, 'auth-users.json') : undefined\n\t\t});\n\t}\n\n\t/**\n\t * Runs on every authenticated request, so it stays read-only: one cached\n\t * `findById`, no writes. `lastLoginAt` is stamped at login time in\n\t * `verifyLogin`, not here — the only consumers treat it as a\n\t * has-ever-signed-in flag (invited vs. active in admin/team lists), not a\n\t * per-request activity clock, so a write on every request would cost a\n\t * full file read+parse just to usually decide not to write.\n\t */\n\tasync verifyToken(token: string): Promise<AuthUser | null> {\n\t\tlet { valid, userId } = verifyHmacToken(token, this.hmacSecret);\n\t\tconst previousAccepted =\n\t\t\tthis.previousHmacSecret !== undefined &&\n\t\t\t(this.previousHmacSecretExpiresAt === undefined ||\n\t\t\t\tDate.now() < this.previousHmacSecretExpiresAt);\n\t\tif (!valid && previousAccepted && this.previousHmacSecret) {\n\t\t\t({ valid, userId } = verifyHmacToken(token, this.previousHmacSecret));\n\t\t}\n\t\tif (!valid) return null;\n\t\tif (!this.users) return null;\n\t\tconst u = await this.users.findById(userId);\n\t\tif (!u || u.disabled) return null;\n\t\treturn toAuthUser(u);\n\t}\n\n\tasync touchLastLogin(id: string): Promise<void> {\n\t\tif (!this.users) return;\n\t\tawait this.users.touchLastLogin(id);\n\t}\n\n\tasync getUser(id: string): Promise<AuthUser | null> {\n\t\tif (!this.users) return null;\n\t\tconst u = await this.users.findById(id);\n\t\treturn u ? toAuthUser(u) : null;\n\t}\n\n\tasync listUsers(opts?: ListOptions): Promise<Page<AuthUser> | null> {\n\t\tif (!this.users) return null;\n\t\tconst users = await this.users.listUsers();\n\t\treturn paginate(users.map(toAuthUser), opts);\n\t}\n\n\tasync deleteUser(id: string): Promise<UserManagementResult> {\n\t\t// Identity-only delete. The caller enforces the sole-instance_admin\n\t\t// invariant via `IPlatformPermissionStore.countInstanceAdminsExcluding`\n\t\t// before calling this, and removes the user-data row via\n\t\t// `LocalDataProvider`'s cascade hook.\n\t\tif (!this.users) return 'not_supported';\n\t\tconst target = await this.users.findById(id);\n\t\tif (!target) return 'not_found';\n\t\ttry {\n\t\t\tawait this.users.deleteUser(id);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync disableUser(id: string): Promise<UserManagementResult> {\n\t\t// Identity-only disable. Same sole-instance_admin invariant as `deleteUser`, enforced by the caller.\n\t\tif (!this.users) return 'not_supported';\n\t\tconst target = await this.users.findById(id);\n\t\tif (!target) return 'not_found';\n\t\ttry {\n\t\t\tawait this.users.setDisabled(id, true);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tIInviteStore,\n\tIEventSink,\n\tInvite,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { NoopEventSink, actorOf } from '@selvajs/platform';\nimport { paginate, applyOrder } from './pagination.js';\nimport { readJsonFile, writeJsonFile, withFileLock } from './fsJson.js';\n\ninterface InvitesFile {\n\tinvites: Invite[];\n}\n// Factory, not a shared constant: `readJsonFile` returns its fallback by\n// reference on a missing file, and `create` mutates it via `.push`. A shared\n// object would leak those mutations across requests.\nconst empty = (): InvitesFile => ({ invites: [] });\n\n/**\n * No per-call scoping by ctx.userId — the route layer gates admin actions.\n * `getByTokenHash` is the sole unauthenticated read; it hides expired and\n * already-accepted invites so a reused link surfaces a clean error.\n */\nexport class LocalInviteStore implements IInviteStore {\n\tprivate readonly filePath: string;\n\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tevents: IEventSink = new NoopEventSink()\n\t): LocalInviteStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalInviteStore(env.DATA_PATH, events);\n\t}\n\n\tconstructor(\n\t\tdataPath: string,\n\t\tprivate readonly events: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.filePath = path.join(dataPath, 'invites.json');\n\t}\n\n\tprivate async load(): Promise<InvitesFile> {\n\t\treturn readJsonFile<InvitesFile>(this.filePath, empty());\n\t}\n\n\tprivate async save(file: InvitesFile): Promise<void> {\n\t\tawait writeJsonFile(this.filePath, file);\n\t}\n\n\tprivate locked<T>(fn: () => Promise<T>): Promise<T> {\n\t\treturn withFileLock(this.filePath, fn);\n\t}\n\n\tasync create(ctx: RequestContext, invite: Invite): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tfile.invites.push(invite);\n\t\t\tawait this.save(file);\n\t\t});\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.created',\n\t\t\tinviteId: invite.id,\n\t\t\torgId: invite.orgId,\n\t\t\temail: invite.email,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync getByTokenHash(_ctx: RequestContext, tokenHash: string): Promise<Invite | null> {\n\t\tconst { invites } = await this.load();\n\t\tconst invite = invites.find((i) => i.tokenHash === tokenHash);\n\t\tif (!invite) return null;\n\t\tif (invite.acceptedAt) return null;\n\t\tif (Date.parse(invite.expiresAt) <= Date.now()) return null;\n\t\treturn invite;\n\t}\n\n\tasync listByOrg(_ctx: RequestContext, orgId: string, opts?: ListOptions): Promise<Page<Invite>> {\n\t\tconst { invites } = await this.load();\n\t\tconst filtered = invites.filter((i) => i.orgId === orgId);\n\t\treturn paginate(applyOrder(filtered, opts), opts);\n\t}\n\n\tasync markAccepted(ctx: RequestContext, id: string, userId: string): Promise<boolean> {\n\t\tconst invite = await this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst target = file.invites.find((i) => i.id === id);\n\t\t\tif (!target || target.acceptedAt) return null;\n\t\t\tif (Date.parse(target.expiresAt) <= Date.now()) return null;\n\t\t\ttarget.acceptedAt = new Date().toISOString();\n\t\t\ttarget.acceptedByUserId = userId;\n\t\t\tawait this.save(file);\n\t\t\treturn target;\n\t\t});\n\t\tif (!invite) return false;\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.accepted',\n\t\t\tinviteId: invite.id,\n\t\t\torgId: invite.orgId,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t\treturn true;\n\t}\n\n\tasync reopen(_ctx: RequestContext, id: string, userId: string): Promise<boolean> {\n\t\treturn this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst target = file.invites.find((i) => i.id === id);\n\t\t\tif (!target?.acceptedAt || target.acceptedByUserId !== userId) return false;\n\t\t\tdelete target.acceptedAt;\n\t\t\tdelete target.acceptedByUserId;\n\t\t\tawait this.save(file);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst target = await this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst found = file.invites.find((i) => i.id === id && !i.acceptedAt);\n\t\t\tif (!found) return null;\n\t\t\tfile.invites = file.invites.filter((i) => i.id !== id || i.acceptedAt);\n\t\t\tawait this.save(file);\n\t\t\treturn found;\n\t\t});\n\t\tif (!target) return;\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.revoked',\n\t\t\tinviteId: id,\n\t\t\torgId: target.orgId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync revokePendingByEmail(ctx: RequestContext, orgId: string, email: string): Promise<string[]> {\n\t\t// Emails are stored lowercase at mint time; normalize the needle too so an\n\t\t// offboarding call with the address as the admin typed it still matches.\n\t\tconst needle = email.trim().toLowerCase();\n\t\tconst doomed = await this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst matched = file.invites.filter(\n\t\t\t\t(i) => i.orgId === orgId && !i.acceptedAt && i.email.toLowerCase() === needle\n\t\t\t);\n\t\t\tif (matched.length === 0) return matched;\n\t\t\tconst ids = new Set(matched.map((i) => i.id));\n\t\t\tfile.invites = file.invites.filter((i) => !ids.has(i.id));\n\t\t\tawait this.save(file);\n\t\t\treturn matched;\n\t\t});\n\t\tfor (const invite of doomed) {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'invite.revoked',\n\t\t\t\tinviteId: invite.id,\n\t\t\t\torgId: invite.orgId,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\t\treturn doomed.map((i) => i.id);\n\t}\n\n\tasync deleteByOrg(_ctx: RequestContext, orgId: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst before = file.invites.length;\n\t\t\tfile.invites = file.invites.filter((i) => i.orgId !== orgId);\n\t\t\tif (file.invites.length === before) return;\n\t\t\tawait this.save(file);\n\t\t});\n\t}\n\n\t/** Invites addressed to or minted by the user, and their name on any they accepted. */\n\tasync eraseUser(userId: string, email: string | undefined): Promise<void> {\n\t\tconst needle = email?.trim().toLowerCase();\n\t\tawait this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tfile.invites = file.invites\n\t\t\t\t.filter((i) => i.invitedBy !== userId && i.email.toLowerCase() !== needle)\n\t\t\t\t.map((i) => (i.acceptedByUserId === userId ? { ...i, acceptedByUserId: undefined } : i));\n\t\t\tawait this.save(file);\n\t\t});\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tApiToken,\n\tApiTokenRevokeReason,\n\tApiTokenSummary,\n\tIApiTokenStore,\n\tIEventSink,\n\tListOptions,\n\tPage,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopEventSink, actorOf } from '@selvajs/platform';\nimport { paginate, applyOrder } from './pagination.js';\nimport { readJsonFile, writeJsonFile, withFileLock } from './fsJson.js';\n\ninterface ApiTokensFile {\n\ttokens: ApiToken[];\n}\n// Factory, not a shared constant: `readJsonFile` returns the fallback by\n// reference and `create` pushes into it.\nconst empty = (): ApiTokensFile => ({ tokens: [] });\n\nfunction isLive(t: ApiToken, now: number): boolean {\n\treturn t.revokedAt === null && Date.parse(t.expiresAt) > now;\n}\n\nfunction summarize({ tokenHash: _hash, ...rest }: ApiToken): ApiTokenSummary {\n\treturn rest;\n}\n\n/** No per-call scoping by ctx: the route layer gates who may mint, list and revoke. */\nexport class LocalApiTokenStore implements IApiTokenStore {\n\tprivate readonly filePath: string;\n\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tevents: IEventSink = new NoopEventSink()\n\t): LocalApiTokenStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalApiTokenStore(env.DATA_PATH, events);\n\t}\n\n\tconstructor(\n\t\tdataPath: string,\n\t\tprivate readonly events: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.filePath = path.join(dataPath, 'api-tokens.json');\n\t}\n\n\tprivate load(): Promise<ApiTokensFile> {\n\t\treturn readJsonFile<ApiTokensFile>(this.filePath, empty());\n\t}\n\n\tprivate save(file: ApiTokensFile): Promise<void> {\n\t\treturn writeJsonFile(this.filePath, file);\n\t}\n\n\tprivate locked<T>(fn: () => Promise<T>): Promise<T> {\n\t\treturn withFileLock(this.filePath, fn);\n\t}\n\n\tasync create(ctx: RequestContext, token: ApiToken): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tfile.tokens.push(token);\n\t\t\tawait this.save(file);\n\t\t});\n\t\tawait this.events.emit({\n\t\t\ttype: 'api_token.created',\n\t\t\tapiTokenId: token.id,\n\t\t\torgId: token.orgId,\n\t\t\tuserId: token.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync getByTokenHash(_ctx: RequestContext, tokenHash: string): Promise<ApiToken | null> {\n\t\tconst { tokens } = await this.load();\n\t\tconst token = tokens.find((t) => t.tokenHash === tokenHash);\n\t\treturn token && isLive(token, Date.now()) ? token : null;\n\t}\n\n\tasync get(_ctx: RequestContext, id: string): Promise<ApiTokenSummary | null> {\n\t\tconst { tokens } = await this.load();\n\t\tconst token = tokens.find((t) => t.id === id);\n\t\treturn token ? summarize(token) : null;\n\t}\n\n\tasync listByOrg(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions & { userId?: string }\n\t): Promise<Page<ApiTokenSummary>> {\n\t\tconst { tokens } = await this.load();\n\t\tconst filtered = tokens\n\t\t\t.filter((t) => t.orgId === orgId && (!opts?.userId || t.userId === opts.userId))\n\t\t\t.map(summarize);\n\t\treturn paginate(applyOrder(filtered, opts), opts);\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string, reason: ApiTokenRevokeReason): Promise<void> {\n\t\tconst token = await this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst found = file.tokens.find((t) => t.id === id);\n\t\t\tif (!found || found.revokedAt !== null) return null;\n\t\t\tfound.revokedAt = new Date().toISOString();\n\t\t\tawait this.save(file);\n\t\t\treturn found;\n\t\t});\n\t\tif (token) await this.emitRevoked(ctx, token, reason);\n\t}\n\n\tasync revokeAllForUser(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\topts: { orgId?: string; reason: ApiTokenRevokeReason }\n\t): Promise<string[]> {\n\t\tconst doomed = await this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst matching = file.tokens.filter(\n\t\t\t\t(t) =>\n\t\t\t\t\tt.userId === userId && t.revokedAt === null && (!opts.orgId || t.orgId === opts.orgId)\n\t\t\t);\n\t\t\tif (matching.length === 0) return [];\n\t\t\tconst at = new Date().toISOString();\n\t\t\tfor (const t of matching) t.revokedAt = at;\n\t\t\tawait this.save(file);\n\t\t\treturn matching;\n\t\t});\n\t\tfor (const t of doomed) await this.emitRevoked(ctx, t, opts.reason);\n\t\treturn doomed.map((t) => t.id);\n\t}\n\n\ttouchLastUsed(_ctx: RequestContext, id: string, at: string): Promise<void> {\n\t\treturn this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst token = file.tokens.find((t) => t.id === id);\n\t\t\tif (!token) return;\n\t\t\ttoken.lastUsedAt = at;\n\t\t\tawait this.save(file);\n\t\t});\n\t}\n\n\teraseUser(_ctx: RequestContext, userId: string): Promise<void> {\n\t\treturn this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst before = JSON.stringify(file.tokens);\n\t\t\tfile.tokens = file.tokens\n\t\t\t\t.filter((t) => t.userId !== userId)\n\t\t\t\t.map((t) => (t.createdBy === userId ? { ...t, createdBy: null } : t));\n\t\t\tif (JSON.stringify(file.tokens) !== before) await this.save(file);\n\t\t});\n\t}\n\n\tdeleteByOrg(_ctx: RequestContext, orgId: string): Promise<void> {\n\t\treturn this.locked(async () => {\n\t\t\tconst file = await this.load();\n\t\t\tconst before = file.tokens.length;\n\t\t\tfile.tokens = file.tokens.filter((t) => t.orgId !== orgId);\n\t\t\tif (file.tokens.length !== before) await this.save(file);\n\t\t});\n\t}\n\n\tprivate emitRevoked(\n\t\tctx: RequestContext,\n\t\ttoken: ApiToken,\n\t\treason: ApiTokenRevokeReason\n\t): Promise<void> {\n\t\treturn this.events.emit({\n\t\t\ttype: 'api_token.revoked',\n\t\t\tapiTokenId: token.id,\n\t\t\torgId: token.orgId,\n\t\t\treason,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n","import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';\nimport { parseKey32 } from './key32.js';\nimport { previousKey } from '../config/previous-key.js';\nimport type { EnvRecord } from '../config/resolve.js';\n\nconst ALGO = 'aes-256-gcm';\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst PREFIX_V1 = 'enc:v1:';\nconst PREFIX_V2 = 'enc:v2:';\nconst PREFIX_V3 = 'enc:v3:';\n// Every version prefix has this length.\nconst PREFIX_LENGTH = PREFIX_V1.length;\n\n/** The record a secret belongs to, and the URL the secret is sent to. */\nexport interface SecretBinding {\n\tid: string;\n\turl: string;\n}\n\nexport function isEncryptedSecret(value: string): boolean {\n\treturn isLegacyEnvelope(value) || value.startsWith(PREFIX_V3);\n}\n\n/**\n * An `enc:v1:` or `enc:v2:` envelope: sealed without a {@link SecretBinding}, so it\n * still opens after its record's URL changes. Stores re-seal these.\n */\nexport function isLegacyEnvelope(value: string): boolean {\n\treturn value.startsWith(PREFIX_V1) || value.startsWith(PREFIX_V2);\n}\n\n/**\n * An `enc:v<n>:` envelope this build cannot open: a newer Selva sealed it, and this\n * one runs after a downgrade. It is ciphertext, so it must never be reported or\n * used as a plaintext key.\n */\nexport function isUnknownEnvelope(value: string): boolean {\n\treturn /^enc:v\\d+:/.test(value) && !isEncryptedSecret(value);\n}\n\n// JSON, so no two id/url pairs encode alike: `[\"a:b\",\"c\"]` is not `[\"a\",\"b:c\"]`.\nfunction bindingAad({ id, url }: SecretBinding): Buffer {\n\treturn Buffer.from(JSON.stringify([id, url]), 'utf8');\n}\n\n/**\n * AES-256-GCM envelope for at-rest secrets (e.g. compute API keys):\n * `enc:v<n>:<base64(iv|tag|ciphertext)>`. What `aad` is picks the version, and\n * the version says what GCM authenticates besides the ciphertext:\n * - a {@link SecretBinding} gives `v3`: the record's id and URL. Ciphertext copied\n * onto another record, or a record pointed at another host, fails to decrypt\n * instead of handing the plaintext to that host.\n * - a string gives `v2`: that string, which stores set to the record's id.\n * - nothing gives `v1`: nothing.\n *\n * Defends against backup leaks, accidental file/DB sharing, and read-only\n * storage access — not against an attacker who also has the master key\n * (`SELVA_AT_REST_KEY` env var, process memory). This is encryption at rest,\n * not a secret manager.\n *\n * Pure `node:crypto`, no fs or DB coupling, so the local and Supabase\n * compute-server stores share this one implementation.\n */\nexport function encryptSecret(\n\tplaintext: string,\n\tkey: Buffer,\n\taad?: string | SecretBinding\n): string {\n\tif (key.length !== 32) {\n\t\tthrow new Error(`Secret key must be 32 bytes; got ${key.length}`);\n\t}\n\tif (isEncryptedSecret(plaintext)) {\n\t\tthrow new Error('Refusing to encrypt a value that is already encrypted');\n\t}\n\tconst [prefix, aadBytes] =\n\t\taad === undefined\n\t\t\t? [PREFIX_V1, undefined]\n\t\t\t: typeof aad === 'string'\n\t\t\t\t? [PREFIX_V2, Buffer.from(aad, 'utf8')]\n\t\t\t\t: [PREFIX_V3, bindingAad(aad)];\n\tconst iv = randomBytes(IV_BYTES);\n\tconst cipher = createCipheriv(ALGO, key, iv);\n\tif (aadBytes) cipher.setAAD(aadBytes);\n\tconst ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n\tconst tag = cipher.getAuthTag();\n\treturn prefix + Buffer.concat([iv, tag, ciphertext]).toString('base64');\n}\n\nfunction aadToOpen(envelope: string, aad: string | SecretBinding | undefined): Buffer | undefined {\n\tif (envelope.startsWith(PREFIX_V1)) return undefined;\n\tif (envelope.startsWith(PREFIX_V2)) {\n\t\tif (aad === undefined) throw new Error('This secret is bound to a record: pass its id');\n\t\treturn Buffer.from(typeof aad === 'string' ? aad : aad.id, 'utf8');\n\t}\n\tif (aad === undefined || typeof aad === 'string') {\n\t\tthrow new Error('This secret is bound to a record and its URL: pass both');\n\t}\n\treturn bindingAad(aad);\n}\n\n/**\n * `aad` is ignored for `v1`. `v2` takes the string it was sealed with, or a\n * binding's `id`; `v3` needs the binding.\n */\nexport function decryptSecret(envelope: string, key: Buffer, aad?: string | SecretBinding): string {\n\tif (key.length !== 32) {\n\t\tthrow new Error(`Secret key must be 32 bytes; got ${key.length}`);\n\t}\n\tif (!isEncryptedSecret(envelope)) {\n\t\tthrow new Error('Value is not an encrypted secret envelope');\n\t}\n\tconst aadBytes = aadToOpen(envelope, aad);\n\tconst buf = Buffer.from(envelope.slice(PREFIX_LENGTH), 'base64');\n\tif (buf.length < IV_BYTES + TAG_BYTES) {\n\t\tthrow new Error('Encrypted secret is shorter than its IV and tag');\n\t}\n\tconst iv = buf.subarray(0, IV_BYTES);\n\tconst tag = buf.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);\n\tconst ciphertext = buf.subarray(IV_BYTES + TAG_BYTES);\n\t// Pinned: without it Node accepts a truncated tag, down to 4 bytes.\n\tconst decipher = createDecipheriv(ALGO, key, iv, { authTagLength: TAG_BYTES });\n\tdecipher.setAuthTag(tag);\n\tif (aadBytes) decipher.setAAD(aadBytes);\n\treturn Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');\n}\n\nconst GENERATE_HINT =\n\t\"Generate one with: node -e \\\"console.log(require('crypto').randomBytes(32).toString('hex'))\\\"\";\n\n/**\n * Decodes a `SELVA_AT_REST_KEY` env var into a 32-byte buffer (64-char hex or\n * base64, with or without padding). Throws on anything else so a\n * misconfigured key fails loudly at boot instead of silently producing\n * ciphertext nothing can decrypt.\n */\nexport function decodeSecretKey(raw: string): Buffer {\n\tconst key = parseKey32(raw);\n\tif (key) return key;\n\tthrow new Error(\n\t\t`SELVA_AT_REST_KEY must be 32 bytes encoded as 64-char hex or base64. ${GENERATE_HINT}`\n\t);\n}\n\n/**\n * `SELVA_AT_REST_KEY`, plus `SELVA_AT_REST_KEY_PREVIOUS` while it is within its\n * deadline. Throws when the current key is missing or malformed.\n */\nexport function readAtRestKeys(env: EnvRecord): { current: Buffer; previous?: Buffer } {\n\tif (!env.SELVA_AT_REST_KEY) {\n\t\tthrow new Error(\n\t\t\t`Missing required env var: SELVA_AT_REST_KEY (32-byte hex or base64). ${GENERATE_HINT}`\n\t\t);\n\t}\n\tconst current = decodeSecretKey(env.SELVA_AT_REST_KEY);\n\tconst previous = previousKey(env, 'SELVA_AT_REST_KEY').key;\n\treturn previous ? { current, previous: decodeSecretKey(previous) } : { current };\n}\n\n/**\n * Result of a compute-server store's `verifySecrets()`. One `failures` entry\n * per server whose `apiKey` couldn't be loaded:\n * - `plaintext_on_disk` — the field exists but isn't an `enc:` envelope:\n * a hand-edit, a legacy row from before encryption, or a migration\n * regression. Security-relevant.\n * - `key_mismatch` — envelope is valid but GCM auth-tag verification fails\n * under the current `SELVA_AT_REST_KEY`: the key was rotated, or the data\n * came from another deployment.\n * - `unknown_envelope` — an `enc:v<n>:` envelope from a newer Selva than the\n * one running ({@link isUnknownEnvelope}): the app was downgraded.\n */\nexport type SecretVerificationFailureReason =\n\t'key_mismatch' | 'plaintext_on_disk' | 'unknown_envelope';\n\nexport interface SecretVerificationFailure {\n\tserverId: string;\n\tserverLabel: string;\n\treason: SecretVerificationFailureReason;\n\t/** Underlying error message for `key_mismatch`. Absent otherwise. */\n\tcause?: string;\n}\n\nexport interface SecretVerificationReport {\n\tok: boolean;\n\tfailures: SecretVerificationFailure[];\n\t/** True if at least one row holds an unencrypted apiKey at rest. */\n\tplaintextFound: boolean;\n\t/** Rows only SELVA_AT_REST_KEY_PREVIOUS opens. Drop the previous key once this is 0. */\n\tonPreviousKey?: number;\n\t/**\n\t * Rows in a {@link isLegacyEnvelope legacy envelope}, which still opens after the\n\t * server's URL changes. `reencryptSecrets` re-seals them. Absent when there are none.\n\t */\n\tlegacyEnvelopes?: number;\n}\n\n/**\n * {@link decryptSecret} under each key in turn, current first. AES-GCM\n * authenticates, so a wrong key fails rather than returning garbage, and trying\n * the next one is safe. `keyIndex` above 0 means the caller should re-encrypt\n * under `keys[0]`.\n */\nexport function decryptWithKeys(\n\tenvelope: string,\n\tkeys: readonly Buffer[],\n\taad?: string | SecretBinding\n): { plaintext: string; keyIndex: number } {\n\tlet lastError: unknown;\n\tfor (const [keyIndex, key] of keys.entries()) {\n\t\ttry {\n\t\t\treturn { plaintext: decryptSecret(envelope, key, aad), keyIndex };\n\t\t} catch (err) {\n\t\t\tlastError = err;\n\t\t}\n\t}\n\tthrow lastError ?? new Error('No key to decrypt with');\n}\n","import * as path from 'node:path';\nimport {\n\tisOrgServer,\n\tisPlatformServer,\n\tscopeConfigToOrg,\n\ttype IComputeServerStore,\n\ttype ComputeConfig,\n\ttype ComputeServerConfig,\n\ttype GetConfigOptions,\n\ttype PlatformComputeServer,\n\ttype RequestContext,\n\ttype SecretVerificationFailure,\n\ttype SecretVerificationReport,\n\ttype ILogger\n} from '@selvajs/platform';\nimport { NoopLogger, ProviderError } from '@selvajs/platform';\nimport {\n\tdecryptWithKeys,\n\tencryptSecret,\n\tisEncryptedSecret,\n\tisLegacyEnvelope,\n\tisUnknownEnvelope,\n\treadAtRestKeys,\n\ttype SecretBinding\n} from '@selvajs/platform/computeServer';\nimport { readJsonFile, withFileLock, writeJsonFile } from './fsJson.js';\n\n// Re-exported from `@selvajs/platform` (`computeServer/secrets`) — kept here so\n// the local provider's public surface (index.ts) stays backward-compatible.\nexport type {\n\tSecretVerificationFailure,\n\tSecretVerificationFailureReason,\n\tSecretVerificationReport\n} from '@selvajs/platform';\n\n/**\n * On-disk shape of compute.config.json: all servers (platform + org-private)\n * in one array, the global `defaultServerId`, and the per-org `orgDefaults`\n * map. `apiKey` is always stored as an `enc:` envelope (AES-256-GCM) bound to\n * the server's id and URL; the store decrypts on read so callers see plaintext.\n */\ninterface OnDiskShape {\n\tservers: ComputeServerConfig[];\n\tdefaultServerId?: string;\n\torgDefaults?: Record<string, string>;\n}\n\n// `readJsonFile` returns its fallback BY REFERENCE when the file is missing,\n// so a shared module-level constant would let mutations bleed across calls.\nconst empty = (): OnDiskShape => ({ servers: [], orgDefaults: {} });\n\n// `getServerApiKey` looks a key up by id alone, so an org reusing another\n// scope's id would get that scope's key sent to its own URL.\nfunction assertIdsFree(\n\tincoming: readonly ComputeServerConfig[],\n\totherScopes: readonly ComputeServerConfig[]\n): void {\n\tconst taken = new Set(otherScopes.map((s) => s.id));\n\tif (incoming.some((s) => taken.has(s.id))) {\n\t\tthrow new ProviderError('A compute server id is already in use', 409);\n\t}\n}\n\nconst bindingOf = (s: ComputeServerConfig): SecretBinding => ({ id: s.id, url: s.serverUrl });\n\n/**\n * Reads/writes compute.config.json, re-read on every call so edits take\n * effect without a restart. Mutation methods are scope-targeted\n * (`savePlatformServers`, `saveOrgServers`, `setOrgDefault`) — each leaves\n * rows in the other scopes untouched.\n */\nexport class LocalComputeServerStore implements IComputeServerStore {\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tlogger?: ILogger\n\t): LocalComputeServerStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\tconst keys = readAtRestKeys(env);\n\t\treturn new LocalComputeServerStore(\n\t\t\tpath.join(env.DATA_PATH, 'compute.config.json'),\n\t\t\tkeys.current,\n\t\t\tlogger,\n\t\t\tkeys.previous\n\t\t);\n\t}\n\n\tprivate readonly logger: ILogger;\n\t/** Current key first; the previous one still opens rows sealed before a rotation. */\n\tprivate readonly keys: Buffer[];\n\n\tconstructor(\n\t\tprivate readonly configFilePath: string,\n\t\tprivate readonly secretKey: Buffer,\n\t\tlogger?: ILogger,\n\t\tpreviousKey?: Buffer\n\t) {\n\t\tthis.logger = logger ?? new NoopLogger();\n\t\tthis.keys = previousKey ? [secretKey, previousKey] : [secretKey];\n\t}\n\n\tprivate async readAll(): Promise<OnDiskShape> {\n\t\tconst raw = await readJsonFile<OnDiskShape>(this.configFilePath, empty());\n\t\treturn {\n\t\t\tservers: raw.servers ?? [],\n\t\t\tdefaultServerId: raw.defaultServerId,\n\t\t\torgDefaults: raw.orgDefaults ?? {}\n\t\t};\n\t}\n\n\t/**\n\t * Tolerant per-row decrypt: a row whose key cannot be opened comes back with\n\t * `apiKey: undefined` and a logged warning, rather than failing the whole read.\n\t * The page keeps rendering, and a solve against that server fails later when\n\t * Rhino.Compute rejects the missing key. That covers ciphertext that does not\n\t * authenticate under the current `SELVA_AT_REST_KEY`, and an envelope from a\n\t * newer Selva. `verifySecrets()` is the strict counterpart for boot time.\n\t *\n\t * Plaintext is the exception. The store never writes it (every write goes\n\t * through `encryptApiKeys`), so seeing it means someone hand-edited the file\n\t * with a real secret exposed: a read that would use the key throws.\n\t * `plaintext: 'unreadable'` returns the row keyless instead, for the save\n\t * path: a throw there would block the save that replaces the key.\n\t */\n\tprivate decryptApiKeys(\n\t\tservers: ComputeServerConfig[],\n\t\t{ plaintext = 'throw' }: { plaintext?: 'throw' | 'unreadable' } = {}\n\t): ComputeServerConfig[] {\n\t\treturn servers.map((s) => {\n\t\t\tif (!s.apiKey) return s;\n\t\t\tconst fields = { component: 'selva', serverLabel: s.label, serverId: s.id };\n\t\t\tif (isUnknownEnvelope(s.apiKey)) {\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t`Could not read apiKey: it is sealed as ${s.apiKey.slice(0, 6)}, a format this Selva version does not know. ` +\n\t\t\t\t\t\t'A newer version wrote it. This server is returned without an apiKey and solves against it will fail. ' +\n\t\t\t\t\t\t'Upgrade Selva again, or re-enter the key via /admin/compute.',\n\t\t\t\t\tfields\n\t\t\t\t);\n\t\t\t\treturn { ...s, apiKey: undefined };\n\t\t\t}\n\t\t\tif (!isEncryptedSecret(s.apiKey)) {\n\t\t\t\tconst message =\n\t\t\t\t\t`compute.config.json contains an unencrypted apiKey for server \"${s.label}\" (${s.id}). ` +\n\t\t\t\t\t'Re-enter the key via /admin/compute so it is stored encrypted.';\n\t\t\t\tif (plaintext === 'throw') throw new Error(message);\n\t\t\t\tthis.logger.error(message, fields);\n\t\t\t\treturn { ...s, apiKey: undefined };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn { ...s, apiKey: decryptWithKeys(s.apiKey, this.keys, bindingOf(s)).plaintext };\n\t\t\t} catch (cause) {\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t'Could not decrypt apiKey: the stored ciphertext does not match the current SELVA_AT_REST_KEY. ' +\n\t\t\t\t\t\t'This server is returned without an apiKey and solves against it will fail. ' +\n\t\t\t\t\t\t'Re-enter the key via /admin/compute, or restore the original SELVA_AT_REST_KEY.',\n\t\t\t\t\t{\n\t\t\t\t\t\t...fields,\n\t\t\t\t\t\terr: cause instanceof Error ? (cause.stack ?? cause.message) : String(cause)\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\treturn { ...s, apiKey: undefined };\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Boot-time integrity check: attempts to decrypt every server's `apiKey`\n\t * and returns a report instead of throwing — the caller decides what to do\n\t * (refuse boot, log and degrade, etc). Call from `hooks.server.ts` so a key\n\t * mismatch fails loudly at deploy time, not as a blank page when a user\n\t * first hits a route that loads compute config.\n\t */\n\tasync verifySecrets(): Promise<SecretVerificationReport> {\n\t\tconst all = await this.readAll();\n\t\tconst failures: SecretVerificationFailure[] = [];\n\t\tlet plaintextFound = false;\n\t\tlet onPreviousKey = 0;\n\t\tlet legacyEnvelopes = 0;\n\n\t\tfor (const s of all.servers) {\n\t\t\tif (!s.apiKey) continue;\n\t\t\tif (isUnknownEnvelope(s.apiKey)) {\n\t\t\t\tfailures.push({ serverId: s.id, serverLabel: s.label, reason: 'unknown_envelope' });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isEncryptedSecret(s.apiKey)) {\n\t\t\t\tplaintextFound = true;\n\t\t\t\tfailures.push({\n\t\t\t\t\tserverId: s.id,\n\t\t\t\t\tserverLabel: s.label,\n\t\t\t\t\treason: 'plaintext_on_disk'\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isLegacyEnvelope(s.apiKey)) legacyEnvelopes += 1;\n\t\t\ttry {\n\t\t\t\tif (decryptWithKeys(s.apiKey, this.keys, bindingOf(s)).keyIndex > 0) onPreviousKey += 1;\n\t\t\t} catch (cause) {\n\t\t\t\tfailures.push({\n\t\t\t\t\tserverId: s.id,\n\t\t\t\t\tserverLabel: s.label,\n\t\t\t\t\treason: 'key_mismatch',\n\t\t\t\t\tcause: cause instanceof Error ? cause.message : String(cause)\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tok: failures.length === 0,\n\t\t\tfailures,\n\t\t\tplaintextFound,\n\t\t\t...(this.keys.length > 1 ? { onPreviousKey } : {}),\n\t\t\t...(legacyEnvelopes > 0 ? { legacyEnvelopes } : {})\n\t\t};\n\t}\n\n\t/**\n\t * Re-seal every row that only the previous key opens, or that sits in a legacy\n\t * envelope, under the current key and the row's binding. Under the file lock,\n\t * so it can't interleave with an admin save. Returns how many rows it re-sealed.\n\t */\n\tasync reencryptSecrets(): Promise<number> {\n\t\treturn withFileLock(this.configFilePath, async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tlet changed = 0;\n\t\t\tconst servers = all.servers.map((s) => {\n\t\t\t\tif (!s.apiKey || !isEncryptedSecret(s.apiKey)) return s;\n\t\t\t\ttry {\n\t\t\t\t\tconst { plaintext, keyIndex } = decryptWithKeys(s.apiKey, this.keys, bindingOf(s));\n\t\t\t\t\tif (keyIndex === 0 && !isLegacyEnvelope(s.apiKey)) return s;\n\t\t\t\t\tchanged += 1;\n\t\t\t\t\treturn { ...s, apiKey: encryptSecret(plaintext, this.secretKey, bindingOf(s)) };\n\t\t\t\t} catch {\n\t\t\t\t\treturn s;\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (changed > 0) await writeJsonFile<OnDiskShape>(this.configFilePath, { ...all, servers });\n\t\t\treturn changed;\n\t\t});\n\t}\n\n\tprivate encryptApiKeys(servers: ComputeServerConfig[]): ComputeServerConfig[] {\n\t\treturn servers.map((s) => {\n\t\t\tif (!s.apiKey) return s;\n\t\t\treturn { ...s, apiKey: encryptSecret(s.apiKey, this.secretKey, bindingOf(s)) };\n\t\t});\n\t}\n\n\tasync getConfig(_ctx: RequestContext, opts: GetConfigOptions = {}): Promise<ComputeConfig> {\n\t\tconst all = await this.readAll();\n\t\t// Keys are read through here only to merge a save, which must be able to\n\t\t// replace a plaintext one.\n\t\tconst servers = opts.includeApiKeys\n\t\t\t? this.decryptApiKeys(all.servers, { plaintext: 'unreadable' })\n\t\t\t: all.servers.map((s) => ({ ...s, apiKey: undefined }));\n\t\tconst config: ComputeConfig = {\n\t\t\t// `hasApiKey` reads the stored (still-encrypted) value, so presence is\n\t\t\t// reported without decrypting anything.\n\t\t\tservers: servers.map((s, i) => ({ ...s, hasApiKey: !!all.servers[i].apiKey })),\n\t\t\tdefaultServerId: all.defaultServerId,\n\t\t\torgDefaults: all.orgDefaults\n\t\t};\n\t\treturn opts.scopeToOrgId ? scopeConfigToOrg(config, opts.scopeToOrgId) : config;\n\t}\n\n\t/**\n\t * One server's decrypted key. The local store reads the whole file anyway, so\n\t * this exists for interface parity with Supabase (where it saves a table scan\n\t * plus N decrypts) — and it still avoids decrypting the other servers' keys.\n\t */\n\tasync getServerApiKey(_ctx: RequestContext, serverId: string): Promise<string | undefined> {\n\t\tconst all = await this.readAll();\n\t\tconst server = all.servers.find((s) => s.id === serverId);\n\t\tif (!server?.apiKey) return undefined;\n\t\treturn this.decryptApiKeys([server])[0].apiKey;\n\t}\n\n\tasync savePlatformServers(\n\t\t_ctx: RequestContext,\n\t\tservers: ComputeServerConfig[],\n\t\tdefaultServerId: string | undefined\n\t): Promise<void> {\n\t\tawait withFileLock(this.configFilePath, async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst orgRows = all.servers.filter(isOrgServer);\n\t\t\tconst incoming = servers.filter(isPlatformServer);\n\t\t\tassertIdsFree(incoming, orgRows);\n\t\t\tconst platformRows = this.encryptApiKeys(incoming);\n\n\t\t\tawait writeJsonFile<OnDiskShape>(this.configFilePath, {\n\t\t\t\tservers: [...platformRows, ...orgRows],\n\t\t\t\tdefaultServerId,\n\t\t\t\torgDefaults: all.orgDefaults\n\t\t\t});\n\t\t});\n\t}\n\n\tasync saveOrgServers(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\tservers: ComputeServerConfig[],\n\t\tdefaultServerId?: string | null\n\t): Promise<void> {\n\t\tawait withFileLock(this.configFilePath, async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst platformRows = all.servers.filter(isPlatformServer);\n\t\t\tconst otherOrgRows = all.servers.filter((s) => isOrgServer(s) && s.ownerOrgId !== orgId);\n\t\t\tconst incoming = servers.filter(isOrgServer).map((s) => ({ ...s, ownerOrgId: orgId }));\n\t\t\tassertIdsFree(incoming, [...platformRows, ...otherOrgRows]);\n\t\t\tconst thisOrgRows = this.encryptApiKeys(incoming);\n\n\t\t\tconst orgDefaults = { ...(all.orgDefaults ?? {}) };\n\t\t\tif (defaultServerId === null) {\n\t\t\t\tdelete orgDefaults[orgId];\n\t\t\t} else if (typeof defaultServerId === 'string') {\n\t\t\t\torgDefaults[orgId] = defaultServerId;\n\t\t\t}\n\n\t\t\tawait writeJsonFile<OnDiskShape>(this.configFilePath, {\n\t\t\t\tservers: [...platformRows, ...otherOrgRows, ...thisOrgRows],\n\t\t\t\tdefaultServerId: all.defaultServerId,\n\t\t\t\torgDefaults\n\t\t\t});\n\t\t});\n\t}\n\n\tasync setOrgDefault(_ctx: RequestContext, orgId: string, serverId: string | null): Promise<void> {\n\t\tawait withFileLock(this.configFilePath, async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst orgDefaults = { ...(all.orgDefaults ?? {}) };\n\t\t\tif (serverId === null) {\n\t\t\t\tdelete orgDefaults[orgId];\n\t\t\t} else {\n\t\t\t\torgDefaults[orgId] = serverId;\n\t\t\t}\n\t\t\tawait writeJsonFile<OnDiskShape>(this.configFilePath, { ...all, orgDefaults });\n\t\t});\n\t}\n\n\tasync deleteByOrg(_ctx: RequestContext, orgId: string): Promise<void> {\n\t\tawait withFileLock(this.configFilePath, async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst remaining = all.servers.filter((s) => !(isOrgServer(s) && s.ownerOrgId === orgId));\n\n\t\t\tconst cleaned: ComputeServerConfig[] = remaining.map((s) => {\n\t\t\t\tif (!isPlatformServer(s)) return s;\n\t\t\t\tif (s.sharedWith === 'all') return s;\n\t\t\t\tif (!s.sharedWith.includes(orgId)) return s;\n\t\t\t\tconst next: PlatformComputeServer = {\n\t\t\t\t\t...s,\n\t\t\t\t\tsharedWith: s.sharedWith.filter((id) => id !== orgId)\n\t\t\t\t};\n\t\t\t\treturn next;\n\t\t\t});\n\n\t\t\tconst orgDefaults = { ...(all.orgDefaults ?? {}) };\n\t\t\tconst hadDefault = orgId in orgDefaults;\n\t\t\tdelete orgDefaults[orgId];\n\n\t\t\tconst changed =\n\t\t\t\tcleaned.length !== all.servers.length ||\n\t\t\t\thadDefault ||\n\t\t\t\tcleaned.some((c, i) => c !== all.servers[i]);\n\t\t\tif (!changed) return;\n\n\t\t\tawait writeJsonFile<OnDiskShape>(this.configFilePath, {\n\t\t\t\tservers: cleaned,\n\t\t\t\tdefaultServerId: all.defaultServerId,\n\t\t\t\torgDefaults\n\t\t\t});\n\t\t});\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tIPlatformProjectGrantStore,\n\tPlatformProjectGrant,\n\tRequestContext\n} from '@selvajs/platform';\nimport { ERASED_ACTOR_ID, ProviderError } from '@selvajs/platform';\nimport { readJsonFile, withFileLock, writeJsonFile } from './fsJson.js';\n\ninterface OnDiskShape {\n\tgrants: PlatformProjectGrant[];\n}\n\nconst empty = (): OnDiskShape => ({ grants: [] });\n\nexport class LocalPlatformProjectGrantStore implements IPlatformProjectGrantStore {\n\tprivate readonly filePath: string;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalPlatformProjectGrantStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalPlatformProjectGrantStore(\n\t\t\tpath.join(env.DATA_PATH, 'platform-project-grants.json')\n\t\t);\n\t}\n\n\tconstructor(filePath: string) {\n\t\tthis.filePath = filePath;\n\t}\n\n\tprivate async read(): Promise<OnDiskShape> {\n\t\treturn readJsonFile<OnDiskShape>(this.filePath, empty());\n\t}\n\n\tprivate async write(data: OnDiskShape): Promise<void> {\n\t\tawait writeJsonFile(this.filePath, data);\n\t}\n\n\tprivate locked<T>(fn: () => Promise<T>): Promise<T> {\n\t\treturn withFileLock(this.filePath, fn);\n\t}\n\n\tasync listByProject(_ctx: RequestContext, projectId: string): Promise<PlatformProjectGrant[]> {\n\t\tconst { grants } = await this.read();\n\t\treturn grants.filter((g) => g.projectId === projectId);\n\t}\n\n\tasync listByProjects(\n\t\t_ctx: RequestContext,\n\t\tprojectIds: readonly string[]\n\t): Promise<Map<string, PlatformProjectGrant[]>> {\n\t\tconst { grants } = await this.read();\n\t\tconst result = new Map(projectIds.map((id) => [id, [] as PlatformProjectGrant[]]));\n\t\tfor (const g of grants) result.get(g.projectId)?.push(g);\n\t\treturn result;\n\t}\n\n\tasync create(_ctx: RequestContext, grant: PlatformProjectGrant): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst data = await this.read();\n\t\t\tif (data.grants.some((g) => g.id === grant.id)) {\n\t\t\t\tthrow new ProviderError(`Grant '${grant.id}' already exists`, 409);\n\t\t\t}\n\t\t\tconst duplicate = data.grants.find(\n\t\t\t\t(g) =>\n\t\t\t\t\tg.projectId === grant.projectId &&\n\t\t\t\t\tg.granteeType === grant.granteeType &&\n\t\t\t\t\tg.granteeId === grant.granteeId\n\t\t\t);\n\t\t\tif (duplicate) {\n\t\t\t\tthrow new ProviderError(\n\t\t\t\t\t`A grant for this ${grant.granteeType} already exists on this project`,\n\t\t\t\t\t409\n\t\t\t\t);\n\t\t\t}\n\t\t\tdata.grants.push(grant);\n\t\t\tawait this.write(data);\n\t\t});\n\t}\n\n\tasync delete(_ctx: RequestContext, id: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst data = await this.read();\n\t\t\tconst idx = data.grants.findIndex((g) => g.id === id);\n\t\t\tif (idx === -1) throw new ProviderError(`Grant '${id}' not found`, 404);\n\t\t\tdata.grants.splice(idx, 1);\n\t\t\tawait this.write(data);\n\t\t});\n\t}\n\n\tasync deleteByProject(_ctx: RequestContext, projectId: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst data = await this.read();\n\t\t\tconst before = data.grants.length;\n\t\t\tdata.grants = data.grants.filter((g) => g.projectId !== projectId);\n\t\t\tif (data.grants.length !== before) await this.write(data);\n\t\t});\n\t}\n\n\tasync deleteByGranteeOrg(_ctx: RequestContext, orgId: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst data = await this.read();\n\t\t\tconst before = data.grants.length;\n\t\t\tdata.grants = data.grants.filter((g) => !(g.granteeType === 'org' && g.granteeId === orgId));\n\t\t\tif (data.grants.length !== before) await this.write(data);\n\t\t});\n\t}\n\n\t/** A user grant is the user's own, so it goes with them. */\n\tasync eraseUser(userId: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst data = await this.read();\n\t\t\tdata.grants = data.grants\n\t\t\t\t.filter((g) => !(g.granteeType === 'user' && g.granteeId === userId))\n\t\t\t\t.map((g) => (g.createdBy === userId ? { ...g, createdBy: ERASED_ACTOR_ID } : g));\n\t\t\tawait this.write(data);\n\t\t});\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tIOrgStore,\n\tIInviteStore,\n\tIApiTokenStore,\n\tIComputeServerStore,\n\tIDefinitionStore,\n\tIPlatformProjectGrantStore,\n\tIEventSink,\n\tOrganization,\n\tOrgRole,\n\tOrgPermission,\n\tOrgMember,\n\tProject,\n\tProjectMember,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport {\n\tDEFAULT_ORG_PERMISSIONS,\n\tERASED_ACTOR_ID,\n\tProviderError,\n\tauditUpdate,\n\tauditSoftDelete,\n\tactorOf,\n\tNoopEventSink\n} from '@selvajs/platform';\nimport { paginate, applyOrder } from './pagination.js';\nimport { CachedJsonFile } from './fsJson.js';\nimport { LocalInviteStore } from './LocalInviteStore.js';\nimport { LocalApiTokenStore } from './LocalApiTokenStore.js';\nimport { LocalComputeServerStore } from './LocalComputeServerStore.js';\nimport { LocalPlatformProjectGrantStore } from './LocalPlatformProjectGrantStore.js';\n\n/** Shape of the on-disk local-org.json file. */\nexport interface LocalOrgStoreData {\n\torgs: Organization[];\n\tprojects: Project[];\n\torgMembers: OrgMember[];\n\tprojectMembers: ProjectMember[];\n}\n\n/** Data-access-layer filter: row is live (not soft-deleted). */\nfunction isLive<T extends { deletedAt?: string | null }>(row: T): boolean {\n\treturn row.deletedAt == null;\n}\n\n/**\n * Shared by LocalOrgStore and LocalProjectStore — one instance so all\n * reads/writes go through one cache and one atomic write path.\n *\n */\nexport class LocalOrgStoreLoader {\n\treadonly storePath: string;\n\tprivate readonly file: CachedJsonFile<LocalOrgStoreData>;\n\n\tconstructor(dataPath: string) {\n\t\tthis.storePath = path.join(dataPath, 'local-org.json');\n\t\tthis.file = new CachedJsonFile(this.storePath, () => ({\n\t\t\torgs: [],\n\t\t\tprojects: [],\n\t\t\torgMembers: [],\n\t\t\tprojectMembers: []\n\t\t}));\n\t}\n\n\tget(): Promise<LocalOrgStoreData> {\n\t\treturn this.file.get();\n\t}\n\n\twrite(store: LocalOrgStoreData): Promise<void> {\n\t\treturn this.file.write(store);\n\t}\n}\n\nexport interface LocalOrgStoreOptions {\n\tloader: LocalOrgStoreLoader;\n\t/**\n\t * Sibling stores for the `deleteOrg` cascade — invites, API tokens, compute\n\t * config, and grants live in separate JSON files the loader can't reach. Required, not\n\t * optional: an unwired cascade silently leaks operational data.\n\t */\n\tinvites: IInviteStore;\n\tapiTokens: IApiTokenStore;\n\tcomputeServer: IComputeServerStore;\n\tgrants: IPlatformProjectGrantStore;\n\tevents?: IEventSink;\n}\n\nexport class LocalOrgStore implements IOrgStore {\n\tprivate readonly loader: LocalOrgStoreLoader;\n\tprivate definitions?: IDefinitionStore;\n\tprivate readonly events: IEventSink;\n\tprivate readonly invites: IInviteStore;\n\tprivate readonly apiTokens: IApiTokenStore;\n\tprivate readonly computeServer: IComputeServerStore;\n\tprivate readonly grants: IPlatformProjectGrantStore;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalOrgStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalOrgStore({\n\t\t\tloader: new LocalOrgStoreLoader(env.DATA_PATH),\n\t\t\tinvites: LocalInviteStore.fromEnv(env),\n\t\t\tapiTokens: LocalApiTokenStore.fromEnv(env),\n\t\t\tcomputeServer: LocalComputeServerStore.fromEnv(env),\n\t\t\tgrants: LocalPlatformProjectGrantStore.fromEnv(env)\n\t\t});\n\t}\n\n\tconstructor(opts: LocalOrgStoreOptions) {\n\t\tthis.loader = opts.loader;\n\t\tthis.invites = opts.invites;\n\t\tthis.apiTokens = opts.apiTokens;\n\t\tthis.computeServer = opts.computeServer;\n\t\tthis.grants = opts.grants;\n\t\tthis.events = opts.events ?? new NoopEventSink();\n\t}\n\n\t/** A setter rather than an option: the definition store is built after this one. */\n\tsetDefinitionProvider(definitions: IDefinitionStore): void {\n\t\tthis.definitions = definitions;\n\t}\n\n\t/** Removes the user's membership rows, soft-deleted ones too, and their name elsewhere. */\n\tasync eraseUser(userId: string): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst erased = <T extends { updatedBy?: string }>(row: T): T =>\n\t\t\trow.updatedBy === userId ? { ...row, updatedBy: ERASED_ACTOR_ID } : row;\n\t\tconst erasedOwner = <T extends { ownerId: string; createdBy: string; updatedBy: string }>(\n\t\t\trow: T\n\t\t): T =>\n\t\t\terased({\n\t\t\t\t...row,\n\t\t\t\townerId: row.ownerId === userId ? ERASED_ACTOR_ID : row.ownerId,\n\t\t\t\tcreatedBy: row.createdBy === userId ? ERASED_ACTOR_ID : row.createdBy\n\t\t\t});\n\t\tstore.orgs = store.orgs.map(erasedOwner);\n\t\tstore.projects = store.projects.map(erasedOwner);\n\t\tstore.orgMembers = store.orgMembers.filter((m) => m.userId !== userId).map(erased);\n\t\tstore.projectMembers = store.projectMembers.filter((m) => m.userId !== userId).map(erased);\n\t\tawait this.loader.write(store);\n\t}\n\n\tasync listOrgs(_ctx: RequestContext, opts?: ListOptions): Promise<Page<Organization>> {\n\t\tconst { orgs } = await this.loader.get();\n\t\treturn paginate(applyOrder(orgs.filter(isLive), opts), opts);\n\t}\n\n\tasync getOrg(_ctx: RequestContext, id: string): Promise<Organization | null> {\n\t\tconst { orgs } = await this.loader.get();\n\t\tconst o = orgs.find((o) => o.id === id);\n\t\treturn o && isLive(o) ? o : null;\n\t}\n\n\tasync getOrgBySlug(_ctx: RequestContext, slug: string): Promise<Organization | null> {\n\t\tconst { orgs } = await this.loader.get();\n\t\tconst o = orgs.find((o) => o.slug === slug);\n\t\treturn o && isLive(o) ? o : null;\n\t}\n\n\tasync createOrg(ctx: RequestContext, org: Organization): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tif (store.orgs.some((o) => o.id === org.id && isLive(o))) {\n\t\t\tthrow new ProviderError(`Org '${org.id}' already exists`, 409);\n\t\t}\n\t\tif (store.orgs.some((o) => o.slug === org.slug && isLive(o))) {\n\t\t\tthrow new ProviderError(`Org slug '${org.slug}' already in use`, 409);\n\t\t}\n\t\tstore.orgs.push({ ...org, deletedAt: null });\n\t\tconst now = new Date().toISOString();\n\t\tstore.orgMembers.push({\n\t\t\torgId: org.id,\n\t\t\tuserId: org.ownerId,\n\t\t\trole: 'owner',\n\t\t\tpermissions: [...DEFAULT_ORG_PERMISSIONS.owner],\n\t\t\tjoinedAt: now,\n\t\t\t...auditUpdate(ctx, org.ownerId),\n\t\t\tdeletedAt: null\n\t\t});\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({ type: 'org.created', orgId: org.id, ...actorOf(ctx) });\n\t}\n\n\tasync updateOrg(\n\t\tctx: RequestContext,\n\t\tid: string,\n\t\tpatch: Partial<Pick<Organization, 'name' | 'slug' | 'assets'>>\n\t): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst idx = store.orgs.findIndex((o) => o.id === id && isLive(o));\n\t\tif (idx === -1) throw new ProviderError(`Org '${id}' not found`, 404);\n\t\tif (patch.slug && patch.slug !== store.orgs[idx].slug) {\n\t\t\tif (store.orgs.some((o) => o.id !== id && o.slug === patch.slug && isLive(o))) {\n\t\t\t\tthrow new ProviderError(`Org slug '${patch.slug}' already in use`, 409);\n\t\t\t}\n\t\t}\n\t\tstore.orgs[idx] = {\n\t\t\t...store.orgs[idx],\n\t\t\t...patch,\n\t\t\t...auditUpdate(ctx, store.orgs[idx].updatedBy ?? store.orgs[idx].ownerId)\n\t\t};\n\t\tawait this.loader.write(store);\n\t}\n\n\tasync deleteOrg(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst idx = store.orgs.findIndex((o) => o.id === id && isLive(o));\n\t\tif (idx === -1) throw new ProviderError(`Org '${id}' not found`, 404);\n\t\tconst stamp = auditSoftDelete(ctx, store.orgs[idx].updatedBy ?? store.orgs[idx].ownerId);\n\t\tstore.orgs[idx] = { ...store.orgs[idx], ...stamp };\n\t\tstore.orgMembers = store.orgMembers.map((m) =>\n\t\t\tm.orgId === id && isLive(m) ? { ...m, ...stamp } : m\n\t\t);\n\t\tconst orgProjectIds = new Set(\n\t\t\tstore.projects.filter((p) => p.orgId === id && isLive(p)).map((p) => p.id)\n\t\t);\n\t\tstore.projects = store.projects.map((p) =>\n\t\t\tp.orgId === id && isLive(p) ? { ...p, ...stamp } : p\n\t\t);\n\t\tstore.projectMembers = store.projectMembers.map((m) =>\n\t\t\torgProjectIds.has(m.projectId) && isLive(m) ? { ...m, ...stamp } : m\n\t\t);\n\t\tawait this.loader.write(store);\n\t\t// Invites and compute config are operational, not user data, so they\n\t\t// hard-delete rather than soft-delete — no audit trail to preserve.\n\t\tawait this.invites.deleteByOrg(ctx, id);\n\t\tawait this.apiTokens.deleteByOrg(ctx, id);\n\t\tawait this.computeServer.deleteByOrg(ctx, id);\n\t\tif (this.definitions) {\n\t\t\tfor (const projectId of orgProjectIds) {\n\t\t\t\tawait this.definitions.deleteByProject(ctx, projectId);\n\t\t\t}\n\t\t}\n\t\t// User grants survive — they're identity-scoped, not org-scoped.\n\t\tfor (const projectId of orgProjectIds) {\n\t\t\tawait this.grants.deleteByProject(ctx, projectId);\n\t\t}\n\t\tawait this.grants.deleteByGranteeOrg(ctx, id);\n\t\tawait this.events.emit({ type: 'org.deleted', orgId: id, ...actorOf(ctx) });\n\t}\n\n\tasync listOrgMembers(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<OrgMember>> {\n\t\tconst { orgMembers } = await this.loader.get();\n\t\treturn paginate(\n\t\t\torgMembers.filter((m) => m.orgId === orgId && isLive(m)),\n\t\t\topts\n\t\t);\n\t}\n\n\tasync getOrgMember(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string\n\t): Promise<OrgMember | null> {\n\t\tconst { orgMembers } = await this.loader.get();\n\t\tconst m = orgMembers.find((m) => m.orgId === orgId && m.userId === userId);\n\t\treturn m && isLive(m) ? m : null;\n\t}\n\n\tasync countOrgMembers(\n\t\t_ctx: RequestContext,\n\t\torgIds: readonly string[]\n\t): Promise<Map<string, number>> {\n\t\tconst { orgMembers } = await this.loader.get();\n\t\tconst counts = new Map<string, number>(orgIds.map((id) => [id, 0]));\n\t\tfor (const m of orgMembers) {\n\t\t\tconst n = counts.get(m.orgId);\n\t\t\tif (n !== undefined && isLive(m)) counts.set(m.orgId, n + 1);\n\t\t}\n\t\treturn counts;\n\t}\n\n\tasync getOrgMembersFor(\n\t\t_ctx: RequestContext,\n\t\torgIds: readonly string[],\n\t\tuserId: string\n\t): Promise<Map<string, OrgMember | null>> {\n\t\tconst { orgMembers } = await this.loader.get();\n\t\tconst byOrgId = new Map(\n\t\t\torgMembers.filter((m) => m.userId === userId && isLive(m)).map((m) => [m.orgId, m])\n\t\t);\n\t\treturn new Map(orgIds.map((id) => [id, byOrgId.get(id) ?? null]));\n\t}\n\n\tasync findUserMembership(\n\t\t_ctx: RequestContext,\n\t\tuserId: string\n\t): Promise<{ org: Organization; member: OrgMember } | null> {\n\t\t// Picks the first live membership; ordering follows insertion order in\n\t\t// the JSON file, stable across reads.\n\t\tconst store = await this.loader.get();\n\t\tconst member = store.orgMembers.find((m) => m.userId === userId && isLive(m));\n\t\tif (!member) return null;\n\t\tconst org = store.orgs.find((o) => o.id === member.orgId);\n\t\t// A membership pointing at a soft-deleted org counts as gone, same as the\n\t\t// SQL adapter gets via FK + RLS on `orgs.deleted_at`.\n\t\tif (!org || !isLive(org)) return null;\n\t\treturn { org, member };\n\t}\n\n\tasync addOrgMember(ctx: RequestContext, member: OrgMember): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\t// Reactivate a prior soft-deleted row rather than piling rows up.\n\t\tconst existing = store.orgMembers.find(\n\t\t\t(m) => m.orgId === member.orgId && m.userId === member.userId\n\t\t);\n\t\tif (existing) {\n\t\t\tObject.assign(existing, member, {\n\t\t\t\t...auditUpdate(ctx, member.userId),\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t} else {\n\t\t\tstore.orgMembers.push({ ...member, deletedAt: null });\n\t\t}\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.added',\n\t\t\torgId: member.orgId,\n\t\t\tuserId: member.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateOrgMemberRole(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string,\n\t\trole: OrgRole\n\t): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst m = store.orgMembers.find((m) => m.orgId === orgId && m.userId === userId && isLive(m));\n\t\tif (!m) throw new ProviderError(`Org member '${userId}' not found`, 404);\n\t\tm.role = role;\n\t\t// Resets permissions to the role's defaults. To keep a custom set, call\n\t\t// updateOrgMemberPermissions after this.\n\t\tm.permissions = [...DEFAULT_ORG_PERMISSIONS[role]];\n\t\tObject.assign(m, auditUpdate(ctx, m.updatedBy));\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.role_changed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\trole,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateOrgMemberPermissions(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string,\n\t\tpermissions: readonly OrgPermission[]\n\t): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst m = store.orgMembers.find((m) => m.orgId === orgId && m.userId === userId && isLive(m));\n\t\tif (!m) throw new ProviderError(`Org member '${userId}' not found`, 404);\n\t\tm.permissions = [...permissions];\n\t\tObject.assign(m, auditUpdate(ctx, m.updatedBy));\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.permissions_changed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\tpermissions: [...permissions],\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync removeOrgMember(ctx: RequestContext, orgId: string, userId: string): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst m = store.orgMembers.find((m) => m.orgId === orgId && m.userId === userId && isLive(m));\n\t\tif (!m) throw new ProviderError(`Org member '${userId}' not found`, 404);\n\t\tconst stamp = auditSoftDelete(ctx, m.updatedBy);\n\t\tObject.assign(m, stamp);\n\n\t\t// Losing org membership ends every project membership in that org, so\n\t\t// \"members ⊂ org members\" stays true without reads having to re-check it.\n\t\tconst projectIdsInOrg = new Set(\n\t\t\tstore.projects.filter((p) => p.orgId === orgId).map((p) => p.id)\n\t\t);\n\t\tstore.projectMembers = store.projectMembers.map((pm) =>\n\t\t\tpm.userId === userId && projectIdsInOrg.has(pm.projectId) && isLive(pm)\n\t\t\t\t? { ...pm, ...stamp }\n\t\t\t\t: pm\n\t\t);\n\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.removed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n","import type {\n\tIProjectStore,\n\tIPlatformProjectGrantStore,\n\tIDefinitionStore,\n\tIEventSink,\n\tProject,\n\tProjectRole,\n\tProjectMember,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport {\n\tProviderError,\n\tauditUpdate,\n\tauditSoftDelete,\n\tactorOf,\n\tNoopEventSink\n} from '@selvajs/platform';\nimport { paginate, applyOrder } from './pagination.js';\nimport type { LocalOrgStoreLoader } from './LocalOrgStore.js';\n\n/** Data-access-layer filter — never let a soft-deleted row surface to callers. */\nfunction isLive<T extends { deletedAt?: string | null }>(row: T): boolean {\n\treturn row.deletedAt == null;\n}\n\nexport interface LocalProjectStoreOptions {\n\tloader: LocalOrgStoreLoader;\n\t/**\n\t * Sibling store for the `deleteProject` cascade — grants live in a separate\n\t * JSON file the loader can't reach. Required, not optional: an unwired\n\t * cascade leaks grants on platform projects after deletion.\n\t */\n\tgrants: IPlatformProjectGrantStore;\n\tevents?: IEventSink;\n}\n\nexport class LocalProjectStore implements IProjectStore {\n\tprivate readonly loader: LocalOrgStoreLoader;\n\tprivate readonly events: IEventSink;\n\tprivate readonly grants: IPlatformProjectGrantStore;\n\tprivate definitions?: IDefinitionStore;\n\n\tconstructor(opts: LocalProjectStoreOptions) {\n\t\tthis.loader = opts.loader;\n\t\tthis.grants = opts.grants;\n\t\tthis.events = opts.events ?? new NoopEventSink();\n\t}\n\n\t/**\n\t * Wires the definition store for the `deleteProject` cascade. A setter, not\n\t * a constructor param, because the composition root builds this store\n\t * before the definition store (whose `setProjectProvider` depends on this\n\t * one). Unwired, deleted projects keep leaking their definitions into the\n\t * library/public listings.\n\t */\n\tsetDefinitionProvider(definitions: IDefinitionStore): void {\n\t\tthis.definitions = definitions;\n\t}\n\n\tasync listProjects(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<Project>> {\n\t\tconst { projects } = await this.loader.get();\n\t\treturn paginate(\n\t\t\tapplyOrder(\n\t\t\t\tprojects.filter((p) => p.orgId === orgId && isLive(p)),\n\t\t\t\topts\n\t\t\t),\n\t\t\topts\n\t\t);\n\t}\n\n\tasync getProject(_ctx: RequestContext, id: string): Promise<Project | null> {\n\t\tconst { projects } = await this.loader.get();\n\t\tconst p = projects.find((p) => p.id === id);\n\t\treturn p && isLive(p) ? p : null;\n\t}\n\n\tasync getProjectBySlug(\n\t\t_ctx: RequestContext,\n\t\torgId: string,\n\t\tslug: string\n\t): Promise<Project | null> {\n\t\tconst { projects } = await this.loader.get();\n\t\tconst p = projects.find((p) => p.orgId === orgId && p.slug === slug);\n\t\treturn p && isLive(p) ? p : null;\n\t}\n\n\tasync createProject(ctx: RequestContext, project: Project): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tif (!store.orgs.some((o) => o.id === project.orgId && isLive(o))) {\n\t\t\tthrow new ProviderError(`Org '${project.orgId}' not found`, 404);\n\t\t}\n\t\tif (store.projects.some((p) => p.id === project.id && isLive(p))) {\n\t\t\tthrow new ProviderError(`Project '${project.id}' already exists`, 409);\n\t\t}\n\t\tconst nameKey = project.name.toLowerCase();\n\t\tif (\n\t\t\tstore.projects.some(\n\t\t\t\t(p) => p.orgId === project.orgId && isLive(p) && p.name.toLowerCase() === nameKey\n\t\t\t)\n\t\t) {\n\t\t\tthrow new ProviderError('projects_org_name_unique: project name already in use', 409);\n\t\t}\n\t\tif (\n\t\t\tstore.projects.some((p) => p.orgId === project.orgId && isLive(p) && p.slug === project.slug)\n\t\t) {\n\t\t\tthrow new ProviderError('projects_org_id_slug_key: project slug already in use', 409);\n\t\t}\n\t\tstore.projects.push({ ...project, deletedAt: null });\n\t\tstore.projectMembers.push({\n\t\t\tprojectId: project.id,\n\t\t\tuserId: project.ownerId,\n\t\t\trole: 'owner',\n\t\t\tjoinedAt: project.createdAt,\n\t\t\tupdatedAt: project.createdAt,\n\t\t\tupdatedBy: project.ownerId,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project.created',\n\t\t\tprojectId: project.id,\n\t\t\torgId: project.orgId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateProject(\n\t\tctx: RequestContext,\n\t\tid: string,\n\t\tpatch: Partial<\n\t\t\tPick<Project, 'name' | 'slug' | 'description' | 'visibility' | 'autoJoinOnUpload'>\n\t\t>\n\t): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst idx = store.projects.findIndex((p) => p.id === id && isLive(p));\n\t\tif (idx === -1) throw new ProviderError(`Project '${id}' not found`, 404);\n\n\t\tconst current = store.projects[idx];\n\n\t\tif (patch.name && patch.name.toLowerCase() !== current.name.toLowerCase()) {\n\t\t\tconst nameKey = patch.name.toLowerCase();\n\t\t\tif (\n\t\t\t\tstore.projects.some(\n\t\t\t\t\t(p) =>\n\t\t\t\t\t\tp.orgId === current.orgId &&\n\t\t\t\t\t\tp.id !== id &&\n\t\t\t\t\t\tisLive(p) &&\n\t\t\t\t\t\tp.name.toLowerCase() === nameKey\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow new ProviderError('projects_org_name_unique: project name already in use', 409);\n\t\t\t}\n\t\t}\n\n\t\tif (patch.slug && patch.slug !== current.slug) {\n\t\t\tif (\n\t\t\t\tstore.projects.some(\n\t\t\t\t\t(p) => p.orgId === current.orgId && p.slug === patch.slug && p.id !== id && isLive(p)\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow new ProviderError('projects_org_id_slug_key: project slug already in use', 409);\n\t\t\t}\n\t\t}\n\n\t\tstore.projects[idx] = {\n\t\t\t...current,\n\t\t\t...patch,\n\t\t\t...auditUpdate(ctx, current.updatedBy ?? current.ownerId)\n\t\t};\n\t\tawait this.loader.write(store);\n\t}\n\n\tasync deleteProject(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst idx = store.projects.findIndex((p) => p.id === id && isLive(p));\n\t\tif (idx === -1) throw new ProviderError(`Project '${id}' not found`, 404);\n\t\tconst stamp = auditSoftDelete(\n\t\t\tctx,\n\t\t\tstore.projects[idx].updatedBy ?? store.projects[idx].ownerId\n\t\t);\n\t\tstore.projects[idx] = { ...store.projects[idx], ...stamp };\n\t\tstore.projectMembers = store.projectMembers.map((m) =>\n\t\t\tm.projectId === id && isLive(m) ? { ...m, ...stamp } : m\n\t\t);\n\t\tawait this.loader.write(store);\n\t\t// A deleted project must stop serving its definitions — they surface in\n\t\t// library/public listings keyed on the definition row, independent of\n\t\t// the project. Supabase does the same cascade.\n\t\tawait this.definitions?.deleteByProject(ctx, id);\n\t\t// Grants have no soft-delete column, so this hard-deletes them.\n\t\tawait this.grants.deleteByProject(ctx, id);\n\t\tawait this.events.emit({ type: 'project.deleted', projectId: id, ...actorOf(ctx) });\n\t}\n\n\tasync reactivateProject(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tslug: string\n\t): Promise<Project | null> {\n\t\tconst store = await this.loader.get();\n\t\tconst idx = store.projects.findIndex((p) => p.orgId === orgId && p.slug === slug && !isLive(p));\n\t\tif (idx === -1) return null;\n\n\t\tconst now = new Date().toISOString();\n\t\tstore.projects[idx] = { ...store.projects[idx], deletedAt: null, updatedAt: now };\n\n\t\tconst ownerId = store.projects[idx].ownerId;\n\t\tconst pmIdx = store.projectMembers.findIndex(\n\t\t\t(m) => m.projectId === store.projects[idx].id && m.userId === ownerId && !isLive(m)\n\t\t);\n\t\tif (pmIdx !== -1) {\n\t\t\tstore.projectMembers[pmIdx] = {\n\t\t\t\t...store.projectMembers[pmIdx],\n\t\t\t\tdeletedAt: null,\n\t\t\t\tupdatedAt: now\n\t\t\t};\n\t\t}\n\n\t\tawait this.loader.write(store);\n\t\tconst project = { ...store.projects[idx] };\n\t\tawait this.events.emit({\n\t\t\ttype: 'project.created',\n\t\t\tprojectId: project.id,\n\t\t\torgId: project.orgId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t\treturn project;\n\t}\n\n\tasync listProjectMembers(\n\t\t_ctx: RequestContext,\n\t\tprojectId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<ProjectMember>> {\n\t\tconst { projectMembers } = await this.loader.get();\n\t\treturn paginate(\n\t\t\tprojectMembers.filter((m) => m.projectId === projectId && isLive(m)),\n\t\t\topts\n\t\t);\n\t}\n\n\tasync getProjectMember(\n\t\t_ctx: RequestContext,\n\t\tprojectId: string,\n\t\tuserId: string\n\t): Promise<ProjectMember | null> {\n\t\tconst { projectMembers } = await this.loader.get();\n\t\tconst m = projectMembers.find((m) => m.projectId === projectId && m.userId === userId);\n\t\treturn m && isLive(m) ? m : null;\n\t}\n\n\tasync getProjectMembersFor(\n\t\t_ctx: RequestContext,\n\t\tprojectIds: readonly string[],\n\t\tuserId: string\n\t): Promise<Map<string, ProjectMember | null>> {\n\t\tconst { projectMembers } = await this.loader.get();\n\t\tconst byProjectId = new Map(\n\t\t\tprojectMembers.filter((m) => m.userId === userId && isLive(m)).map((m) => [m.projectId, m])\n\t\t);\n\t\treturn new Map(projectIds.map((id) => [id, byProjectId.get(id) ?? null]));\n\t}\n\n\tasync countProjectMembers(\n\t\t_ctx: RequestContext,\n\t\tprojectIds: readonly string[]\n\t): Promise<Map<string, number>> {\n\t\tconst { projectMembers } = await this.loader.get();\n\t\tconst counts = new Map<string, number>(projectIds.map((id) => [id, 0]));\n\t\tfor (const m of projectMembers) {\n\t\t\tconst n = counts.get(m.projectId);\n\t\t\tif (n !== undefined && isLive(m)) counts.set(m.projectId, n + 1);\n\t\t}\n\t\treturn counts;\n\t}\n\n\tasync addProjectMember(ctx: RequestContext, member: ProjectMember): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\t// Reactivate a prior soft-deleted row rather than piling rows up.\n\t\tconst existing = store.projectMembers.find(\n\t\t\t(m) => m.projectId === member.projectId && m.userId === member.userId\n\t\t);\n\t\tif (existing) {\n\t\t\tObject.assign(existing, member, {\n\t\t\t\t...auditUpdate(ctx, member.userId),\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t} else {\n\t\t\tconst stamp = auditUpdate(ctx, member.userId);\n\t\t\tstore.projectMembers.push({\n\t\t\t\t...member,\n\t\t\t\tupdatedAt: member.updatedAt ?? stamp.updatedAt,\n\t\t\t\tupdatedBy: member.updatedBy ?? stamp.updatedBy,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t}\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.added',\n\t\t\tprojectId: member.projectId,\n\t\t\tuserId: member.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateProjectMemberRole(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\tuserId: string,\n\t\trole: ProjectRole\n\t): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst m = store.projectMembers.find(\n\t\t\t(m) => m.projectId === projectId && m.userId === userId && isLive(m)\n\t\t);\n\t\tif (!m) throw new ProviderError(`Project member '${userId}' not found`, 404);\n\t\tm.role = role;\n\t\tObject.assign(m, auditUpdate(ctx, m.updatedBy));\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.role_changed',\n\t\t\tprojectId,\n\t\t\tuserId,\n\t\t\trole,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync removeProjectMember(ctx: RequestContext, projectId: string, userId: string): Promise<void> {\n\t\tconst store = await this.loader.get();\n\t\tconst m = store.projectMembers.find(\n\t\t\t(m) => m.projectId === projectId && m.userId === userId && isLive(m)\n\t\t);\n\t\tif (!m) return;\n\t\tObject.assign(m, auditSoftDelete(ctx, m.updatedBy));\n\t\tawait this.loader.write(store);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.removed',\n\t\t\tprojectId,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tIDefinitionStore,\n\tIProjectStore,\n\tIEventSink,\n\tDefinitionRecord,\n\tDefinitionRecordPatch,\n\tDefinitionVersion,\n\tRequestContext,\n\tDefinitionListOptions,\n\tListOptions,\n\tPage,\n\tUISchema,\n\tDocumentInventory,\n\tInventorySummary\n} from '@selvajs/platform';\nimport {\n\tERASED_ACTOR_ID,\n\tProviderError,\n\tauditUpdate,\n\tauditSoftDelete,\n\tactorOf,\n\tNoopEventSink\n} from '@selvajs/platform';\nimport { paginate, applyOrder } from './pagination.js';\nimport { CachedJsonFile } from './fsJson.js';\n\ninterface DefinitionsConfig {\n\tdefinitions: Record<string, DefinitionRecord>;\n\tdefinitionVersions: Record<string, DefinitionVersion>;\n}\n\n// `readJsonFile` returns its fallback by reference when the file is missing,\n// so a shared singleton here would let one read's mutations pollute the next.\nconst empty = (): DefinitionsConfig => ({ definitions: {}, definitionVersions: {} });\n\nexport class LocalDefinitionStore implements IDefinitionStore {\n\tprivate readonly file: CachedJsonFile<DefinitionsConfig>;\n\tprivate readonly events: IEventSink;\n\tprivate projectProvider?: IProjectStore;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalDefinitionStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalDefinitionStore(env.DATA_PATH);\n\t}\n\n\tconstructor(\n\t\tdefinitionsPath: string,\n\t\tprojectProvider?: IProjectStore,\n\t\tevents: IEventSink = new NoopEventSink()\n\t) {\n\t\t// Constructed once per provider, and the share-link store gets this instance\n\t\t// (see LocalDataProvider.fromEnv), so there is one cache over the file.\n\t\tthis.file = new CachedJsonFile(path.join(definitionsPath, 'definitions-config.json'), empty);\n\t\tthis.projectProvider = projectProvider;\n\t\tthis.events = events;\n\t}\n\n\tsetProjectProvider(projectProvider: IProjectStore): void {\n\t\tthis.projectProvider = projectProvider;\n\t}\n\n\tprivate readConfig(): Promise<DefinitionsConfig> {\n\t\treturn this.file.get();\n\t}\n\n\t/**\n\t * Does not stop a prototype lookup: `definitions['__proto__']` returns\n\t * `Object.prototype`, whose `deletedAt` is undefined, so it passes as live\n\t * and the caller's `Object.assign` writes onto the prototype. Callers reach\n\t * this only behind `GuidSchema`, which rejects non-UUID keys — keep it that\n\t * way for any new entry point.\n\t */\n\tprivate live(record: DefinitionRecord | undefined | null): record is DefinitionRecord {\n\t\treturn Boolean(record && record.deletedAt == null);\n\t}\n\n\tprivate writeConfig(config: DefinitionsConfig): Promise<void> {\n\t\treturn this.file.write(config);\n\t}\n\n\t/** Definitions outlive their uploader, so only the name on them goes. */\n\tasync eraseUser(userId: string): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tfor (const record of Object.values(config.definitions)) {\n\t\t\tif (record.ownerId === userId) record.ownerId = ERASED_ACTOR_ID;\n\t\t\tif (record.createdBy === userId) record.createdBy = ERASED_ACTOR_ID;\n\t\t\tif (record.updatedBy === userId) record.updatedBy = ERASED_ACTOR_ID;\n\t\t}\n\t\tfor (const version of Object.values(config.definitionVersions)) {\n\t\t\tif (version.uploadedBy === userId) version.uploadedBy = ERASED_ACTOR_ID;\n\t\t}\n\t\tawait this.writeConfig(config);\n\t}\n\n\tprivate sortedRecords(\n\t\trecords: DefinitionRecord[],\n\t\topts?: DefinitionListOptions\n\t): DefinitionRecord[] {\n\t\tconst defaulted: DefinitionListOptions = {\n\t\t\t...opts,\n\t\t\torderBy: opts?.orderBy ?? 'name',\n\t\t\torderDir: opts?.orderDir ?? 'asc'\n\t\t};\n\t\treturn applyOrder([...records], defaulted, (r, field) => {\n\t\t\tif (field === 'name') return r.displayName.toLowerCase();\n\t\t\tif (field === 'solveCount') return r.solveCount ?? 0;\n\t\t\treturn (r as unknown as Record<string, unknown>)[field];\n\t\t});\n\t}\n\n\tprivate visibleRecords(\n\t\trecords: DefinitionRecord[],\n\t\topts?: DefinitionListOptions\n\t): DefinitionRecord[] {\n\t\tlet filtered = records.filter((r) => r?.displayName && this.live(r));\n\t\tif (opts?.projectIds) {\n\t\t\tconst allowedProjects = new Set(opts.projectIds);\n\t\t\tfiltered = filtered.filter((r) => allowedProjects.has(r.projectId));\n\t\t}\n\t\tif (opts?.sourceDocumentId) {\n\t\t\tfiltered = filtered.filter((r) => r.sourceDocumentId === opts.sourceDocumentId);\n\t\t}\n\t\tif (opts?.statuses?.length) {\n\t\t\tconst allowed = new Set(opts.statuses);\n\t\t\treturn filtered.filter((r) => allowed.has(r.status));\n\t\t}\n\t\treturn filtered.filter((r) => {\n\t\t\tif (r.status === 'pending' && !opts?.includePending) return false;\n\t\t\tif (r.status === 'archived' && !opts?.includeArchived) return false;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync list(_ctx: RequestContext, opts?: DefinitionListOptions): Promise<Page<DefinitionRecord>> {\n\t\tconst config = await this.readConfig();\n\t\tconst records = this.visibleRecords(Object.values(config.definitions), opts);\n\t\treturn paginate(this.sortedRecords(records, opts), opts);\n\t}\n\n\tasync listByProject(\n\t\t_ctx: RequestContext,\n\t\tprojectId: string,\n\t\topts?: DefinitionListOptions\n\t): Promise<Page<DefinitionRecord>> {\n\t\tconst config = await this.readConfig();\n\t\tconst records = this.visibleRecords(\n\t\t\tObject.values(config.definitions).filter((r) => r?.projectId === projectId),\n\t\t\topts\n\t\t);\n\t\treturn paginate(this.sortedRecords(records, opts), opts);\n\t}\n\n\tasync listPublic(\n\t\tctx: RequestContext,\n\t\topts?: DefinitionListOptions & { orgId?: string }\n\t): Promise<Page<DefinitionRecord>> {\n\t\tif (!this.projectProvider) {\n\t\t\t// Before setProjectProvider is called, behave as if the default\n\t\t\t// project is public — matches the local bootstrap. Dead code after wiring.\n\t\t\treturn this.list(ctx, opts);\n\t\t}\n\n\t\tconst config = await this.readConfig();\n\t\tconst records = Object.values(config.definitions).filter((r): r is DefinitionRecord =>\n\t\t\tBoolean(r?.displayName && this.live(r))\n\t\t);\n\n\t\tconst projectIds = Array.from(new Set(records.map((r) => r.projectId)));\n\t\tconst projects = await Promise.all(\n\t\t\tprojectIds.map((id) => this.projectProvider!.getProject(ctx, id))\n\t\t);\n\t\tconst publicProjectIds = new Set(\n\t\t\tprojects\n\t\t\t\t.filter(\n\t\t\t\t\t(p): p is NonNullable<typeof p> =>\n\t\t\t\t\t\tp !== null && p.visibility === 'public' && (!opts?.orgId || p.orgId === opts.orgId)\n\t\t\t\t)\n\t\t\t\t.map((p) => p.id)\n\t\t);\n\n\t\tconst publicRecords = this.visibleRecords(\n\t\t\trecords.filter((r) => publicProjectIds.has(r.projectId)),\n\t\t\topts\n\t\t);\n\t\treturn paginate(this.sortedRecords(publicRecords, opts), opts);\n\t}\n\n\tasync get(_ctx: RequestContext, guid: string): Promise<DefinitionRecord | null> {\n\t\tconst config = await this.readConfig();\n\t\tconst r = config.definitions[guid];\n\t\treturn this.live(r) ? r : null;\n\t}\n\n\tasync getDefinitionsFor(\n\t\t_ctx: RequestContext,\n\t\tguids: readonly string[]\n\t): Promise<Map<string, DefinitionRecord>> {\n\t\tconst config = await this.readConfig();\n\t\tconst found = new Map<string, DefinitionRecord>();\n\t\tfor (const guid of guids) {\n\t\t\tconst r = config.definitions[guid];\n\t\t\tif (this.live(r)) found.set(guid, r);\n\t\t}\n\t\treturn found;\n\t}\n\n\tasync create(ctx: RequestContext, record: DefinitionRecord): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst actor = ctx.userId || record.ownerId;\n\t\tconfig.definitions[record.guid] = {\n\t\t\t...record,\n\t\t\tcreatedBy: record.createdBy || actor,\n\t\t\tupdatedBy: record.updatedBy || actor,\n\t\t\tliveVersionId: record.liveVersionId ?? null,\n\t\t\tdraftVersionId: record.draftVersionId ?? null,\n\t\t\tdeletedAt: null\n\t\t};\n\t\tawait this.writeConfig(config);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition.created',\n\t\t\tdefinitionId: record.guid,\n\t\t\tprojectId: record.projectId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync update(ctx: RequestContext, guid: string, patch: DefinitionRecordPatch): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst existing = config.definitions[guid];\n\t\tif (!this.live(existing)) throw new ProviderError(`Definition '${guid}' not found`, 404);\n\n\t\tconst clearable = (v: unknown) => (v === null ? undefined : v);\n\t\tconfig.definitions[guid] = {\n\t\t\t...existing,\n\t\t\t...(patch.displayName !== undefined && { displayName: patch.displayName }),\n\t\t\t...(patch.description !== undefined && {\n\t\t\t\tdescription: clearable(patch.description) as string | undefined\n\t\t\t}),\n\t\t\t...(patch.category !== undefined && {\n\t\t\t\tcategory: clearable(patch.category) as string | undefined\n\t\t\t}),\n\t\t\t...(patch.tags !== undefined && { tags: clearable(patch.tags) as string[] | undefined }),\n\t\t\t...(patch.coverImage !== undefined && {\n\t\t\t\tcoverImage: clearable(patch.coverImage) as string | undefined\n\t\t\t}),\n\t\t\t...(patch.projectId !== undefined && { projectId: patch.projectId }),\n\t\t\t...(patch.computeServerId !== undefined && {\n\t\t\t\tcomputeServerId: clearable(patch.computeServerId) as string | undefined\n\t\t\t}),\n\t\t\t...(patch.solveCacheLimit !== undefined && {\n\t\t\t\tsolveCacheLimit: clearable(patch.solveCacheLimit) as number | undefined\n\t\t\t}),\n\t\t\t...(patch.status !== undefined && { status: patch.status }),\n\t\t\t...(patch.ownerId !== undefined && { ownerId: patch.ownerId }),\n\t\t\t...(patch.sourceDocumentId !== undefined && {\n\t\t\t\tsourceDocumentId: clearable(patch.sourceDocumentId) as string | undefined\n\t\t\t}),\n\t\t\t...auditUpdate(ctx, existing.updatedBy ?? existing.ownerId)\n\t\t};\n\t\tawait this.writeConfig(config);\n\t}\n\n\tasync delete(ctx: RequestContext, guid: string): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst existing = config.definitions[guid];\n\t\tif (!this.live(existing)) return;\n\t\tObject.assign(existing, auditSoftDelete(ctx, existing.updatedBy ?? existing.ownerId));\n\t\tawait this.writeConfig(config);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition.deleted',\n\t\t\tdefinitionId: guid,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync deleteByProject(ctx: RequestContext, projectId: string): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\t// One read-modify-write pass over the cached config so the whole cascade\n\t\t// lands in a single `writeConfig`. Collect the affected guids first, then\n\t\t// emit one `definition.deleted` per tombstoned record after the write.\n\t\tconst affected: DefinitionRecord[] = [];\n\t\tfor (const record of Object.values(config.definitions)) {\n\t\t\tif (record.projectId === projectId && this.live(record)) {\n\t\t\t\tObject.assign(record, auditSoftDelete(ctx, record.updatedBy ?? record.ownerId));\n\t\t\t\taffected.push(record);\n\t\t\t}\n\t\t}\n\t\tif (affected.length === 0) return;\n\t\tawait this.writeConfig(config);\n\t\tfor (const record of affected) {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'definition.deleted',\n\t\t\t\tdefinitionId: record.guid,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\t}\n\n\tasync incrementSolveCount(_ctx: RequestContext, guid: string): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst existing = config.definitions[guid];\n\t\tif (!this.live(existing)) return;\n\t\texisting.solveCount = (existing.solveCount ?? 0) + 1;\n\t\texisting.updatedAt = new Date().toISOString();\n\t\tawait this.writeConfig(config);\n\t}\n\n\tasync reserveNextVersionNumber(_ctx: RequestContext, guid: string): Promise<number> {\n\t\tconst config = await this.readConfig();\n\t\tconst existing = config.definitions[guid];\n\t\tif (!this.live(existing)) throw new ProviderError(`Definition '${guid}' not found`, 404);\n\t\t// No `await` between the read and the increment, so nothing can interleave\n\t\t// on Node's single thread — concurrent uploads can't race this. Never reads\n\t\t// the version list once `nextVersionNumber` exists: the counter alone\n\t\t// advances, so a deleted latest version's number is never handed out again.\n\t\tconst current = existing.nextVersionNumber ?? this.highestVersionNumber(config, guid) + 1;\n\t\texisting.nextVersionNumber = current + 1;\n\t\texisting.updatedAt = new Date().toISOString();\n\t\tawait this.writeConfig(config);\n\t\treturn current;\n\t}\n\n\t/**\n\t * Highest `versionNumber` currently on disk for a definition (0 if none). Only\n\t * used as the seed when a legacy record predates `nextVersionNumber`; new\n\t * records carry the counter and never take this path.\n\t */\n\tprivate highestVersionNumber(\n\t\tconfig: { definitionVersions: Record<string, DefinitionVersion> },\n\t\tdefinitionId: string\n\t): number {\n\t\tlet max = 0;\n\t\tfor (const v of Object.values(config.definitionVersions)) {\n\t\t\tif (v.definitionId === definitionId && v.versionNumber > max) max = v.versionNumber;\n\t\t}\n\t\treturn max;\n\t}\n\n\t// ============================================================================\n\t// Versions\n\t// ============================================================================\n\n\tasync createVersion(ctx: RequestContext, version: DefinitionVersion): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst parent = config.definitions[version.definitionId];\n\t\tif (!this.live(parent)) {\n\t\t\tthrow new ProviderError(`Definition '${version.definitionId}' not found`, 404);\n\t\t}\n\t\tif (config.definitionVersions[version.id]) {\n\t\t\tthrow new ProviderError(`Version '${version.id}' already exists`, 409);\n\t\t}\n\t\tconfig.definitionVersions[version.id] = { ...version };\n\t\tawait this.writeConfig(config);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition_version.created',\n\t\t\tversionId: version.id,\n\t\t\tdefinitionId: version.definitionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync listVersions(\n\t\t_ctx: RequestContext,\n\t\tdefinitionId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<DefinitionVersion>> {\n\t\tconst config = await this.readConfig();\n\t\tconst parent = config.definitions[definitionId];\n\t\tif (!this.live(parent)) return paginate([], opts);\n\t\t// `schema`, `inventory` and `savedValues` are stripped to match the interface contract (and\n\t\t// Supabase, which leaves those columns out of the list projection): listed rows are metadata only,\n\t\t// and callers who need them go through `getVersion`.\n\t\tconst rows = Object.values(config.definitionVersions)\n\t\t\t.filter((v) => v.definitionId === definitionId)\n\t\t\t.sort((a, b) => b.versionNumber - a.versionNumber)\n\t\t\t.map(\n\t\t\t\t({ schema: _schema, inventory: _inventory, savedValues: _savedValues, ...rest }) => rest\n\t\t\t);\n\t\treturn paginate(rows, opts);\n\t}\n\n\tasync listVersionsFor(\n\t\t_ctx: RequestContext,\n\t\tdefinitionIds: readonly string[]\n\t): Promise<Map<string, DefinitionVersion[]>> {\n\t\tconst config = await this.readConfig();\n\t\tconst byDefinition = new Map<string, DefinitionVersion[]>(definitionIds.map((id) => [id, []]));\n\t\tfor (const {\n\t\t\tschema: _schema,\n\t\t\tinventory: _inventory,\n\t\t\tsavedValues: _savedValues,\n\t\t\t...version\n\t\t} of Object.values(config.definitionVersions)) {\n\t\t\tif (this.live(config.definitions[version.definitionId])) {\n\t\t\t\tbyDefinition.get(version.definitionId)?.push(version);\n\t\t\t}\n\t\t}\n\t\tfor (const versions of byDefinition.values()) {\n\t\t\tversions.sort((a, b) => b.versionNumber - a.versionNumber);\n\t\t}\n\t\treturn byDefinition;\n\t}\n\n\tasync getVersion(_ctx: RequestContext, versionId: string): Promise<DefinitionVersion | null> {\n\t\tconst config = await this.readConfig();\n\t\treturn config.definitionVersions[versionId] ?? null;\n\t}\n\n\tasync setVersionSchema(_ctx: RequestContext, versionId: string, schema: UISchema): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version) return;\n\t\tversion.schema = schema;\n\t\tversion.schemaExtractedAt = new Date().toISOString();\n\t\tawait this.writeConfig(config);\n\t}\n\n\tasync setVersionInventory(\n\t\t_ctx: RequestContext,\n\t\tversionId: string,\n\t\tinventory: DocumentInventory,\n\t\tsummary: InventorySummary\n\t): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version) return;\n\t\tversion.inventory = inventory;\n\t\tversion.inventorySummary = summary;\n\t\tawait this.writeConfig(config);\n\t}\n\n\tasync setVersionSavedValues(\n\t\t_ctx: RequestContext,\n\t\tversionId: string,\n\t\tvalues: Record<string, unknown>\n\t): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version) return;\n\t\tversion.savedValues = values;\n\t\tawait this.writeConfig(config);\n\t}\n\n\tasync deleteVersion(ctx: RequestContext, versionId: string): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version) return;\n\t\tconst parent = config.definitions[version.definitionId];\n\t\t// Cannot delete a version while it's serving live or draft — caller must\n\t\t// repoint first.\n\t\tif (parent && (parent.liveVersionId === versionId || parent.draftVersionId === versionId)) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Version '${versionId}' is referenced by liveVersionId or draftVersionId`,\n\t\t\t\t409\n\t\t\t);\n\t\t}\n\t\tdelete config.definitionVersions[versionId];\n\t\tawait this.writeConfig(config);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition_version.deleted',\n\t\t\tversionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync setLiveVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tawait this.repoint('live', ctx, definitionId, versionId);\n\t}\n\n\tasync setDraftVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tawait this.repoint('draft', ctx, definitionId, versionId);\n\t}\n\n\tasync attachInitialVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\t// Single read-modify-write pass: both pointers + status updated together.\n\t\t// `writeConfig` is one fs operation, so the 'pending' → 'draft'\n\t\t// transition is atomic from any subsequent reader's perspective.\n\t\tconst config = await this.readConfig();\n\t\tconst record = config.definitions[definitionId];\n\t\tif (!this.live(record)) throw new ProviderError(`Definition '${definitionId}' not found`, 404);\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version || version.definitionId !== definitionId) {\n\t\t\tthrow new ProviderError(`Version '${versionId}' not found for this definition`, 404);\n\t\t}\n\t\trecord.liveVersionId = versionId;\n\t\trecord.draftVersionId = versionId;\n\t\trecord.status = 'draft';\n\t\tObject.assign(record, auditUpdate(ctx, record.updatedBy ?? record.ownerId));\n\t\tawait this.writeConfig(config);\n\t\t// No `definition.published` event — see interface doc. The parent's\n\t\t// `definition.created` + `definition_version.created` (emitted earlier\n\t\t// in this transaction) cover the bootstrap.\n\t}\n\n\tprivate async repoint(\n\t\tchannel: 'live' | 'draft',\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tconst config = await this.readConfig();\n\t\tconst record = config.definitions[definitionId];\n\t\tif (!this.live(record)) throw new ProviderError(`Definition '${definitionId}' not found`, 404);\n\t\tconst version = config.definitionVersions[versionId];\n\t\tif (!version || version.definitionId !== definitionId) {\n\t\t\tthrow new ProviderError(`Version '${versionId}' not found for this definition`, 404);\n\t\t}\n\t\tif (channel === 'live') record.liveVersionId = versionId;\n\t\telse record.draftVersionId = versionId;\n\t\tObject.assign(record, auditUpdate(ctx, record.updatedBy ?? record.ownerId));\n\t\tawait this.writeConfig(config);\n\t\t// Only `live` advancement is the published-event trigger. Draft\n\t\t// repointing is silent — it's the editor's working pointer, not a\n\t\t// publication signal.\n\t\tif (channel === 'live') {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'definition.published',\n\t\t\t\tdefinitionId,\n\t\t\t\tversionId,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\t}\n}\n","import * as path from 'node:path';\nimport type {\n\tIShareLinkStore,\n\tIDefinitionStore,\n\tIProjectStore,\n\tIEventSink,\n\tOrgShareLink,\n\tShareLink,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { ProviderError, SYSTEM_CONTEXT, actorOf, NoopEventSink } from '@selvajs/platform';\nimport { paginate } from './pagination.js';\nimport { readJsonFile, withFileLock, writeJsonFile } from './fsJson.js';\n\ninterface OnDiskShape {\n\tlinks: Record<string, ShareLink>;\n}\n\nconst empty = (): OnDiskShape => ({ links: {} });\n\nexport interface LocalShareLinkStoreOptions {\n\t/** Absolute path to the JSON file backing this store. */\n\tfilePath: string;\n\tevents?: IEventSink;\n}\n\n/**\n * Writes queue on `withFileLock`, so `tryIncrementSolveCount` checks the cap and\n * counts as one step, but only within this process: two processes sharing\n * `share-links.json` can both admit the last solve under the cap.\n */\nexport class LocalShareLinkStore implements IShareLinkStore {\n\tprivate definitionProvider?: IDefinitionStore;\n\tprivate projectProvider?: IProjectStore;\n\tprivate readonly events: IEventSink;\n\tprivate readonly configFilePath: string;\n\n\t// Callers must still call `setDefinitionProvider` before token resolution or\n\t// solve counting, or the soft-delete cascade check silently no-ops.\n\t// LocalDataProvider wires this when it builds the store.\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalShareLinkStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalShareLinkStore({\n\t\t\tfilePath: path.join(env.DATA_PATH, 'share-links.json')\n\t\t});\n\t}\n\n\tconstructor(opts: LocalShareLinkStoreOptions) {\n\t\tthis.configFilePath = opts.filePath;\n\t\tthis.events = opts.events ?? new NoopEventSink();\n\t}\n\n\t/**\n\t * Wires the definition store so token resolution and solve counting can check\n\t * the parent definition's `deletedAt`, as Supabase does in SQL. Optional: if\n\t * unset, this falls back to the local-only revoke check, and the selva\n\t * app's route layer does the parent lookup as a safety net either way.\n\t */\n\tsetDefinitionProvider(definitions: IDefinitionStore): void {\n\t\tthis.definitionProvider = definitions;\n\t}\n\n\t/**\n\t * Wires the project store so `listByOrg` can complete the definition→project\n\t * hop that gives a link its org. Unset, the roster reads empty rather than\n\t * unfiltered — a share-link list that silently spans tenants is worse than\n\t * no list.\n\t */\n\tsetProjectProvider(projects: IProjectStore): void {\n\t\tthis.projectProvider = projects;\n\t}\n\n\tprivate async readAll(): Promise<OnDiskShape> {\n\t\treturn readJsonFile<OnDiskShape>(this.configFilePath, empty());\n\t}\n\n\tprivate async writeAll(data: OnDiskShape): Promise<void> {\n\t\tawait writeJsonFile(this.configFilePath, data);\n\t}\n\n\tprivate locked<T>(fn: () => Promise<T>): Promise<T> {\n\t\treturn withFileLock(this.configFilePath, fn);\n\t}\n\n\t// Revoked or expired counts as dead. Both providers filter both fields; a\n\t// link that reads live under one and dead under the other is the bug this\n\t// prevents.\n\tprivate isLive(l: ShareLink | undefined | null): l is ShareLink {\n\t\tif (!l || l.revokedAt != null) return false;\n\t\treturn l.expiresAt == null || Date.parse(l.expiresAt) > Date.now();\n\t}\n\n\tasync create(ctx: RequestContext, link: ShareLink): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tif (all.links[link.id]) {\n\t\t\t\tthrow new ProviderError(`Share link '${link.id}' already exists`, 409);\n\t\t\t}\n\t\t\tall.links[link.id] = { ...link, revokedAt: null };\n\t\t\tawait this.writeAll(all);\n\t\t});\n\t\tawait this.events.emit({\n\t\t\ttype: 'share_link.minted',\n\t\t\tlinkId: link.id,\n\t\t\tdefinitionId: link.definitionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync listByDefinition(\n\t\t_ctx: RequestContext,\n\t\tdefinitionId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<ShareLink>> {\n\t\tconst all = await this.readAll();\n\t\tconst rows = Object.values(all.links)\n\t\t\t.filter((l) => l.definitionId === definitionId && this.isLive(l))\n\t\t\t.sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n\t\treturn paginate(rows, opts);\n\t}\n\n\tasync listByOrg(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<OrgShareLink>> {\n\t\t// No org column on a link — the org is two hops up, through the parent\n\t\t// definition to its project. Supabase does this as a SQL join; here it is\n\t\t// a lookup, same as the soft-delete cascade in `getByTokenHash`.\n\t\tif (!this.definitionProvider || !this.projectProvider) return paginate([], opts);\n\n\t\tconst all = await this.readAll();\n\t\tconst live = Object.values(all.links).filter((l) => this.isLive(l));\n\t\tif (live.length === 0) return paginate([], opts);\n\n\t\tconst definitions = new Map(\n\t\t\tawait Promise.all(\n\t\t\t\t[...new Set(live.map((l) => l.definitionId))].map(\n\t\t\t\t\tasync (id) => [id, await this.definitionProvider!.get(SYSTEM_CONTEXT, id)] as const\n\t\t\t\t)\n\t\t\t)\n\t\t);\n\n\t\t// One page covers any realistic org; the roster is a per-tenant view.\n\t\tconst projects = await this.projectProvider.listProjects(ctx, orgId, { limit: 1000 });\n\t\tconst projectById = new Map(projects.items.map((p) => [p.id, p]));\n\n\t\tconst rows: OrgShareLink[] = [];\n\t\tfor (const link of live) {\n\t\t\tconst definition = definitions.get(link.definitionId);\n\t\t\t// A link whose definition is soft-deleted is unresolvable, so listing it\n\t\t\t// would offer a revoke that changes nothing.\n\t\t\tif (!definition) continue;\n\t\t\tconst project = projectById.get(definition.projectId);\n\t\t\tif (!project) continue;\n\t\t\tconst { tokenHash: _tokenHash, ...rest } = link;\n\t\t\trows.push({\n\t\t\t\t...rest,\n\t\t\t\tdefinitionName: definition.displayName,\n\t\t\t\tprojectId: project.id,\n\t\t\t\tprojectName: project.name\n\t\t\t});\n\t\t}\n\t\trows.sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n\t\treturn paginate(rows, opts);\n\t}\n\n\tasync getById(_ctx: RequestContext, id: string): Promise<ShareLink | null> {\n\t\tconst all = await this.readAll();\n\t\treturn all.links[id] ?? null;\n\t}\n\n\tasync getByTokenHash(_ctx: RequestContext, tokenHash: string): Promise<ShareLink | null> {\n\t\tconst all = await this.readAll();\n\t\tconst found = Object.values(all.links).find((l) => l.tokenHash === tokenHash);\n\t\tif (!this.isLive(found)) return null;\n\t\treturn (await this.parentIsLive(found)) ? found : null;\n\t}\n\n\t// Token resolution and solve counting must not see links whose parent\n\t// definition is soft-deleted — Supabase enforces this in SQL, here via lookup.\n\tprivate async parentIsLive(link: ShareLink): Promise<boolean> {\n\t\tif (!this.definitionProvider) return true;\n\t\treturn (await this.definitionProvider.get(SYSTEM_CONTEXT, link.definitionId)) !== null;\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst revoked = await this.locked(async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst l = all.links[id];\n\t\t\tif (!l) throw new ProviderError(`Share link '${id}' not found`, 404);\n\t\t\tif (!this.isLive(l)) return false; // idempotent\n\t\t\tl.revokedAt = new Date().toISOString();\n\t\t\tawait this.writeAll(all);\n\t\t\treturn true;\n\t\t});\n\t\tif (!revoked) return;\n\t\tawait this.events.emit({ type: 'share_link.revoked', linkId: id, ...actorOf(ctx) });\n\t}\n\n\tasync tryIncrementSolveCount(_ctx: RequestContext, id: string): Promise<number | null> {\n\t\treturn this.locked(async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tconst l = all.links[id];\n\t\t\tif (!l || !this.isLive(l)) return null;\n\t\t\tif (l.maxSolves != null && l.solveCount >= l.maxSolves) return null;\n\t\t\tif (!(await this.parentIsLive(l))) return null;\n\t\t\tl.solveCount += 1;\n\t\t\tawait this.writeAll(all);\n\t\t\treturn l.solveCount;\n\t\t});\n\t}\n\n\t/** A link goes with the user who minted it, as Supabase's `created_by` cascade does. */\n\tasync eraseUser(userId: string): Promise<void> {\n\t\tawait this.locked(async () => {\n\t\t\tconst all = await this.readAll();\n\t\t\tfor (const [id, link] of Object.entries(all.links)) {\n\t\t\t\tif (link.createdBy === userId) delete all.links[id];\n\t\t\t}\n\t\t\tawait this.writeAll(all);\n\t\t});\n\t}\n}\n","import { ProviderError } from '@selvajs/platform';\nimport type { PlatformPermission, RecentRun } from '@selvajs/platform';\nimport { MAX_RECENT_RUNS } from '@selvajs/platform/userProfile';\nimport { CachedJsonFile } from './fsJson.js';\n\n/**\n * Per-user state keyed by the auth provider's user ID. Mirrors\n * `public.user_profiles` in the Supabase schema. **Never holds identity**\n * (email, password hash, createdAt) — that lives with the auth provider.\n *\n * `hooks.server.ts` calls `IDataProvider.ensureUser` once per authenticated\n * request (the local equivalent of Supabase's `handle_new_auth_user`\n * trigger), so every read here after that is guaranteed to find a row.\n */\nexport interface StoredUserData {\n\tuserId: string;\n\tdisplayName?: string;\n\tplatformPermissions: PlatformPermission[];\n\tstarredDefinitions: string[];\n\trecentRuns: RecentRun[];\n}\n\nexport interface UserDataFile {\n\tusers: StoredUserData[];\n}\n\nconst empty = (): UserDataFile => ({ users: [] });\n\nfunction emptyRow(userId: string): StoredUserData {\n\treturn {\n\t\tuserId,\n\t\tplatformPermissions: [],\n\t\tstarredDefinitions: [],\n\t\trecentRuns: []\n\t};\n}\n\nexport interface LocalUserDataStore {\n\t/** Idempotent: adds an empty row if missing, no-op if present. */\n\tensure(userId: string): Promise<void>;\n\tfindById(userId: string): Promise<StoredUserData | null>;\n\tlistAll(): Promise<StoredUserData[]>;\n\tupdatePermissions(userId: string, permissions: PlatformPermission[]): Promise<void>;\n\t/**\n\t * Write `permissions`, but only while the §2 sole-`instance_admin`\n\t * invariant still holds — the count and the write happen without an\n\t * `await` between them, so two concurrent demotions cannot both observe\n\t * the other as \"another admin exists\".\n\t *\n\t * Returns `'last_admin'` when the write would drop the final admin,\n\t * `'not_found'` for an absent row. Callers must not pre-check the count\n\t * themselves: a decision made before this call is exactly the race.\n\t */\n\tupdatePermissionsGuarded(\n\t\tuserId: string,\n\t\tpermissions: PlatformPermission[]\n\t): Promise<'ok' | 'last_admin' | 'not_found'>;\n\t/** Grants only if no user holds `instance_admin` yet. True if this call claimed it. */\n\tclaimFirstInstanceAdminGuarded(\n\t\tuserId: string,\n\t\tpermissions: PlatformPermission[]\n\t): Promise<boolean>;\n\tupdateDisplayName(userId: string, displayName: string | undefined): Promise<void>;\n\tstarDefinition(userId: string, definitionId: string): Promise<void>;\n\tunstarDefinition(userId: string, definitionId: string): Promise<void>;\n\trecordRun(userId: string, run: RecentRun): Promise<void>;\n\tdeleteUser(userId: string): Promise<void>;\n}\n\nexport function createLocalUserDataStore(filePath: string): LocalUserDataStore {\n\t// Load-once, write-through cache, same pattern as `LocalOrgStoreLoader`.\n\t// The provider is the sole writer in single-process local mode, so the\n\t// in-memory copy is authoritative — but only if every consumer shares one\n\t// instance. LocalDataProvider injects a single instance across the\n\t// profile, permission, and data-provider views; don't call this factory\n\t// more than once per process.\n\tconst store = new CachedJsonFile<UserDataFile>(filePath, empty);\n\tconst load = () => store.get();\n\tconst persist = (file: UserDataFile) => store.write(file);\n\n\t// Serializes permission writes that must not interleave. Single-process\n\t// only, like the cache above — it makes the local provider's own\n\t// concurrency safe, not a multi-process deployment's. That is the same\n\t// dev-scale boundary the load-once cache already draws.\n\tlet permissionLock: Promise<unknown> = Promise.resolve();\n\n\tfunction withPermissionLock<T>(fn: () => Promise<T>): Promise<T> {\n\t\t// Chain onto the tail regardless of how the previous holder settled, so\n\t\t// one rejection cannot wedge the queue for the process's lifetime.\n\t\tconst next = permissionLock.then(fn, fn);\n\t\tpermissionLock = next.catch(() => {});\n\t\treturn next;\n\t}\n\n\tasync function findOrThrow(userId: string): Promise<{ file: UserDataFile; row: StoredUserData }> {\n\t\tconst file = await load();\n\t\tconst row = file.users.find((u) => u.userId === userId);\n\t\tif (!row) throw new ProviderError(`User-data row \"${userId}\" not found`, 404);\n\t\treturn { file, row };\n\t}\n\n\treturn {\n\t\tasync ensure(userId) {\n\t\t\tconst file = await load();\n\t\t\tif (file.users.some((u) => u.userId === userId)) return;\n\t\t\tfile.users.push(emptyRow(userId));\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync findById(userId) {\n\t\t\tconst { users } = await load();\n\t\t\treturn users.find((u) => u.userId === userId) ?? null;\n\t\t},\n\n\t\tasync listAll() {\n\t\t\tconst { users } = await load();\n\t\t\treturn users;\n\t\t},\n\n\t\tasync updatePermissions(userId, permissions) {\n\t\t\tconst { file, row } = await findOrThrow(userId);\n\t\t\trow.platformPermissions = permissions;\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync updatePermissionsGuarded(userId, permissions) {\n\t\t\t// Serialized against every other guarded write: `load()` may yield,\n\t\t\t// and the admin count read before that yield is stale by the time\n\t\t\t// the write lands. Queueing keeps count-and-write indivisible.\n\t\t\treturn withPermissionLock(async () => {\n\t\t\t\tconst file = await load();\n\t\t\t\tconst row = file.users.find((u) => u.userId === userId);\n\t\t\t\tif (!row) return 'not_found';\n\n\t\t\t\tconst wasAdmin = row.platformPermissions.includes('instance_admin');\n\t\t\t\tconst willBeAdmin = permissions.includes('instance_admin');\n\t\t\t\tif (wasAdmin && !willBeAdmin) {\n\t\t\t\t\tconst others = file.users.filter(\n\t\t\t\t\t\t(u) => u.userId !== userId && u.platformPermissions.includes('instance_admin')\n\t\t\t\t\t).length;\n\t\t\t\t\tif (others === 0) return 'last_admin';\n\t\t\t\t}\n\n\t\t\t\trow.platformPermissions = permissions;\n\t\t\t\tawait persist(file);\n\t\t\t\treturn 'ok';\n\t\t\t});\n\t\t},\n\n\t\tasync claimFirstInstanceAdminGuarded(userId, permissions) {\n\t\t\t// Shares the lock with `updatePermissionsGuarded` deliberately: the\n\t\t\t// two decide the same question from opposite ends (\"is there still an\n\t\t\t// admin\" / \"is there one yet\"), so they must not interleave with each\n\t\t\t// other any more than with themselves.\n\t\t\treturn withPermissionLock(async () => {\n\t\t\t\tconst file = await load();\n\t\t\t\tif (file.users.some((u) => u.platformPermissions.includes('instance_admin'))) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tconst row = file.users.find((u) => u.userId === userId);\n\t\t\t\tif (!row) return false;\n\n\t\t\t\trow.platformPermissions = permissions;\n\t\t\t\tawait persist(file);\n\t\t\t\treturn true;\n\t\t\t});\n\t\t},\n\n\t\tasync updateDisplayName(userId, displayName) {\n\t\t\tconst { file, row } = await findOrThrow(userId);\n\t\t\tif (displayName === undefined) {\n\t\t\t\tdelete row.displayName;\n\t\t\t} else {\n\t\t\t\trow.displayName = displayName;\n\t\t\t}\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync starDefinition(userId, definitionId) {\n\t\t\tconst { file, row } = await findOrThrow(userId);\n\t\t\tif (!row.starredDefinitions.includes(definitionId)) {\n\t\t\t\trow.starredDefinitions.push(definitionId);\n\t\t\t\tawait persist(file);\n\t\t\t}\n\t\t},\n\n\t\tasync unstarDefinition(userId, definitionId) {\n\t\t\tconst { file, row } = await findOrThrow(userId);\n\t\t\trow.starredDefinitions = row.starredDefinitions.filter((d) => d !== definitionId);\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync recordRun(userId, run) {\n\t\t\tconst { file, row } = await findOrThrow(userId);\n\t\t\t// Remove older entry for same definition, then prepend newest.\n\t\t\trow.recentRuns = [\n\t\t\t\trun,\n\t\t\t\t...row.recentRuns.filter((r) => r.definitionId !== run.definitionId)\n\t\t\t].slice(0, MAX_RECENT_RUNS);\n\t\t\tawait persist(file);\n\t\t},\n\n\t\tasync deleteUser(userId) {\n\t\t\tconst file = await load();\n\t\t\tconst before = file.users.length;\n\t\t\tfile.users = file.users.filter((u) => u.userId !== userId);\n\t\t\tif (file.users.length === before) {\n\t\t\t\tthrow new ProviderError(`User-data row \"${userId}\" not found`, 404);\n\t\t\t}\n\t\t\tawait persist(file);\n\t\t}\n\t};\n}\n","import * as path from 'node:path';\nimport type {\n\tIUserProfileStore,\n\tRecentRun,\n\tRequestContext,\n\tUserManagementResult,\n\tUserProfile\n} from '@selvajs/platform';\nimport { ProviderError } from '@selvajs/platform';\nimport { assertCanAccessProfile } from '@selvajs/platform/userProfile';\nimport {\n\tcreateLocalUserDataStore,\n\ttype LocalUserDataStore,\n\ttype StoredUserData\n} from '../data/userData.js';\n\nfunction toProfile(u: StoredUserData): UserProfile {\n\treturn {\n\t\tuserId: u.userId,\n\t\tdisplayName: u.displayName,\n\t\tstarredDefinitions: u.starredDefinitions ?? [],\n\t\trecentRuns: u.recentRuns ?? []\n\t};\n}\n\n/**\n * Filesystem-backed user-profile store. Reads and writes `user-data.json`,\n * shared with `LocalPlatformPermissionStore`. Keys exclusively by user ID;\n * identity (email, password hash) lives separately on the auth provider.\n * `IDataProvider.ensureUser` (called from `hooks.server.ts`) seeds an empty\n * row for every authed user.\n */\nexport class LocalUserProfileProvider implements IUserProfileStore {\n\tprivate readonly data: LocalUserDataStore;\n\n\t/**\n\t * Accepts a file path (constructs its own store — for `fromEnv` and\n\t * standalone conformance tests) or a shared `LocalUserDataStore`.\n\t * `LocalDataProvider` injects one store shared with the permission store\n\t * and the data provider so all three see the same load-once write-through\n\t * cache over `user-data.json` (§3a) — separate stores on the same file\n\t * would diverge.\n\t */\n\tconstructor(userData: string | LocalUserDataStore) {\n\t\tthis.data = typeof userData === 'string' ? createLocalUserDataStore(userData) : userData;\n\t}\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalUserProfileProvider {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalUserProfileProvider(path.join(env.DATA_PATH, 'user-data.json'));\n\t}\n\n\tasync getProfile(ctx: RequestContext, userId: string): Promise<UserProfile | null> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\tconst u = await this.data.findById(userId);\n\t\treturn u ? toProfile(u) : null;\n\t}\n\n\tasync getProfiles(_ctx: RequestContext, userIds: readonly string[]): Promise<UserProfile[]> {\n\t\t// Unscoped by design: used for display-name lookups across the UI.\n\t\t// Adapters needing per-caller restriction should override.\n\t\tconst all = await this.data.listAll();\n\t\tconst wanted = new Set(userIds);\n\t\treturn all.filter((u) => wanted.has(u.userId)).map(toProfile);\n\t}\n\n\tasync updateProfile(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tpatch: { displayName?: string }\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\ttry {\n\t\t\tif (patch.displayName !== undefined) {\n\t\t\t\tawait this.data.updateDisplayName(userId, patch.displayName);\n\t\t\t}\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync starDefinition(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tdefinitionId: string\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\ttry {\n\t\t\tawait this.data.starDefinition(userId, definitionId);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync unstarDefinition(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tdefinitionId: string\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\ttry {\n\t\t\tawait this.data.unstarDefinition(userId, definitionId);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync recordRun(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\trun: RecentRun\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\ttry {\n\t\t\tawait this.data.recordRun(userId, run);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\n/** Scoped to the user themselves; `instance_admin` and `system: true` callers bypass. */\n","import * as path from 'node:path';\nimport type {\n\tIPlatformPermissionStore,\n\tPlatformPermission,\n\tRequestContext,\n\tUserManagementResult\n} from '@selvajs/platform';\nimport { ProviderError } from '@selvajs/platform';\nimport {\n\tassertCanManagePermissions,\n\tassertCanReadPermissions,\n\tassertCanReadPermissionsBatch\n} from '@selvajs/platform/permissions';\nimport { createLocalUserDataStore, type LocalUserDataStore } from '../data/userData.js';\n\n/**\n * Filesystem-backed platform-permission store. Reads/writes the\n * `platformPermissions` field on `user-data.json`, owned by\n * `LocalDataProvider` and separate from `auth-users.json` (owned by\n * `LocalAuthProvider`) — the data layer only ever keys by user ID, never by\n * how identity is stored, so it pairs with any auth provider.\n *\n * Rows are seeded by `IDataProvider.ensureUser` (called per authed request\n * from `hooks.server.ts`); before that call `set` returns `not_found`.\n *\n * `set` enforces the §2 sole-`instance_admin` invariant (refuses to drop the\n * last admin) through `updatePermissionsGuarded`, which counts and writes\n * without yielding — a caller must never pre-check the count and then call\n * `set`, since the gap between the two is the race the guard exists to close.\n * That protects this process only; two processes sharing one `user-data.json`\n * is outside what the load-once cache supports either.\n *\n * It has no visibility into \"disabled\" state, which lives on\n * the auth provider's record — **every row here counts as enabled**. A\n * disabled admin would therefore still satisfy the \"another admin exists\"\n * check and let the last enabled one be demoted, so whoever disables a user\n * must revoke `instance_admin` through `set` first. That sequencing lives in\n * the disable route (`POST /api/admin/users/[id]/disable`), which holds both\n * this store and the auth provider; `LocalAuthProvider` deliberately has no\n * reference to the permission store.\n */\nexport class LocalPlatformPermissionStore implements IPlatformPermissionStore {\n\tprivate readonly data: LocalUserDataStore;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalPlatformPermissionStore {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalPlatformPermissionStore(path.join(env.DATA_PATH, 'user-data.json'));\n\t}\n\n\t/**\n\t * Accepts a file path (constructs its own store) or a shared\n\t * `LocalUserDataStore` — `LocalDataProvider` injects one shared store so\n\t * the permission, profile, and data-provider views of `user-data.json`\n\t * share a single load-once write-through cache (§3a).\n\t */\n\tconstructor(userData: string | LocalUserDataStore) {\n\t\tthis.data = typeof userData === 'string' ? createLocalUserDataStore(userData) : userData;\n\t}\n\n\tasync getFor(ctx: RequestContext, userId: string): Promise<PlatformPermission[]> {\n\t\tassertCanReadPermissions(ctx, userId);\n\t\tconst row = await this.data.findById(userId);\n\t\treturn row?.platformPermissions ?? [];\n\t}\n\n\tasync getForBatch(\n\t\tctx: RequestContext,\n\t\tuserIds: readonly string[]\n\t): Promise<Map<string, PlatformPermission[]>> {\n\t\tassertCanReadPermissionsBatch(ctx);\n\t\tconst all = await this.data.listAll();\n\t\tconst wanted = new Set(userIds);\n\t\tconst out = new Map<string, PlatformPermission[]>();\n\t\tfor (const u of all) {\n\t\t\tif (wanted.has(u.userId)) out.set(u.userId, u.platformPermissions ?? []);\n\t\t}\n\t\treturn out;\n\t}\n\n\tasync set(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tpermissions: readonly PlatformPermission[]\n\t): Promise<UserManagementResult> {\n\t\tassertCanManagePermissions(ctx);\n\t\t// The count and the write have to be indivisible — checking here and\n\t\t// writing after would let two concurrent demotions each see the other\n\t\t// as the surviving admin. `updatePermissionsGuarded` owns both.\n\t\ttry {\n\t\t\treturn await this.data.updatePermissionsGuarded(userId, [...permissions]);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync claimFirstInstanceAdmin(\n\t\t_ctx: RequestContext,\n\t\tuserId: string,\n\t\tpermissions: readonly PlatformPermission[]\n\t): Promise<boolean> {\n\t\t// No `assertCanManagePermissions`: by definition nobody holds `instance_admin` when this\n\t\t// succeeds. The guard is the store's own no-admin-yet condition, which is\n\t\t// why the check cannot be hoisted into the caller.\n\t\treturn this.data.claimFirstInstanceAdminGuarded(userId, [...permissions]);\n\t}\n\n\tasync hasInstanceAdmin(_ctx: RequestContext): Promise<boolean> {\n\t\t// Read-only existence probe, always allowed — used for first-run checks.\n\t\tconst all = await this.data.listAll();\n\t\treturn all.some((u) => u.platformPermissions.includes('instance_admin'));\n\t}\n\n\tasync countInstanceAdminsExcluding(_ctx: RequestContext, excludeUserId: string): Promise<number> {\n\t\treturn this.countOtherAdmins(excludeUserId);\n\t}\n\n\tprivate async countOtherAdmins(excludeUserId: string): Promise<number> {\n\t\tconst all = await this.data.listAll();\n\t\treturn all.filter(\n\t\t\t(u) => u.userId !== excludeUserId && u.platformPermissions.includes('instance_admin')\n\t\t).length;\n\t}\n}\n","import type {\n\tIDataProvider,\n\tIOrgStore,\n\tIProjectStore,\n\tIDefinitionStore,\n\tIComputeServerStore,\n\tIInviteStore,\n\tIApiTokenStore,\n\tIShareLinkStore,\n\tIUserProfileStore,\n\tIPlatformPermissionStore,\n\tIPlatformProjectGrantStore,\n\tIEventSink,\n\tRequestContext,\n\tUserErasureOptions\n} from '@selvajs/platform';\nimport { NoopEventSink } from '@selvajs/platform';\nimport * as path from 'node:path';\nimport { LocalOrgStore, LocalOrgStoreLoader } from './LocalOrgStore.js';\nimport { LocalProjectStore } from './LocalProjectStore.js';\nimport { LocalDefinitionStore } from './LocalDefinitionStore.js';\nimport { LocalComputeServerStore } from './LocalComputeServerStore.js';\nimport { LocalInviteStore } from './LocalInviteStore.js';\nimport { LocalApiTokenStore } from './LocalApiTokenStore.js';\nimport { LocalShareLinkStore } from './LocalShareLinkStore.js';\nimport { LocalPlatformProjectGrantStore } from './LocalPlatformProjectGrantStore.js';\nimport { LocalUserProfileProvider } from '../userProfile/LocalUserProfileProvider.js';\nimport { LocalPlatformPermissionStore } from '../permissions/LocalPlatformPermissionStore.js';\nimport { createLocalUserDataStore, type LocalUserDataStore } from './userData.js';\n\n/** The concrete stores, for the erasure steps the platform interfaces don't have. */\ninterface ErasableStores {\n\torgs: LocalOrgStore;\n\tdefinitions: LocalDefinitionStore;\n\tinvites: LocalInviteStore;\n\tshareLinks: LocalShareLinkStore;\n\tplatformProjectGrants: LocalPlatformProjectGrantStore;\n}\n\n/**\n * Composition root for every local-provider data store. One\n * `LocalOrgStoreLoader` is shared across org + project stores so they see the\n * same cache and atomic write path; one `LocalUserDataStore` is shared across\n * the permissions, profile, and `ensureUser`/`onUserDeleted` paths so they\n * all read and write the same `user-data.json` row (the local equivalent of\n * Supabase's `handle_new_auth_user` trigger).\n */\nexport class LocalDataProvider implements IDataProvider {\n\treadonly orgs: IOrgStore;\n\treadonly projects: IProjectStore;\n\treadonly definitions: IDefinitionStore;\n\treadonly computeServer: IComputeServerStore;\n\treadonly invites: IInviteStore;\n\treadonly apiTokens: IApiTokenStore;\n\treadonly shareLinks: IShareLinkStore;\n\treadonly userProfile: IUserProfileStore;\n\treadonly permissions: IPlatformPermissionStore;\n\treadonly platformProjectGrants: IPlatformProjectGrantStore;\n\treadonly events?: IEventSink;\n\n\tprivate readonly userData: LocalUserDataStore;\n\tprivate readonly erasable: ErasableStores;\n\n\tprivate constructor(\n\t\tstores: Omit<\n\t\t\tIDataProvider,\n\t\t\t| 'ensureUser'\n\t\t\t| 'onUserDeleted'\n\t\t\t| 'apiTokens'\n\t\t\t| 'orgs'\n\t\t\t| 'definitions'\n\t\t\t| 'invites'\n\t\t\t| 'shareLinks'\n\t\t\t| 'platformProjectGrants'\n\t\t> &\n\t\t\tErasableStores & { apiTokens: IApiTokenStore },\n\t\tuserData: LocalUserDataStore\n\t) {\n\t\tthis.erasable = stores;\n\t\tthis.events = stores.events;\n\t\tthis.orgs = stores.orgs;\n\t\tthis.projects = stores.projects;\n\t\tthis.definitions = stores.definitions;\n\t\tthis.computeServer = stores.computeServer;\n\t\tthis.invites = stores.invites;\n\t\tthis.apiTokens = stores.apiTokens;\n\t\tthis.shareLinks = stores.shareLinks;\n\t\tthis.userProfile = stores.userProfile;\n\t\tthis.permissions = stores.permissions;\n\t\tthis.platformProjectGrants = stores.platformProjectGrants;\n\t\tthis.userData = userData;\n\t}\n\n\t/**\n\t * Idempotently seeds a user's `user-data.json` row. Called on every authed\n\t * request from `hooks.server.ts` — the local equivalent of Supabase's\n\t * `handle_new_auth_user` trigger. `ctx` is unused; registration runs as a\n\t * system operation regardless of the calling user, kept for interface\n\t * symmetry with adapters that need it.\n\t */\n\tasync ensureUser(_ctx: RequestContext, userId: string): Promise<void> {\n\t\tawait this.userData.ensure(userId);\n\t}\n\n\t/**\n\t * Cascade hook run after the auth provider deletes a user: removes the\n\t * `user-data.json` row, every membership and everything else that names them\n\t * (Supabase gets most of this from FK constraints). Rows they made stay, under\n\t * `ERASED_ACTOR_ID`. Tolerates missing rows.\n\t */\n\tasync onUserDeleted(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\topts?: UserErasureOptions\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait this.userData.deleteUser(userId);\n\t\t} catch {\n\t\t\t// Already absent — nothing to clean up.\n\t\t}\n\t\tawait this.apiTokens.eraseUser(ctx, userId);\n\t\tawait this.erasable.orgs.eraseUser(userId);\n\t\tawait this.erasable.definitions.eraseUser(userId);\n\t\tawait this.erasable.invites.eraseUser(userId, opts?.email);\n\t\tawait this.erasable.shareLinks.eraseUser(userId);\n\t\tawait this.erasable.platformProjectGrants.eraseUser(userId);\n\t}\n\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tevents: IEventSink = new NoopEventSink()\n\t): LocalDataProvider {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\tconst dataPath = env.DATA_PATH;\n\t\tconst userDataFilePath = path.join(dataPath, 'user-data.json');\n\n\t\tconst loader = new LocalOrgStoreLoader(dataPath);\n\t\tconst platformProjectGrants = LocalPlatformProjectGrantStore.fromEnv(env);\n\t\tconst invites = LocalInviteStore.fromEnv(env, events);\n\t\tconst apiTokens = LocalApiTokenStore.fromEnv(env, events);\n\t\tconst computeServer = LocalComputeServerStore.fromEnv(env);\n\t\tconst projects = new LocalProjectStore({ loader, grants: platformProjectGrants, events });\n\t\tconst definitions = new LocalDefinitionStore(dataPath, undefined, events);\n\t\tconst shareLinks = new LocalShareLinkStore({\n\t\t\tfilePath: path.join(dataPath, 'share-links.json'),\n\t\t\tevents\n\t\t});\n\t\tconst orgs = new LocalOrgStore({\n\t\t\tloader,\n\t\t\tinvites,\n\t\t\tapiTokens,\n\t\t\tcomputeServer,\n\t\t\tgrants: platformProjectGrants,\n\t\t\tevents\n\t\t});\n\n\t\t// Wire cross-store deps that aren't constructor-injected:\n\t\t// - definitions needs the project store for listPublic's visibility check\n\t\t// - shareLinks needs the definition store to enforce the soft-delete\n\t\t// cascade on resolution, and both stores to walk link→definition→project\n\t\t// for the org roster (Supabase does both via JOIN)\n\t\t// - projects needs the definition store to cascade soft-delete to a\n\t\t// deleted project's definitions (Supabase does this inline)\n\t\tdefinitions.setProjectProvider(projects);\n\t\tshareLinks.setDefinitionProvider(definitions);\n\t\tshareLinks.setProjectProvider(projects);\n\t\tprojects.setDefinitionProvider(definitions);\n\t\torgs.setDefinitionProvider(definitions);\n\n\t\tconst userData = createLocalUserDataStore(userDataFilePath);\n\n\t\treturn new LocalDataProvider(\n\t\t\t{\n\t\t\t\torgs,\n\t\t\t\tprojects,\n\t\t\t\tdefinitions,\n\t\t\t\tcomputeServer,\n\t\t\t\tinvites,\n\t\t\t\tapiTokens,\n\t\t\t\tshareLinks,\n\t\t\t\tuserProfile: new LocalUserProfileProvider(userData),\n\t\t\t\tpermissions: new LocalPlatformPermissionStore(userData),\n\t\t\t\tplatformProjectGrants,\n\t\t\t\tevents\n\t\t\t},\n\t\t\tuserData\n\t\t);\n\t}\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport { ProviderError } from '@selvajs/platform';\nimport { transcodeImageIfNeeded } from '@selvajs/platform/storage';\nimport { renameReplacing } from '../data/fsJson.js';\nimport type { IStorageProvider } from '@selvajs/platform/storage';\n\n/**\n * Filesystem implementation of `IStorageProvider`. Files live under\n * `DATA_PATH/{path}`. `put()` transcodes images to WebP via the shared\n * `transcodeImageIfNeeded` helper — the same one the Supabase adapter uses,\n * so both providers produce identical bytes for the same upload.\n */\nexport class LocalStorageProvider implements IStorageProvider {\n\tprivate readonly basePath: string;\n\tprivate readonly publicUrlBase: string;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): LocalStorageProvider {\n\t\tif (!env.DATA_PATH) throw new Error('Missing required env var: DATA_PATH');\n\t\treturn new LocalStorageProvider(env.DATA_PATH, '/api/files');\n\t}\n\n\tconstructor(basePath: string, publicUrlBase = '/api/files') {\n\t\tthis.basePath = basePath;\n\t\tthis.publicUrlBase = publicUrlBase;\n\t}\n\n\t/**\n\t * Resolves a caller-provided path under basePath; rejects anything that\n\t * would escape the root. Last line of defense against traversal — this\n\t * adapter is reached by any `IStorageProvider` caller, not just ones that\n\t * already validated the key.\n\t */\n\tprivate resolvePath(storagePath: string): string {\n\t\tconst base = path.resolve(this.basePath);\n\t\tconst full = path.resolve(base, storagePath);\n\t\tif (full !== base && !full.startsWith(base + path.sep)) {\n\t\t\tthrow new ProviderError(`Path escapes base: ${storagePath}`, 400);\n\t\t}\n\t\t// The storage root is `DATA_PATH`, which also holds the stores' JSON files,\n\t\t// `auth-users.json` among them. No asset lives directly in the root.\n\t\tif (path.dirname(full) === base && full.endsWith('.json')) {\n\t\t\tthrow new ProviderError(`Path is a data file, not an asset: ${storagePath}`, 400);\n\t\t}\n\t\treturn full;\n\t}\n\n\tasync get(storagePath: string): Promise<Uint8Array | null> {\n\t\ttry {\n\t\t\tconst buffer = await fs.readFile(this.resolvePath(storagePath));\n\t\t\treturn new Uint8Array(buffer);\n\t\t} catch (err) {\n\t\t\tif ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync put(storagePath: string, data: Uint8Array, contentType?: string): Promise<string> {\n\t\t// Rewrites images to .webp; non-images pass through untouched.\n\t\tconst transcoded = await transcodeImageIfNeeded(data, contentType, storagePath);\n\t\tconst fullPath = this.resolvePath(transcoded.path);\n\t\tawait fs.mkdir(path.dirname(fullPath), { recursive: true });\n\t\t// Temp and rename: an in-place overwrite truncates first, so a concurrent `get`\n\t\t// would come back short.\n\t\tconst tmp = `${fullPath}.${randomUUID()}.tmp`;\n\t\ttry {\n\t\t\tawait fs.writeFile(tmp, Buffer.from(transcoded.data));\n\t\t\tawait renameReplacing(tmp, fullPath);\n\t\t} catch (err) {\n\t\t\tawait fs.rm(tmp, { force: true }).catch(() => {});\n\t\t\tthrow err;\n\t\t}\n\t\treturn transcoded.path;\n\t}\n\n\tasync delete(storagePath: string): Promise<void> {\n\t\ttry {\n\t\t\tawait fs.unlink(this.resolvePath(storagePath));\n\t\t} catch (err) {\n\t\t\tif ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n\t\t}\n\t}\n\n\tasync deletePrefix(prefix: string): Promise<void> {\n\t\tconst fullPath = this.resolvePath(prefix);\n\t\t// The root is `DATA_PATH`, so this would take every store with it.\n\t\tif (fullPath === path.resolve(this.basePath)) {\n\t\t\tthrow new ProviderError(`Refusing to delete the whole store: ${JSON.stringify(prefix)}`, 400);\n\t\t}\n\t\tawait fs.rm(fullPath, { recursive: true, force: true });\n\t}\n\n\tgetPublicUrl(storagePath: string): string {\n\t\t// No CDN locally — every asset goes through the `/api/files` proxy, which\n\t\t// classifies the path (`classifyAssetPath`) and applies auth per visibility.\n\t\treturn `${this.publicUrlBase}/${storagePath}`;\n\t}\n}\n","import type { SupabaseClient } from '@supabase/supabase-js';\nimport { createClient } from '@supabase/supabase-js';\nimport { transcodeImageIfNeeded, classifyAssetPath } from '@selvajs/platform/storage';\nimport type { IStorageProvider } from '@selvajs/platform/storage';\nimport { ProviderError, trimTrailing } from '@selvajs/platform';\n\n/**\n * Storage backend for Selva on Supabase Storage. Routes each path to one of\n * two buckets: `publicBucket` (CDN-readable, `getPublicUrl` returns the\n * direct CDN URL) or `privateBucket` (`getPublicUrl` returns\n * `${privateUrlPrefix}/{path}` — the consuming app must route that prefix\n * through an auth check and `get()`).\n */\nexport interface SupabaseStorageProviderConfig {\n\t/** Supabase project URL (e.g. http://127.0.0.1:54321 for local stack). */\n\tsupabaseUrl: string;\n\t/**\n\t * Service-role key. The provider runs server-side and must bypass RLS\n\t * for server-internal actions (admin uploads, janitor cleanup) — never\n\t * used from the browser.\n\t */\n\tserviceRoleKey: string;\n\t/** Bucket for CDN-readable objects. Default: \"selva-public\". */\n\tpublicBucket?: string;\n\t/** Bucket for authenticated-only objects. Default: \"selva-private\". */\n\tprivateBucket?: string;\n\t/** URL prefix for authenticated file downloads, used by `getPublicUrl`. Default: \"/api/files\". */\n\tprivateUrlPrefix?: string;\n}\n\nconst LIST_PAGE_SIZE = 1000;\n\n/**\n * Supabase Storage refuses to upload a `..` key but answers a read of one with\n * not-found. Refusing here gives every method the local store's 400.\n */\nfunction assertNoClimb(storagePath: string): void {\n\tif (storagePath.split('/').includes('..')) {\n\t\tthrow new ProviderError(`Path escapes the store: ${JSON.stringify(storagePath)}`, 400);\n\t}\n}\n\nexport class SupabaseStorageProvider implements IStorageProvider {\n\tprivate readonly client: SupabaseClient;\n\tprivate readonly publicBucket: string;\n\tprivate readonly privateBucket: string;\n\tprivate readonly publicBaseUrl: string;\n\tprivate readonly privateUrlPrefix: string;\n\n\tstatic fromEnv(env: Record<string, string | undefined>): SupabaseStorageProvider {\n\t\tconst supabaseUrl = env.SUPABASE_URL;\n\t\tconst serviceRoleKey = env.SUPABASE_SERVICE_ROLE_KEY;\n\t\tif (!supabaseUrl) throw new Error('Missing required env var: SUPABASE_URL');\n\t\tif (!serviceRoleKey) throw new Error('Missing required env var: SUPABASE_SERVICE_ROLE_KEY');\n\t\treturn new SupabaseStorageProvider({\n\t\t\tsupabaseUrl,\n\t\t\tserviceRoleKey,\n\t\t\tpublicBucket: env.SUPABASE_PUBLIC_BUCKET,\n\t\t\tprivateBucket: env.SUPABASE_PRIVATE_BUCKET\n\t\t});\n\t}\n\n\tconstructor(config: SupabaseStorageProviderConfig) {\n\t\tthis.client = createClient(config.supabaseUrl, config.serviceRoleKey, {\n\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t});\n\t\tthis.publicBucket = config.publicBucket ?? 'selva-public';\n\t\tthis.privateBucket = config.privateBucket ?? 'selva-private';\n\t\tthis.publicBaseUrl = `${config.supabaseUrl.replace(/\\/$/, '')}/storage/v1/object/public/${this.publicBucket}`;\n\t\tthis.privateUrlPrefix = (config.privateUrlPrefix ?? '/api/files').replace(/\\/$/, '');\n\t}\n\n\t/**\n\t * `.gh`/`.ghx` source files are always private, regardless of what\n\t * `classifyAssetPath` says — confidentiality by extension means a\n\t * path-scheme rename can't silently move sources into the public bucket.\n\t * Everything else routes by asset class, and only a `public` class reaches\n\t * the public bucket: an unclassified path stays private.\n\t */\n\tprivate bucketFor(storagePath: string): string {\n\t\tif (/\\.(gh|ghx)$/i.test(storagePath)) return this.privateBucket;\n\t\tconst cls = classifyAssetPath(storagePath);\n\t\treturn cls?.class.visibility === 'public' ? this.publicBucket : this.privateBucket;\n\t}\n\n\tasync get(storagePath: string): Promise<Uint8Array | null> {\n\t\tassertNoClimb(storagePath);\n\t\tconst bucket = this.bucketFor(storagePath);\n\t\tconst { data, error } = await this.client.storage.from(bucket).download(storagePath);\n\t\tif (error) {\n\t\t\t// storage-js has no stable status code for 404 — match the message instead.\n\t\t\tconst msg = (error as { message?: string }).message ?? '';\n\t\t\tif (/not found/i.test(msg) || /no such key/i.test(msg)) return null;\n\t\t\tthrow error;\n\t\t}\n\t\tconst buffer = await data.arrayBuffer();\n\t\treturn new Uint8Array(buffer);\n\t}\n\n\tasync put(storagePath: string, data: Uint8Array, contentType?: string): Promise<string> {\n\t\tassertNoClimb(storagePath);\n\t\tconst transcoded = await transcodeImageIfNeeded(data, contentType, storagePath);\n\t\tconst bucket = this.bucketFor(transcoded.path);\n\t\tconst { error } = await this.client.storage\n\t\t\t.from(bucket)\n\t\t\t.upload(transcoded.path, transcoded.data, {\n\t\t\t\tcontentType: transcoded.contentType,\n\t\t\t\t// `put` upserts, so a changed object needs a new URL: `withCacheBust` is\n\t\t\t\t// how callers get one. A year is safe only because of that.\n\t\t\t\tcacheControl: '31536000',\n\t\t\t\tupsert: true\n\t\t\t});\n\t\tif (error) throw error;\n\t\treturn transcoded.path;\n\t}\n\n\tasync delete(storagePath: string): Promise<void> {\n\t\tassertNoClimb(storagePath);\n\t\tconst bucket = this.bucketFor(storagePath);\n\t\tconst { error } = await this.client.storage.from(bucket).remove([storagePath]);\n\t\tif (error) throw error;\n\t}\n\n\tasync deletePrefix(prefix: string): Promise<void> {\n\t\tassertNoClimb(prefix);\n\t\tif (trimTrailing(prefix, '/') === '') {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Refusing to delete the whole store: prefix ${JSON.stringify(prefix)}`,\n\t\t\t\t400\n\t\t\t);\n\t\t}\n\t\t// A definition's GUID prefix may have files in either bucket.\n\t\tawait Promise.all([\n\t\t\tthis.deletePrefixInBucket(this.publicBucket, prefix),\n\t\t\tthis.deletePrefixInBucket(this.privateBucket, prefix)\n\t\t]);\n\t}\n\n\tprivate async deletePrefixInBucket(bucket: string, prefix: string): Promise<void> {\n\t\tconst normalized = trimTrailing(prefix, '/');\n\t\tconst keys = await this.listAllKeys(bucket, normalized);\n\t\tif (keys.length === 0) return;\n\t\t// remove() caps out at 1000 paths per call.\n\t\tfor (let i = 0; i < keys.length; i += 1000) {\n\t\t\tconst slice = keys.slice(i, i + 1000);\n\t\t\tconst { error } = await this.client.storage.from(bucket).remove(slice);\n\t\t\tif (error) throw error;\n\t\t}\n\t}\n\n\t/** storage-js's `list` only returns immediate children of a \"folder\", so DFS to get everything under `prefix`. */\n\tprivate async listAllKeys(bucket: string, prefix: string): Promise<string[]> {\n\t\tconst out: string[] = [];\n\t\tconst stack: string[] = [prefix];\n\t\twhile (stack.length > 0) {\n\t\t\tconst dir = stack.pop()!;\n\t\t\tfor (let offset = 0; ; offset += LIST_PAGE_SIZE) {\n\t\t\t\tconst { data, error } = await this.client.storage.from(bucket).list(dir, {\n\t\t\t\t\tlimit: LIST_PAGE_SIZE,\n\t\t\t\t\toffset,\n\t\t\t\t\tsortBy: { column: 'name', order: 'asc' }\n\t\t\t\t});\n\t\t\t\tif (error) throw error;\n\t\t\t\tconst entries = data ?? [];\n\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\tconst full = dir ? `${dir}/${entry.name}` : entry.name;\n\t\t\t\t\t// storage-js marks folder entries with id === null.\n\t\t\t\t\tif (entry.id === null) {\n\t\t\t\t\t\tstack.push(full);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout.push(full);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (entries.length < LIST_PAGE_SIZE) break;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\tgetPublicUrl(storagePath: string): string {\n\t\tif (this.bucketFor(storagePath) === this.publicBucket) {\n\t\t\treturn `${this.publicBaseUrl}/${storagePath}`;\n\t\t}\n\t\treturn `${this.privateUrlPrefix}/${storagePath}`;\n\t}\n}\n","import { ProviderError } from '@selvajs/platform';\n\n/**\n * PostgREST/Postgres error translation shared by every Supabase store.\n *\n * `PGRST116` (the code `.single()` raises when a selector matches zero rows)\n * maps to 404 — that's almost always what a store's caller wants. So does\n * `P0002`, which our RPCs raise for a missing row. `42501` (RLS or a privilege\n * refusing the caller) maps to 403. Unique and FK violations map to 409.\n * Anything else becomes a plain `Error` (500\n * downstream via `api-errors`), with `details`/`hint`/`code` preserved on the\n * error object for logs.\n */\ninterface PostgrestErrorShape {\n\tcode?: string;\n\tmessage?: string;\n\tdetails?: string;\n\thint?: string;\n}\n\nexport function mapPostgrestError(e: unknown): Error {\n\tconst pg = e as PostgrestErrorShape;\n\tswitch (pg?.code) {\n\t\tcase 'PGRST116':\n\t\tcase 'P0002':\n\t\t\treturn new ProviderError(pg.message ?? 'Not found', 404);\n\t\tcase '42501':\n\t\t\treturn new ProviderError(pg.message ?? 'Forbidden', 403);\n\t\tcase '23505':\n\t\t\treturn new ProviderError(pg.message ?? 'Duplicate record', 409);\n\t\tcase '23503':\n\t\t\treturn new ProviderError(pg.message ?? 'Foreign key violation', 409);\n\t}\n\tif (e instanceof Error) return e;\n\tif (e && typeof e === 'object') {\n\t\tconst obj = e as PostgrestErrorShape;\n\t\tconst msg = obj.message ?? obj.details ?? obj.hint ?? 'Unknown Postgres error';\n\t\tconst err = new Error(obj.code ? `[${obj.code}] ${msg}` : msg);\n\t\tObject.assign(err, obj);\n\t\treturn err;\n\t}\n\treturn new Error(String(e));\n}\n","import type {\n\tIPlatformProjectGrantStore,\n\tPlatformProjectGrant,\n\tRequestContext\n} from '@selvajs/platform';\nimport { ERASED_ACTOR_ID, ProviderError } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\n\nconst GRANT_COLUMNS = 'id, project_id, grantee_type, grantee_id, can_solve, created_by, created_at';\n\n/** Reads go through the caller's client, so RLS shows a grantee only its own grants. */\nexport class SupabasePlatformProjectGrantStore implements IPlatformProjectGrantStore {\n\tconstructor(private readonly clients: ClientBundle) {}\n\n\tasync listByProject(ctx: RequestContext, projectId: string): Promise<PlatformProjectGrant[]> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('platform_project_grants')\n\t\t\t.select(GRANT_COLUMNS)\n\t\t\t.eq('project_id', projectId)\n\t\t\t.order('created_at', { ascending: true });\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn (data ?? []).map(rowToGrant);\n\t}\n\n\tasync listByProjects(\n\t\tctx: RequestContext,\n\t\tprojectIds: readonly string[]\n\t): Promise<Map<string, PlatformProjectGrant[]>> {\n\t\tconst result = new Map(projectIds.map((id) => [id, [] as PlatformProjectGrant[]]));\n\t\tif (projectIds.length === 0) return result;\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('platform_project_grants')\n\t\t\t.select(GRANT_COLUMNS)\n\t\t\t.in('project_id', [...projectIds])\n\t\t\t.order('created_at', { ascending: true });\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of data ?? []) {\n\t\t\tconst grant = rowToGrant(row);\n\t\t\tresult.get(grant.projectId)?.push(grant);\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync create(_ctx: RequestContext, grant: PlatformProjectGrant): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('platform_project_grants')\n\t\t\t.insert(grantToRow(grant));\n\t\tif (error?.code === '23505' && error.message.includes('platform_project_grants_grantee_key')) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`A grant for this ${grant.granteeType} already exists on this project`,\n\t\t\t\t409\n\t\t\t);\n\t\t}\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync delete(_ctx: RequestContext, id: string): Promise<void> {\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('platform_project_grants')\n\t\t\t.delete()\n\t\t\t.eq('id', id)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) throw new ProviderError(`Grant '${id}' not found`, 404);\n\t}\n\n\tasync deleteByProject(_ctx: RequestContext, projectId: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('platform_project_grants')\n\t\t\t.delete()\n\t\t\t.eq('project_id', projectId);\n\t\tif (error && !isMissingTable(error)) throw mapPostgrestError(error);\n\t}\n\n\tasync deleteByGranteeOrg(_ctx: RequestContext, orgId: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('platform_project_grants')\n\t\t\t.delete()\n\t\t\t.eq('grantee_type', 'org')\n\t\t\t.eq('grantee_id', orgId);\n\t\tif (error && !isMissingTable(error)) throw mapPostgrestError(error);\n\t}\n\n\t/** A user grant is the user's own, so it goes with them; one they created stays. */\n\tasync eraseUser(userId: string): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst deleted = await client\n\t\t\t.from('platform_project_grants')\n\t\t\t.delete()\n\t\t\t.eq('grantee_type', 'user')\n\t\t\t.eq('grantee_id', userId);\n\t\tif (deleted.error) {\n\t\t\tif (isMissingTable(deleted.error)) return;\n\t\t\tthrow mapPostgrestError(deleted.error);\n\t\t}\n\t\tconst anonymized = await client\n\t\t\t.from('platform_project_grants')\n\t\t\t.update({ created_by: null })\n\t\t\t.eq('created_by', userId);\n\t\tif (anonymized.error) throw mapPostgrestError(anonymized.error);\n\t}\n}\n\n/**\n * Deleting an org, a project or a user runs these cleanups on every deployment, also one whose\n * database is still behind `20261117200000`, which the migration handshake lets boot. Without the\n * table there is nothing to clean up.\n */\nfunction isMissingTable(error: { code?: string }): boolean {\n\treturn error.code === 'PGRST205' || error.code === '42P01';\n}\n\ninterface GrantRow {\n\tid: string;\n\tproject_id: string;\n\tgrantee_type: PlatformProjectGrant['granteeType'];\n\tgrantee_id: string;\n\tcan_solve: boolean;\n\tcreated_by: string | null;\n\tcreated_at: string;\n}\n\nfunction rowToGrant(row: GrantRow): PlatformProjectGrant {\n\treturn {\n\t\tid: row.id,\n\t\tprojectId: row.project_id,\n\t\tgranteeType: row.grantee_type,\n\t\tgranteeId: row.grantee_id,\n\t\tcanSolve: row.can_solve,\n\t\tcreatedBy: row.created_by ?? ERASED_ACTOR_ID,\n\t\tcreatedAt: row.created_at\n\t};\n}\n\nfunction grantToRow(g: PlatformProjectGrant): GrantRow {\n\treturn {\n\t\tid: g.id,\n\t\tproject_id: g.projectId,\n\t\tgrantee_type: g.granteeType,\n\t\tgrantee_id: g.granteeId,\n\t\tcan_solve: g.canSolve,\n\t\tcreated_by: g.createdBy === ERASED_ACTOR_ID ? null : g.createdBy,\n\t\tcreated_at: g.createdAt\n\t};\n}\n","/**\n * `ListOptions.cursor` is meant to be opaque; here it's just an offset\n * encoded as a string. Simple and correct for stable sorts, fine at Selva's\n * scale (bounded admin/definition lists, not infinite scroll over millions\n * of rows). Keyset pagination would be faster if that ever changes.\n */\n\nimport { clampPageLimit, decodeOffsetCursor, encodeOffsetCursor } from '@selvajs/platform';\nimport type { ListOptions } from '@selvajs/platform';\n\nexport interface RangeSpec {\n\tfrom: number;\n\tto: number;\n\tlimit: number;\n}\n\nexport { decodeOffsetCursor as decodeCursor, encodeOffsetCursor as encodeCursor };\n\nexport function toRange(opts: Pick<ListOptions, 'limit' | 'cursor'> | undefined): RangeSpec {\n\tconst limit = clampPageLimit(opts?.limit);\n\tconst from = decodeOffsetCursor(opts?.cursor);\n\treturn { from, to: from + limit - 1, limit };\n}\n\nexport function nextCursorFromRange(\n\trange: RangeSpec,\n\treturnedCount: number,\n\ttotalCount: number | null | undefined\n): string | undefined {\n\tconst consumed = range.from + returnedCount;\n\tif (totalCount != null) {\n\t\treturn consumed < totalCount ? encodeOffsetCursor(consumed) : undefined;\n\t}\n\t// Without total, we can only infer \"there might be more\" if we got a full page.\n\treturn returnedCount >= range.limit ? encodeOffsetCursor(consumed) : undefined;\n}\n\nexport function orderColumn(orderBy: ListOptions['orderBy'] | undefined): string {\n\tswitch (orderBy) {\n\t\tcase 'name':\n\t\t\treturn 'name';\n\t\tcase 'updatedAt':\n\t\t\treturn 'updated_at';\n\t\tcase 'createdAt':\n\t\tdefault:\n\t\t\treturn 'created_at';\n\t}\n}\n","import type { RequestContext } from '@selvajs/platform';\nimport { auditSoftDelete } from '@selvajs/platform';\n\n/**\n * Translates platform's camelCase audit fields (`updatedAt`/`updatedBy`) to\n * the snake_case columns every Supabase row uses.\n *\n * `updated_by` is written only when `ctx.userId` is set. On system contexts\n * `auditUpdate`/`auditSoftDelete` fall back to `''`, and the column FKs\n * `auth.users(id)` — writing `''` violates the FK — so it's omitted instead,\n * leaving the existing value untouched.\n *\n * Plain updates don't stamp `updated_at`: a per-table trigger already sets\n * it. Only soft-delete sets `updated_at` explicitly, to match `deleted_at`.\n */\n\nexport function stampUpdate(ctx: RequestContext): { updated_by?: string } {\n\treturn ctx.userId ? { updated_by: ctx.userId } : {};\n}\n\nexport function stampSoftDelete(\n\tctx: RequestContext,\n\tfallbackActor: string | null | undefined = ctx.userId\n): { deleted_at: string; updated_at: string; updated_by?: string } {\n\tconst stamp = auditSoftDelete(ctx, fallbackActor);\n\tconst row: { deleted_at: string; updated_at: string; updated_by?: string } = {\n\t\tdeleted_at: stamp.deletedAt,\n\t\tupdated_at: stamp.updatedAt\n\t};\n\tif (stamp.updatedBy) row.updated_by = stamp.updatedBy;\n\treturn row;\n}\n","import type {\n\tIOrgStore,\n\tIEventSink,\n\tOrganization,\n\tOrgMember,\n\tOrgRole,\n\tOrgPermission,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport {\n\tDEFAULT_ORG_PERMISSIONS,\n\tERASED_ACTOR_ID,\n\tProviderError,\n\tactorOf,\n\tNoopEventSink\n} from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { SupabasePlatformProjectGrantStore } from './SupabasePlatformProjectGrantStore.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, orderColumn, toRange } from './pagination.js';\nimport { stampSoftDelete, stampUpdate } from './rowStamp.js';\n\n/** Explicit column list for `orgs` — every field `rowToOrg` consumes. */\nconst ORG_COLUMNS =\n\t'id, name, slug, owner_id, assets, created_by, updated_by, created_at, updated_at, deleted_at';\n/** Explicit column list for `org_members` — every field `rowToOrgMember` consumes. */\nconst ORG_MEMBER_COLUMNS =\n\t'org_id, user_id, role, permissions, joined_at, updated_at, updated_by, deleted_at';\n\n/**\n * Org + org-membership store backed by Postgres. Reads run as the caller, so\n * RLS decides what they see. Writes run as the service role: the app has\n * already decided, and sessions hold no write privilege.\n */\nexport class SupabaseOrgStore implements IOrgStore {\n\tprivate readonly events: IEventSink;\n\n\t/** Grants have no soft-delete: deleting an org removes the grants it holds and those on its projects. */\n\tprivate readonly grants: SupabasePlatformProjectGrantStore;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tevents: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.events = events;\n\t\tthis.grants = new SupabasePlatformProjectGrantStore(clients);\n\t}\n\n\tasync listOrgs(ctx: RequestContext, opts?: ListOptions): Promise<Page<Organization>> {\n\t\tconst range = toRange(opts);\n\t\tconst direction = opts?.orderDir ?? 'desc';\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('orgs')\n\t\t\t.select(ORG_COLUMNS, { count: 'exact' })\n\t\t\t.is('deleted_at', null)\n\t\t\t.order(orderColumn(opts?.orderBy), { ascending: direction === 'asc' })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToOrg);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync getOrg(ctx: RequestContext, id: string): Promise<Organization | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('orgs')\n\t\t\t.select(ORG_COLUMNS)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToOrg(data) : null;\n\t}\n\n\tasync getOrgBySlug(ctx: RequestContext, slug: string): Promise<Organization | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('orgs')\n\t\t\t.select(ORG_COLUMNS)\n\t\t\t.eq('slug', slug)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToOrg(data) : null;\n\t}\n\n\tasync createOrg(ctx: RequestContext, org: Organization): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst { error } = await client.from('orgs').insert(orgToRow(org));\n\t\tif (error) throw mapPostgrestError(error);\n\n\t\t// Seed owner membership: RLS hides an org from anyone who is not a member,\n\t\t// its creator included. Upsert so a\n\t\t// stale soft-deleted row from a prior org with the same id is reactivated\n\t\t// rather than blocking creation.\n\t\tconst { error: memberError } = await client.from('org_members').upsert(\n\t\t\t{\n\t\t\t\torg_id: org.id,\n\t\t\t\tuser_id: org.ownerId,\n\t\t\t\trole: 'owner',\n\t\t\t\tpermissions: [...DEFAULT_ORG_PERMISSIONS.owner],\n\t\t\t\tjoined_at: new Date().toISOString(),\n\t\t\t\tdeleted_at: null\n\t\t\t},\n\t\t\t{ onConflict: 'org_id,user_id' }\n\t\t);\n\t\tif (memberError) throw mapPostgrestError(memberError);\n\t\tawait this.events.emit({ type: 'org.created', orgId: org.id, ...actorOf(ctx) });\n\t}\n\n\tasync updateOrg(\n\t\tctx: RequestContext,\n\t\tid: string,\n\t\tpatch: Partial<Pick<Organization, 'name' | 'slug' | 'assets'>>\n\t): Promise<void> {\n\t\tconst row: Record<string, unknown> = {};\n\t\tif (patch.name !== undefined) row.name = patch.name;\n\t\tif (patch.slug !== undefined) row.slug = patch.slug;\n\t\t// Callers pass the full merged map — store it as-is (JSONB column, no partial merge).\n\t\tif (patch.assets !== undefined) row.assets = patch.assets;\n\t\tif (Object.keys(row).length === 0) return;\n\t\t// `updated_at` is set by the trg_orgs_updated_at trigger; `stampUpdate`\n\t\t// only adds `updated_by`, and only when ctx.userId is set (empty on\n\t\t// system contexts would violate the `on delete set null` FK).\n\t\tObject.assign(row, stampUpdate(ctx));\n\n\t\tconst { error, data } = await this.clients.serviceClient\n\t\t\t.from('orgs')\n\t\t\t.update(row)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) throw new ProviderError(`Org '${id}' not found`, 404);\n\t}\n\n\tasync deleteOrg(ctx: RequestContext, id: string): Promise<void> {\n\t\t// Soft-delete with cascade, mirroring LocalOrgStore: org → org_members,\n\t\t// projects → project_members, definitions. Hard delete is reserved for\n\t\t// the background janitor; user-facing deletes preserve the audit trail.\n\t\tconst client = this.clients.serviceClient;\n\t\tconst stampRow = stampSoftDelete(ctx);\n\n\t\tconst { error: orgErr, data: orgData } = await client\n\t\t\t.from('orgs')\n\t\t\t.update(stampRow)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('id');\n\t\tif (orgErr) throw mapPostgrestError(orgErr);\n\t\tif (!orgData || orgData.length === 0) throw new ProviderError(`Org '${id}' not found`, 404);\n\n\t\tconst { error: omErr } = await client\n\t\t\t.from('org_members')\n\t\t\t.update(stampRow)\n\t\t\t.eq('org_id', id)\n\t\t\t.is('deleted_at', null);\n\t\tif (omErr) throw mapPostgrestError(omErr);\n\n\t\t// Fetch project IDs first so app code can cascade to project_members and\n\t\t// definitions — Postgres FK CASCADE only fires on hard DELETE, and this is a soft one.\n\t\tconst { data: orgProjects, error: projFetchErr } = await client\n\t\t\t.from('projects')\n\t\t\t.select('id')\n\t\t\t.eq('org_id', id)\n\t\t\t.is('deleted_at', null);\n\t\tif (projFetchErr) throw mapPostgrestError(projFetchErr);\n\t\tconst projectIds = (orgProjects ?? []).map((p) => p.id as string);\n\n\t\tconst { error: projErr } = await client\n\t\t\t.from('projects')\n\t\t\t.update(stampRow)\n\t\t\t.eq('org_id', id)\n\t\t\t.is('deleted_at', null);\n\t\tif (projErr) throw mapPostgrestError(projErr);\n\n\t\tif (projectIds.length > 0) {\n\t\t\tconst { error: pmErr } = await client\n\t\t\t\t.from('project_members')\n\t\t\t\t.update(stampRow)\n\t\t\t\t.in('project_id', projectIds)\n\t\t\t\t.is('deleted_at', null);\n\t\t\tif (pmErr) throw mapPostgrestError(pmErr);\n\n\t\t\tconst { error: defErr } = await client\n\t\t\t\t.from('definitions')\n\t\t\t\t.update(stampRow)\n\t\t\t\t.in('project_id', projectIds)\n\t\t\t\t.is('deleted_at', null);\n\t\t\tif (defErr) throw mapPostgrestError(defErr);\n\t\t}\n\n\t\t// These tables have no `deleted_at` column, and the org soft-delete above\n\t\t// doesn't trigger their FK CASCADE, so clean them up explicitly. Pending\n\t\t// invites and API keys for a dead org are unusable; stale compute config\n\t\t// is operational state with no audit need.\n\t\tconst { error: invErr } = await client.from('invites').delete().eq('org_id', id);\n\t\tif (invErr) throw mapPostgrestError(invErr);\n\n\t\tawait this.grants.deleteByGranteeOrg(ctx, id);\n\t\tfor (const projectId of projectIds) await this.grants.deleteByProject(ctx, projectId);\n\n\t\tconst { error: tokErr } = await client.from('api_tokens').delete().eq('org_id', id);\n\t\tif (tokErr) throw mapPostgrestError(tokErr);\n\n\t\tconst { error: cdErr } = await client\n\t\t\t.from('compute_server_org_defaults')\n\t\t\t.delete()\n\t\t\t.eq('org_id', id);\n\t\tif (cdErr) throw mapPostgrestError(cdErr);\n\n\t\tconst { error: shErr } = await client.from('compute_server_shares').delete().eq('org_id', id);\n\t\tif (shErr) throw mapPostgrestError(shErr);\n\n\t\tconst { error: csErr } = await client\n\t\t\t.from('compute_servers')\n\t\t\t.delete()\n\t\t\t.eq('scope', 'org')\n\t\t\t.eq('owner_org_id', id);\n\t\tif (csErr) throw mapPostgrestError(csErr);\n\n\t\tawait this.events.emit({ type: 'org.deleted', orgId: id, ...actorOf(ctx) });\n\t}\n\n\t// ============================================================================\n\t// Org members\n\t// ============================================================================\n\tasync listOrgMembers(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<OrgMember>> {\n\t\tconst range = toRange(opts);\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('org_members')\n\t\t\t.select(ORG_MEMBER_COLUMNS, { count: 'exact' })\n\t\t\t.eq('org_id', orgId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.order('joined_at', { ascending: (opts?.orderDir ?? 'desc') === 'asc' })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToOrgMember);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync getOrgMember(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string\n\t): Promise<OrgMember | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('org_members')\n\t\t\t.select(ORG_MEMBER_COLUMNS)\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToOrgMember(data) : null;\n\t}\n\n\t// One head count per org, in parallel: tallying selected rows would be capped by\n\t// PostgREST's max-rows, and grouped aggregates are off by default.\n\tasync countOrgMembers(\n\t\tctx: RequestContext,\n\t\torgIds: readonly string[]\n\t): Promise<Map<string, number>> {\n\t\tconst client = this.clients.forRequest(ctx);\n\t\tconst counts = await Promise.all(\n\t\t\torgIds.map(async (orgId) => {\n\t\t\t\tconst { count, error } = await client\n\t\t\t\t\t.from('org_members')\n\t\t\t\t\t.select('user_id', { count: 'exact', head: true })\n\t\t\t\t\t.eq('org_id', orgId)\n\t\t\t\t\t.is('deleted_at', null);\n\t\t\t\tif (error) throw mapPostgrestError(error);\n\t\t\t\treturn [orgId, count ?? 0] as const;\n\t\t\t})\n\t\t);\n\t\treturn new Map(counts);\n\t}\n\n\tasync getOrgMembersFor(\n\t\tctx: RequestContext,\n\t\torgIds: readonly string[],\n\t\tuserId: string\n\t): Promise<Map<string, OrgMember | null>> {\n\t\tconst result = new Map<string, OrgMember | null>(orgIds.map((id) => [id, null]));\n\t\tif (orgIds.length === 0) return result;\n\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('org_members')\n\t\t\t.select(ORG_MEMBER_COLUMNS)\n\t\t\t.in('org_id', [...orgIds])\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of data ?? []) result.set(row.org_id, rowToOrgMember(row));\n\t\treturn result;\n\t}\n\n\tasync findUserMembership(\n\t\tctx: RequestContext,\n\t\tuserId: string\n\t): Promise<{ org: Organization; member: OrgMember } | null> {\n\t\t// One round-trip: join org_members → orgs and filter live rows on\n\t\t// both sides. PostgREST `!inner` on the join keeps it a single SELECT,\n\t\t// avoiding the listOrgs + getOrgMember-per-org N+1 the bootstrap path\n\t\t// used to do. RLS still scopes by ctx; service-role sees all.\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('org_members')\n\t\t\t.select(`${ORG_MEMBER_COLUMNS}, org:orgs!inner(${ORG_COLUMNS})`)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.is('org.deleted_at', null)\n\t\t\t.order('joined_at', { ascending: true })\n\t\t\t.limit(1)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data) return null;\n\n\t\t// PostgREST embeds the related row as `org` per the alias above. Strip\n\t\t// it off the member row before mapping so OrgMember stays clean.\n\t\tconst row = data as OrgMemberRow & { org: OrgRow | OrgRow[] };\n\t\tconst orgRow = Array.isArray(row.org) ? row.org[0] : row.org;\n\t\tif (!orgRow) return null;\n\t\tconst { org: _omit, ...memberRow } = row;\n\t\treturn {\n\t\t\torg: rowToOrg(orgRow),\n\t\t\tmember: rowToOrgMember(memberRow as OrgMemberRow)\n\t\t};\n\t}\n\n\tasync addOrgMember(ctx: RequestContext, member: OrgMember): Promise<void> {\n\t\t// Upsert so a prior soft-deleted row is reactivated rather than throwing\n\t\t// a duplicate-key error. Mirrors LocalOrgStore.addOrgMember.\n\t\tconst row: Record<string, unknown> = {\n\t\t\t...memberToRow(member),\n\t\t\tdeleted_at: null,\n\t\t\t...stampUpdate(ctx)\n\t\t};\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('org_members')\n\t\t\t.upsert(row, { onConflict: 'org_id,user_id' });\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.added',\n\t\t\torgId: member.orgId,\n\t\t\tuserId: member.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateOrgMemberRole(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string,\n\t\trole: OrgRole\n\t): Promise<void> {\n\t\t// Matches LocalOrgStore: changing role re-seeds default permissions for that role.\n\t\tconst row: Record<string, unknown> = {\n\t\t\trole,\n\t\t\tpermissions: [...DEFAULT_ORG_PERMISSIONS[role]],\n\t\t\t...stampUpdate(ctx)\n\t\t};\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('org_members')\n\t\t\t.update(row)\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0)\n\t\t\tthrow new ProviderError(`Org member '${userId}' not found`, 404);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.role_changed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\trole,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateOrgMemberPermissions(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string,\n\t\tpermissions: readonly OrgPermission[]\n\t): Promise<void> {\n\t\t// Distinct from updateOrgMemberRole so callers can grant a finer-grained\n\t\t// set without re-seeding defaults from the role. Matches LocalOrgStore.\n\t\tconst row: Record<string, unknown> = { permissions: [...permissions], ...stampUpdate(ctx) };\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('org_members')\n\t\t\t.update(row)\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0)\n\t\t\tthrow new ProviderError(`Org member '${userId}' not found`, 404);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.permissions_changed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\tpermissions: [...permissions],\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync removeOrgMember(ctx: RequestContext, orgId: string, userId: string): Promise<void> {\n\t\t// An RPC so the membership and the leaver's project memberships end in one\n\t\t// transaction.\n\t\tconst svc = this.clients.serviceClient;\n\t\tlet { error } = await svc.rpc('remove_org_member', {\n\t\t\to: orgId,\n\t\t\tu: userId,\n\t\t\tactor: ctx.userId || null\n\t\t});\n\t\t// The app updates before `20261113120000` is pushed, and the function it\n\t\t// replaces takes no actor. Drop this once that migration is the floor.\n\t\tif (error?.code === 'PGRST202') {\n\t\t\t({ error } = await svc.rpc('remove_org_member', { o: orgId, u: userId }));\n\t\t}\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'org_member.removed',\n\t\t\torgId,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Row ↔ domain mappers\n// ============================================================================\n//\n// Audit columns (`created_by` / `updated_by`) FK to `auth.users(id)` with\n// `ON DELETE SET NULL`, so they can legitimately become NULL when the\n// referenced user is deleted. Mappers fall back to `owner_id` / `user_id` so\n// the domain type stays non-nullable; UIs that care about creator-vs-owner\n// attribution should render \"Deleted user\" at that layer.\n\ninterface OrgRow {\n\tid: string;\n\tname: string;\n\tslug: string;\n\towner_id: string | null;\n\tassets?: Record<string, string> | null;\n\tcreated_by?: string | null;\n\tupdated_by?: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n\tdeleted_at?: string | null;\n}\n\ninterface OrgMemberRow {\n\torg_id: string;\n\tuser_id: string;\n\trole: OrgRole;\n\tpermissions: string[];\n\tjoined_at: string;\n\tupdated_at?: string | null;\n\tupdated_by?: string | null;\n\tdeleted_at?: string | null;\n}\n\nfunction rowToOrg(row: OrgRow): Organization {\n\tconst owner = row.owner_id ?? ERASED_ACTOR_ID;\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\townerId: owner,\n\t\tassets: row.assets ?? undefined,\n\t\tcreatedBy: row.created_by ?? owner,\n\t\tupdatedBy: row.updated_by ?? owner,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tdeletedAt: row.deleted_at ?? null\n\t};\n}\n\nfunction orgToRow(org: Organization): OrgRow {\n\treturn {\n\t\tid: org.id,\n\t\tname: org.name,\n\t\tslug: org.slug,\n\t\towner_id: org.ownerId,\n\t\t// `assets` is `not null default '{}'` — an explicit null defeats the\n\t\t// default and violates the constraint.\n\t\tassets: org.assets ?? {},\n\t\tcreated_by: org.createdBy,\n\t\tupdated_by: org.updatedBy,\n\t\tcreated_at: org.createdAt,\n\t\tupdated_at: org.updatedAt,\n\t\tdeleted_at: org.deletedAt ?? null\n\t};\n}\n\nfunction rowToOrgMember(row: OrgMemberRow): OrgMember {\n\treturn {\n\t\torgId: row.org_id,\n\t\tuserId: row.user_id,\n\t\trole: row.role,\n\t\tpermissions: (row.permissions ?? []) as OrgMember['permissions'],\n\t\tjoinedAt: row.joined_at,\n\t\tupdatedAt: row.updated_at ?? row.joined_at,\n\t\tupdatedBy: row.updated_by ?? row.user_id,\n\t\tdeletedAt: row.deleted_at ?? null\n\t};\n}\n\nfunction memberToRow(m: OrgMember): OrgMemberRow {\n\treturn {\n\t\torg_id: m.orgId,\n\t\tuser_id: m.userId,\n\t\trole: m.role,\n\t\tpermissions: m.permissions ?? [],\n\t\tjoined_at: m.joinedAt\n\t};\n}\n","import type {\n\tIProjectStore,\n\tIEventSink,\n\tProject,\n\tProjectMember,\n\tProjectRole,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { ERASED_ACTOR_ID, ProviderError, actorOf, NoopEventSink } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { SupabasePlatformProjectGrantStore } from './SupabasePlatformProjectGrantStore.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, orderColumn, toRange } from './pagination.js';\nimport { stampSoftDelete, stampUpdate } from './rowStamp.js';\n\n/** Explicit column list for `projects` — every field `rowToProject` consumes. */\nconst PROJECT_COLUMNS =\n\t'id, org_id, name, slug, description, visibility, owner_id, created_by, updated_by, auto_join_on_upload, created_at, updated_at, deleted_at';\n/** Explicit column list for `project_members` — every field `rowToProjectMember` consumes. */\nconst PROJECT_MEMBER_COLUMNS =\n\t'project_id, user_id, role, joined_at, updated_at, updated_by, deleted_at';\n\n/**\n * Project + project-membership store backed by Postgres. Visibility (public /\n * org / private) is enforced by the `visible_project()` RLS helper. Access\n * predicates (canEdit / canManage / canView) live in `@selvajs/platform/access`;\n * the route layer composes them with pre-loaded entities.\n */\nexport class SupabaseProjectStore implements IProjectStore {\n\tprivate readonly events: IEventSink;\n\n\t/** Grants have no soft-delete: deleting a project removes its grants, as in the local provider. */\n\tprivate readonly grants: SupabasePlatformProjectGrantStore;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tevents: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.events = events;\n\t\tthis.grants = new SupabasePlatformProjectGrantStore(clients);\n\t}\n\n\tasync listProjects(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<Project>> {\n\t\tconst range = toRange(opts);\n\t\tconst direction = opts?.orderDir ?? 'desc';\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('projects')\n\t\t\t.select(PROJECT_COLUMNS, { count: 'exact' })\n\t\t\t.eq('org_id', orgId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.order(orderColumn(opts?.orderBy), { ascending: direction === 'asc' })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToProject);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync getProject(ctx: RequestContext, id: string): Promise<Project | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('projects')\n\t\t\t.select(PROJECT_COLUMNS)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToProject(data) : null;\n\t}\n\n\tasync getProjectBySlug(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tslug: string\n\t): Promise<Project | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('projects')\n\t\t\t.select(PROJECT_COLUMNS)\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('slug', slug)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToProject(data) : null;\n\t}\n\n\tasync createProject(ctx: RequestContext, project: Project): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst { error } = await client.from('projects').insert(projectToRow(project));\n\t\tif (error) throw mapPostgrestError(error);\n\n\t\t// Upsert: a stale soft-deleted row from a prior project with this id\n\t\t// gets reactivated instead of blocking creation.\n\t\tconst { error: memberError } = await client.from('project_members').upsert(\n\t\t\t{\n\t\t\t\tproject_id: project.id,\n\t\t\t\tuser_id: project.ownerId,\n\t\t\t\trole: 'owner',\n\t\t\t\tjoined_at: new Date().toISOString(),\n\t\t\t\tdeleted_at: null\n\t\t\t},\n\t\t\t{ onConflict: 'project_id,user_id' }\n\t\t);\n\t\tif (memberError) throw mapPostgrestError(memberError);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project.created',\n\t\t\tprojectId: project.id,\n\t\t\torgId: project.orgId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateProject(\n\t\tctx: RequestContext,\n\t\tid: string,\n\t\tpatch: Partial<\n\t\t\tPick<Project, 'name' | 'slug' | 'description' | 'visibility' | 'autoJoinOnUpload'>\n\t\t>\n\t): Promise<void> {\n\t\tconst row: Record<string, unknown> = {};\n\t\tif (patch.name !== undefined) row.name = patch.name;\n\t\tif (patch.slug !== undefined) row.slug = patch.slug;\n\t\tif (patch.description !== undefined) row.description = patch.description;\n\t\tif (patch.visibility !== undefined) row.visibility = patch.visibility;\n\t\tif (patch.autoJoinOnUpload !== undefined) row.auto_join_on_upload = patch.autoJoinOnUpload;\n\t\tif (Object.keys(row).length === 0) return;\n\t\tObject.assign(row, stampUpdate(ctx));\n\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('projects')\n\t\t\t.update(row)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) throw new ProviderError(`Project '${id}' not found`, 404);\n\t}\n\n\tasync deleteProject(ctx: RequestContext, id: string): Promise<void> {\n\t\t// Soft-delete cascades in app code, not via FK: project → project_members,\n\t\t// definitions. FK CASCADE only fires on a real DELETE.\n\t\tconst client = this.clients.serviceClient;\n\t\tconst stampRow = stampSoftDelete(ctx);\n\n\t\tconst { data, error } = await client\n\t\t\t.from('projects')\n\t\t\t.update(stampRow)\n\t\t\t.eq('id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) throw new ProviderError(`Project '${id}' not found`, 404);\n\n\t\tconst { error: pmErr } = await client\n\t\t\t.from('project_members')\n\t\t\t.update(stampRow)\n\t\t\t.eq('project_id', id)\n\t\t\t.is('deleted_at', null);\n\t\tif (pmErr) throw mapPostgrestError(pmErr);\n\n\t\t// Cascades to definitions inline instead of delegating to the definition\n\t\t// store, to avoid a cross-store constructor dependency. Must stay in sync\n\t\t// with SupabaseDefinitionStore.deleteByProject.\n\t\tconst { data: deletedDefs, error: defErr } = await client\n\t\t\t.from('definitions')\n\t\t\t.update(stampRow)\n\t\t\t.eq('project_id', id)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (defErr) throw mapPostgrestError(defErr);\n\t\tfor (const row of deletedDefs ?? []) {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'definition.deleted',\n\t\t\t\tdefinitionId: row.guid,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\n\t\tawait this.grants.deleteByProject(ctx, id);\n\n\t\tawait this.events.emit({ type: 'project.deleted', projectId: id, ...actorOf(ctx) });\n\t}\n\n\tasync reactivateProject(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tslug: string\n\t): Promise<Project | null> {\n\t\tconst client = this.clients.serviceClient;\n\n\t\t// `.not('deleted_at', 'is', null)` guards against clobbering a live row;\n\t\t// the unique constraint on (org_id, slug) means at most one tombstone exists.\n\t\tconst { data, error } = await client\n\t\t\t.from('projects')\n\t\t\t.update({ deleted_at: null })\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('slug', slug)\n\t\t\t.not('deleted_at', 'is', null)\n\t\t\t.select(PROJECT_COLUMNS)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data) return null;\n\n\t\t// deleteProject cascades the soft-delete to project_members; undo it here too.\n\t\tif (data.owner_id) {\n\t\t\tconst { error: pmErr } = await client\n\t\t\t\t.from('project_members')\n\t\t\t\t.update({ deleted_at: null })\n\t\t\t\t.eq('project_id', data.id)\n\t\t\t\t.eq('user_id', data.owner_id)\n\t\t\t\t.not('deleted_at', 'is', null);\n\t\t\tif (pmErr) throw mapPostgrestError(pmErr);\n\t\t}\n\n\t\tconst project = rowToProject(data);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project.created',\n\t\t\tprojectId: project.id,\n\t\t\torgId: project.orgId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t\treturn project;\n\t}\n\n\t// ============================================================================\n\t// Project members\n\t// ============================================================================\n\tasync listProjectMembers(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<ProjectMember>> {\n\t\tconst range = toRange(opts);\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('project_members')\n\t\t\t.select(PROJECT_MEMBER_COLUMNS, { count: 'exact' })\n\t\t\t.eq('project_id', projectId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.order('joined_at', { ascending: (opts?.orderDir ?? 'desc') === 'asc' })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToProjectMember);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync getProjectMember(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\tuserId: string\n\t): Promise<ProjectMember | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('project_members')\n\t\t\t.select(PROJECT_MEMBER_COLUMNS)\n\t\t\t.eq('project_id', projectId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToProjectMember(data) : null;\n\t}\n\n\tasync getProjectMembersFor(\n\t\tctx: RequestContext,\n\t\tprojectIds: readonly string[],\n\t\tuserId: string\n\t): Promise<Map<string, ProjectMember | null>> {\n\t\tconst result = new Map<string, ProjectMember | null>(projectIds.map((id) => [id, null]));\n\t\tif (projectIds.length === 0) return result;\n\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('project_members')\n\t\t\t.select(PROJECT_MEMBER_COLUMNS)\n\t\t\t.in('project_id', [...projectIds])\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of data ?? []) result.set(row.project_id, rowToProjectMember(row));\n\t\treturn result;\n\t}\n\n\t// One head count per project, in parallel: tallying selected rows would be capped\n\t// by PostgREST's max-rows, and grouped aggregates are off by default.\n\tasync countProjectMembers(\n\t\tctx: RequestContext,\n\t\tprojectIds: readonly string[]\n\t): Promise<Map<string, number>> {\n\t\tconst client = this.clients.forRequest(ctx);\n\t\tconst counts = await Promise.all(\n\t\t\tprojectIds.map(async (projectId) => {\n\t\t\t\tconst { count, error } = await client\n\t\t\t\t\t.from('project_members')\n\t\t\t\t\t.select('user_id', { count: 'exact', head: true })\n\t\t\t\t\t.eq('project_id', projectId)\n\t\t\t\t\t.is('deleted_at', null);\n\t\t\t\tif (error) throw mapPostgrestError(error);\n\t\t\t\treturn [projectId, count ?? 0] as const;\n\t\t\t})\n\t\t);\n\t\treturn new Map(counts);\n\t}\n\n\tasync addProjectMember(ctx: RequestContext, member: ProjectMember): Promise<void> {\n\t\t// Upsert reactivates a prior soft-deleted row instead of throwing duplicate-key.\n\t\tconst row: Record<string, unknown> = {\n\t\t\t...projectMemberToRow(member),\n\t\t\tdeleted_at: null,\n\t\t\t...stampUpdate(ctx)\n\t\t};\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('project_members')\n\t\t\t.upsert(row, { onConflict: 'project_id,user_id' });\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.added',\n\t\t\tprojectId: member.projectId,\n\t\t\tuserId: member.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync updateProjectMemberRole(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\tuserId: string,\n\t\trole: ProjectRole\n\t): Promise<void> {\n\t\tconst row: Record<string, unknown> = { role, ...stampUpdate(ctx) };\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('project_members')\n\t\t\t.update(row)\n\t\t\t.eq('project_id', projectId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0)\n\t\t\tthrow new ProviderError(`Project member '${userId}' not found`, 404);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.role_changed',\n\t\t\tprojectId,\n\t\t\tuserId,\n\t\t\trole,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync removeProjectMember(ctx: RequestContext, projectId: string, userId: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('project_members')\n\t\t\t.update(stampSoftDelete(ctx))\n\t\t\t.eq('project_id', projectId)\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('deleted_at', null);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'project_member.removed',\n\t\t\tprojectId,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Row ↔ domain mappers\n// ============================================================================\n//\n// `created_by` / `updated_by` FK to `auth.users(id)` ON DELETE SET NULL, so they\n// go NULL when that user is deleted. Mappers fall back to owner_id (Project) or\n// user_id / joined_at (ProjectMember) to keep the domain type non-nullable.\n\ninterface ProjectRow {\n\tid: string;\n\torg_id: string;\n\tname: string;\n\tslug: string;\n\tdescription: string | null;\n\tvisibility: Project['visibility'];\n\towner_id: string | null;\n\tcreated_by?: string | null;\n\tupdated_by?: string | null;\n\tauto_join_on_upload?: boolean | null;\n\tcreated_at: string;\n\tupdated_at: string;\n\tdeleted_at?: string | null;\n}\n\ninterface ProjectMemberRow {\n\tproject_id: string;\n\tuser_id: string;\n\trole: ProjectRole;\n\tjoined_at: string;\n\tupdated_at?: string | null;\n\tupdated_by?: string | null;\n\tdeleted_at?: string | null;\n}\n\nfunction rowToProject(row: ProjectRow): Project {\n\tconst owner = row.owner_id ?? ERASED_ACTOR_ID;\n\treturn {\n\t\tid: row.id,\n\t\torgId: row.org_id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tdescription: row.description ?? undefined,\n\t\tvisibility: row.visibility,\n\t\townerId: owner,\n\t\tcreatedBy: row.created_by ?? owner,\n\t\tupdatedBy: row.updated_by ?? owner,\n\t\tautoJoinOnUpload: row.auto_join_on_upload ?? false,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tdeletedAt: row.deleted_at ?? null\n\t};\n}\n\nfunction projectToRow(p: Project): ProjectRow {\n\treturn {\n\t\tid: p.id,\n\t\torg_id: p.orgId,\n\t\tname: p.name,\n\t\tslug: p.slug,\n\t\tdescription: p.description ?? null,\n\t\tvisibility: p.visibility,\n\t\towner_id: p.ownerId,\n\t\tcreated_by: p.createdBy,\n\t\tupdated_by: p.updatedBy,\n\t\tauto_join_on_upload: p.autoJoinOnUpload,\n\t\tcreated_at: p.createdAt,\n\t\tupdated_at: p.updatedAt,\n\t\tdeleted_at: p.deletedAt ?? null\n\t};\n}\n\nfunction rowToProjectMember(row: ProjectMemberRow): ProjectMember {\n\treturn {\n\t\tprojectId: row.project_id,\n\t\tuserId: row.user_id,\n\t\trole: row.role,\n\t\tjoinedAt: row.joined_at,\n\t\tupdatedAt: row.updated_at ?? row.joined_at,\n\t\tupdatedBy: row.updated_by ?? row.user_id,\n\t\tdeletedAt: row.deleted_at ?? null\n\t};\n}\n\nfunction projectMemberToRow(m: ProjectMember): ProjectMemberRow {\n\treturn {\n\t\tproject_id: m.projectId,\n\t\tuser_id: m.userId,\n\t\trole: m.role,\n\t\tjoined_at: m.joinedAt\n\t};\n}\n","import type {\n\tIDefinitionStore,\n\tIEventSink,\n\tDefinitionRecord,\n\tDefinitionRecordPatch,\n\tDefinitionStatus,\n\tDefinitionFileExt,\n\tDefinitionVersion,\n\tRequestContext,\n\tDefinitionListOptions,\n\tListOptions,\n\tPage,\n\tUISchema,\n\tDocumentInventory,\n\tInventorySummary\n} from '@selvajs/platform';\nimport { ERASED_ACTOR_ID, ProviderError, actorOf, NoopEventSink } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, toRange } from './pagination.js';\nimport { stampSoftDelete, stampUpdate } from './rowStamp.js';\n\n/** Explicit column list for `definitions` — every field `rowToRecord` consumes. */\nconst DEFINITION_COLUMNS =\n\t'guid, project_id, owner_id, created_by, updated_by, compute_server_id, solve_cache_limit, display_name, description, category, tags, cover_image, status, run_count, next_version_number, live_version_id, draft_version_id, source_document_id, created_at, updated_at, deleted_at';\n/**\n * Explicit column list for `definition_versions`, minus the `schema`, `inventory` and\n * `saved_values` JSONB. Each can be hundreds of KB per row, so the list projection leaves them out\n * and `listVersions` returns rows without them; only `getVersion`\n * (which reads one row, for a caller that needs them) pulls them in.\n */\nconst DEFINITION_VERSION_COLUMNS =\n\t'id, definition_guid, version_number, file_ext, file_key, original_filename, uploaded_by, uploaded_at, change_note, schema_extracted_at, inventory_summary';\n/**\n * `getVersion`'s projection — the list columns plus the `schema`, `inventory` and `saved_values` JSONB. Spelled\n * out rather than built with a template literal: supabase-js infers the row\n * type from the literal column string, and a template literal degrades it to\n * `string`.\n */\n/** PostgREST's default `max-rows`: a longer read comes back cut at it. */\nconst VERSIONS_PAGE = 1000;\n\nconst DEFINITION_VERSION_COLUMNS_WITH_SCHEMA =\n\t'id, definition_guid, version_number, file_ext, file_key, original_filename, uploaded_by, uploaded_at, change_note, schema_extracted_at, inventory_summary, schema, inventory, saved_values';\n\n/**\n * Definition metadata + version store backed by Postgres. `definitions` carries\n * the parent record and the `live`/`draft` channel pointers; `definition_versions`\n * carries the immutable per-upload rows.\n */\nexport class SupabaseDefinitionStore implements IDefinitionStore {\n\tprivate readonly events: IEventSink;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tevents: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.events = events;\n\t}\n\n\t// ============================================================================\n\t// Definitions\n\t// ============================================================================\n\n\tasync list(ctx: RequestContext, opts?: DefinitionListOptions): Promise<Page<DefinitionRecord>> {\n\t\treturn this.runList(ctx, undefined, opts);\n\t}\n\n\tasync listByProject(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\topts?: DefinitionListOptions\n\t): Promise<Page<DefinitionRecord>> {\n\t\treturn this.runList(ctx, { projectId }, opts);\n\t}\n\n\tasync listPublic(\n\t\tctx: RequestContext,\n\t\topts?: DefinitionListOptions & { orgId?: string }\n\t): Promise<Page<DefinitionRecord>> {\n\t\treturn this.runList(ctx, { publicOnly: true, orgId: opts?.orgId }, opts);\n\t}\n\n\tprivate async runList(\n\t\tctx: RequestContext,\n\t\tfilter: { projectId?: string; publicOnly?: boolean; orgId?: string } | undefined,\n\t\topts?: DefinitionListOptions\n\t): Promise<Page<DefinitionRecord>> {\n\t\tconst range = toRange(opts);\n\t\tconst direction = opts?.orderDir ?? 'desc';\n\n\t\t// Picked up front so there's a single `.select()` call — calling it twice\n\t\t// (once per branch) would give the builder two different inferred types.\n\t\tconst selectColumns = filter?.publicOnly\n\t\t\t? `${DEFINITION_COLUMNS}, project:projects!inner(visibility, org_id)`\n\t\t\t: DEFINITION_COLUMNS;\n\n\t\tlet query = this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('definitions')\n\t\t\t.select(selectColumns, { count: 'exact' })\n\t\t\t.is('deleted_at', null);\n\n\t\tif (filter?.publicOnly) {\n\t\t\tquery = query.eq('project.visibility', 'public');\n\t\t\tif (filter.orgId) query = query.eq('project.org_id', filter.orgId);\n\t\t}\n\n\t\tif (filter?.projectId) query = query.eq('project_id', filter.projectId);\n\n\t\t// An empty `projectIds` must match nothing. PostgREST's `in.()` is a syntax\n\t\t// error, so short-circuit rather than building the query.\n\t\tif (opts?.projectIds) {\n\t\t\tif (opts.projectIds.length === 0) return { items: [] };\n\t\t\tquery = query.in('project_id', [...opts.projectIds]);\n\t\t}\n\n\t\tif (opts?.sourceDocumentId) query = query.eq('source_document_id', opts.sourceDocumentId);\n\n\t\tif (opts?.statuses?.length) {\n\t\t\tquery = query.in('status', opts.statuses);\n\t\t} else {\n\t\t\tconst excluded: string[] = [];\n\t\t\tif (!opts?.includePending) excluded.push('pending');\n\t\t\tif (!opts?.includeArchived) excluded.push('archived');\n\t\t\tif (excluded.length) {\n\t\t\t\tquery = query.not('status', 'in', `(${excluded.join(',')})`);\n\t\t\t}\n\t\t}\n\n\t\tquery = query\n\t\t\t.order(definitionOrderColumn(opts?.orderBy), { ascending: direction === 'asc' })\n\t\t\t.range(range.from, range.to);\n\n\t\tconst { data, error, count } = await query;\n\t\tif (error) throw mapPostgrestError(error);\n\t\t// `data`'s type comes from the dynamic select string, which PostgREST\n\t\t// can't resolve to a row shape — the columns are all present regardless,\n\t\t// so cast through the known `DefinitionRow`.\n\t\tconst items = ((data ?? []) as unknown as DefinitionRow[]).map(rowToRecord);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync get(ctx: RequestContext, guid: string): Promise<DefinitionRecord | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('definitions')\n\t\t\t.select(DEFINITION_COLUMNS)\n\t\t\t.eq('guid', guid)\n\t\t\t.is('deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToRecord(data) : null;\n\t}\n\n\tasync getDefinitionsFor(\n\t\tctx: RequestContext,\n\t\tguids: readonly string[]\n\t): Promise<Map<string, DefinitionRecord>> {\n\t\tconst found = new Map<string, DefinitionRecord>();\n\t\tif (guids.length === 0) return found;\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('definitions')\n\t\t\t.select(DEFINITION_COLUMNS)\n\t\t\t.in('guid', [...new Set(guids)])\n\t\t\t.is('deleted_at', null);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of data ?? []) found.set(row.guid, rowToRecord(row));\n\t\treturn found;\n\t}\n\n\tasync create(ctx: RequestContext, record: DefinitionRecord): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definitions')\n\t\t\t.insert(recordToRow(record));\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition.created',\n\t\t\tdefinitionId: record.guid,\n\t\t\tprojectId: record.projectId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync update(ctx: RequestContext, guid: string, patch: DefinitionRecordPatch): Promise<void> {\n\t\tconst row = patchToRow(patch);\n\t\tif (Object.keys(row).length === 0) return;\n\t\tObject.assign(row, stampUpdate(ctx));\n\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('definitions')\n\t\t\t.update(row)\n\t\t\t.eq('guid', guid)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) throw new ProviderError(`Definition '${guid}' not found`, 404);\n\t}\n\n\tasync delete(ctx: RequestContext, guid: string): Promise<void> {\n\t\t// Soft-delete, matching the local provider. A retention sweep running\n\t\t// as service-role hard-deletes later, which cascades versions +\n\t\t// share_links via FK.\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('definitions')\n\t\t\t.update(stampSoftDelete(ctx))\n\t\t\t.eq('guid', guid)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (error) throw mapPostgrestError(error);\n\t\t// No row: already deleted. Not a deletion to record.\n\t\tif (!data || data.length === 0) return;\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition.deleted',\n\t\t\tdefinitionId: guid,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync deleteByProject(ctx: RequestContext, projectId: string): Promise<void> {\n\t\t// Cascade from `deleteProject`. `select('guid')` returns the affected rows\n\t\t// so we can emit a `definition.deleted` per record, matching the local\n\t\t// provider and the single-`delete` path above.\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('definitions')\n\t\t\t.update(stampSoftDelete(ctx))\n\t\t\t.eq('project_id', projectId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of data ?? []) {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'definition.deleted',\n\t\t\t\tdefinitionId: row.guid,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\t}\n\n\tasync incrementSolveCount(ctx: RequestContext, guid: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient.rpc('increment_run_count', { g: guid });\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync reserveNextVersionNumber(ctx: RequestContext, guid: string): Promise<number> {\n\t\t// Atomic reserve-and-increment in one SQL function — no read-modify-write\n\t\t// race. Raises no_data_found (mapped to 404) when the definition is\n\t\t// missing or soft-deleted.\n\t\tconst { data, error } = await this.clients.serviceClient.rpc('reserve_next_version_number', {\n\t\t\tg: guid\n\t\t});\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (typeof data !== 'number') {\n\t\t\tthrow new ProviderError(`Definition '${guid}' not found`, 404);\n\t\t}\n\t\treturn data;\n\t}\n\n\t// ============================================================================\n\t// Versions\n\t// ============================================================================\n\n\tasync createVersion(ctx: RequestContext, version: DefinitionVersion): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definition_versions')\n\t\t\t.insert(versionToRow(version));\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition_version.created',\n\t\t\tversionId: version.id,\n\t\t\tdefinitionId: version.definitionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync listVersions(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<DefinitionVersion>> {\n\t\tconst range = toRange(opts);\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('definition_versions')\n\t\t\t.select(DEFINITION_VERSION_COLUMNS, { count: 'exact' })\n\t\t\t.eq('definition_guid', definitionId)\n\t\t\t.order('version_number', { ascending: false })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToVersion);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync listVersionsFor(\n\t\tctx: RequestContext,\n\t\tdefinitionIds: readonly string[]\n\t): Promise<Map<string, DefinitionVersion[]>> {\n\t\tconst byDefinition = new Map<string, DefinitionVersion[]>(definitionIds.map((id) => [id, []]));\n\t\tif (definitionIds.length === 0) return byDefinition;\n\t\t// Paged by PostgREST's row cap; the order keeps each definition's versions newest first.\n\t\tfor (let from = 0; ; from += VERSIONS_PAGE) {\n\t\t\tconst { data, error } = await this.clients\n\t\t\t\t.forRequest(ctx)\n\t\t\t\t.from('definition_versions')\n\t\t\t\t.select(DEFINITION_VERSION_COLUMNS)\n\t\t\t\t.in('definition_guid', [...new Set(definitionIds)])\n\t\t\t\t.order('definition_guid')\n\t\t\t\t.order('version_number', { ascending: false })\n\t\t\t\t.range(from, from + VERSIONS_PAGE - 1);\n\t\t\tif (error) throw mapPostgrestError(error);\n\t\t\tconst rows = data ?? [];\n\t\t\tfor (const row of rows) byDefinition.get(row.definition_guid)?.push(rowToVersion(row));\n\t\t\tif (rows.length < VERSIONS_PAGE) return byDefinition;\n\t\t}\n\t}\n\n\tasync getVersion(ctx: RequestContext, versionId: string): Promise<DefinitionVersion | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('definition_versions')\n\t\t\t.select(DEFINITION_VERSION_COLUMNS_WITH_SCHEMA)\n\t\t\t.eq('id', versionId)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToVersion(data) : null;\n\t}\n\n\tasync setVersionSchema(ctx: RequestContext, versionId: string, schema: UISchema): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definition_versions')\n\t\t\t.update({ schema, schema_extracted_at: new Date().toISOString() })\n\t\t\t.eq('id', versionId);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync setVersionInventory(\n\t\t_ctx: RequestContext,\n\t\tversionId: string,\n\t\tinventory: DocumentInventory,\n\t\tsummary: InventorySummary\n\t): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definition_versions')\n\t\t\t.update({ inventory, inventory_summary: summary })\n\t\t\t.eq('id', versionId);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync setVersionSavedValues(\n\t\t_ctx: RequestContext,\n\t\tversionId: string,\n\t\tvalues: Record<string, unknown>\n\t): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definition_versions')\n\t\t\t.update({ saved_values: values })\n\t\t\t.eq('id', versionId);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync deleteVersion(ctx: RequestContext, versionId: string): Promise<void> {\n\t\t// live_version_id / draft_version_id are ON DELETE RESTRICT — if the\n\t\t// version is referenced by either channel, Postgres raises 23503 →\n\t\t// mapPostgrestError → ProviderError(409).\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('definition_versions')\n\t\t\t.delete()\n\t\t\t.eq('id', versionId);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition_version.deleted',\n\t\t\tversionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync setLiveVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tawait this.repointChannel(ctx, definitionId, versionId, 'live_version_id');\n\t\t// Only `live` advancement fires `definition.published`. Draft repointing\n\t\t// is the editor's working pointer, not a publication signal.\n\t\tawait this.events.emit({\n\t\t\ttype: 'definition.published',\n\t\t\tdefinitionId,\n\t\t\tversionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync setDraftVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tawait this.repointChannel(ctx, definitionId, versionId, 'draft_version_id');\n\t}\n\n\tasync attachInitialVersion(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string\n\t): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\t// Duplicates repointChannel's ownership check rather than calling it,\n\t\t// so the bootstrap path enforces the same invariant independently of\n\t\t// the two-channel repoint logic.\n\t\tconst { data: version, error: vError } = await client\n\t\t\t.from('definition_versions')\n\t\t\t.select('id, definition_guid')\n\t\t\t.eq('id', versionId)\n\t\t\t.maybeSingle();\n\t\tif (vError) throw mapPostgrestError(vError);\n\t\tif (!version || version.definition_guid !== definitionId) {\n\t\t\tthrow new ProviderError(`Version '${versionId}' not found for this definition`, 404);\n\t\t}\n\n\t\t// Single UPDATE — both channel pointers and status flip in one row\n\t\t// write, so a mid-flight failure can't leave a half-promoted record.\n\t\tconst row: Record<string, unknown> = {\n\t\t\tlive_version_id: versionId,\n\t\t\tdraft_version_id: versionId,\n\t\t\tstatus: 'draft',\n\t\t\t...stampUpdate(ctx)\n\t\t};\n\n\t\tconst { data, error } = await client\n\t\t\t.from('definitions')\n\t\t\t.update(row)\n\t\t\t.eq('guid', definitionId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) {\n\t\t\tthrow new ProviderError(`Definition '${definitionId}' not found`, 404);\n\t\t}\n\t\t// No `definition.published` event: this is a bootstrap, not a publish.\n\t}\n\n\tprivate async repointChannel(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\tversionId: string,\n\t\tcolumn: 'live_version_id' | 'draft_version_id'\n\t): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst { data: version, error: vError } = await client\n\t\t\t.from('definition_versions')\n\t\t\t.select('id, definition_guid')\n\t\t\t.eq('id', versionId)\n\t\t\t.maybeSingle();\n\t\tif (vError) throw mapPostgrestError(vError);\n\t\tif (!version || version.definition_guid !== definitionId) {\n\t\t\tthrow new ProviderError(`Version '${versionId}' not found for this definition`, 404);\n\t\t}\n\n\t\tconst row: Record<string, unknown> = { [column]: versionId, ...stampUpdate(ctx) };\n\t\tconst { data, error } = await client\n\t\t\t.from('definitions')\n\t\t\t.update(row)\n\t\t\t.eq('guid', definitionId)\n\t\t\t.is('deleted_at', null)\n\t\t\t.select('guid');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) {\n\t\t\tthrow new ProviderError(`Definition '${definitionId}' not found`, 404);\n\t\t}\n\t}\n}\n\n// ============================================================================\n// Row ↔ domain mappers\n// ============================================================================\ninterface DefinitionRow {\n\tguid: string;\n\tproject_id: string;\n\towner_id: string | null;\n\tcreated_by?: string | null;\n\tupdated_by?: string | null;\n\tcompute_server_id: string | null;\n\tsolve_cache_limit: number | string | null;\n\tdisplay_name: string;\n\tdescription: string | null;\n\tcategory: string | null;\n\ttags: string[] | null;\n\tcover_image: string | null;\n\tstatus: DefinitionStatus;\n\trun_count: number | string;\n\tnext_version_number: number | string;\n\tlive_version_id: string | null;\n\tdraft_version_id: string | null;\n\tsource_document_id?: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n\tdeleted_at?: string | null;\n}\n\ninterface DefinitionVersionRow {\n\tid: string;\n\tdefinition_guid: string;\n\tversion_number: number;\n\tfile_ext: DefinitionFileExt;\n\tfile_key: string;\n\toriginal_filename: string | null;\n\tuploaded_by: string | null;\n\tuploaded_at: string;\n\tchange_note?: string | null;\n\tschema?: UISchema | null;\n\tschema_extracted_at?: string | null;\n\tinventory?: DocumentInventory | null;\n\tinventory_summary?: InventorySummary | null;\n\tsaved_values?: Record<string, unknown> | null;\n}\n\nfunction rowToRecord(row: DefinitionRow): DefinitionRecord {\n\tconst owner = row.owner_id ?? ERASED_ACTOR_ID;\n\treturn {\n\t\tguid: row.guid,\n\t\tprojectId: row.project_id,\n\t\townerId: owner,\n\t\tcreatedBy: row.created_by ?? owner,\n\t\tupdatedBy: row.updated_by ?? owner,\n\t\tliveVersionId: row.live_version_id,\n\t\tdraftVersionId: row.draft_version_id,\n\t\tcomputeServerId: row.compute_server_id ?? undefined,\n\t\tsolveCacheLimit:\n\t\t\trow.solve_cache_limit == null\n\t\t\t\t? undefined\n\t\t\t\t: typeof row.solve_cache_limit === 'string'\n\t\t\t\t\t? Number(row.solve_cache_limit)\n\t\t\t\t\t: row.solve_cache_limit,\n\t\tdisplayName: row.display_name,\n\t\tdescription: row.description ?? undefined,\n\t\tcategory: row.category ?? undefined,\n\t\ttags: row.tags ?? undefined,\n\t\tcoverImage: row.cover_image ?? undefined,\n\t\tstatus: row.status,\n\t\tsolveCount: typeof row.run_count === 'string' ? Number(row.run_count) : row.run_count,\n\t\tnextVersionNumber:\n\t\t\ttypeof row.next_version_number === 'string'\n\t\t\t\t? Number(row.next_version_number)\n\t\t\t\t: row.next_version_number,\n\t\tsourceDocumentId: row.source_document_id ?? undefined,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tdeletedAt: row.deleted_at ?? null\n\t};\n}\n\nfunction recordToRow(r: DefinitionRecord): Record<string, unknown> {\n\tconst row: Record<string, unknown> = {\n\t\tguid: r.guid,\n\t\tproject_id: r.projectId,\n\t\towner_id: r.ownerId,\n\t\tcreated_by: r.createdBy,\n\t\tupdated_by: r.updatedBy,\n\t\tlive_version_id: r.liveVersionId,\n\t\tdraft_version_id: r.draftVersionId,\n\t\tcompute_server_id: r.computeServerId ?? null,\n\t\tsolve_cache_limit: r.solveCacheLimit ?? null,\n\t\tdisplay_name: r.displayName,\n\t\tdescription: r.description ?? null,\n\t\tcategory: r.category ?? null,\n\t\tcover_image: r.coverImage ?? null,\n\t\tstatus: r.status,\n\t\trun_count: r.solveCount,\n\t\tnext_version_number: r.nextVersionNumber,\n\t\tsource_document_id: r.sourceDocumentId ?? null,\n\t\tcreated_at: r.createdAt,\n\t\tupdated_at: r.updatedAt,\n\t\tdeleted_at: r.deletedAt ?? null\n\t};\n\tif (r.tags !== undefined) row.tags = r.tags;\n\treturn row;\n}\n\nfunction patchToRow(patch: DefinitionRecordPatch): Record<string, unknown> {\n\tconst row: Record<string, unknown> = {};\n\tif (patch.displayName !== undefined) row.display_name = patch.displayName;\n\tif (patch.description !== undefined) row.description = patch.description;\n\tif (patch.category !== undefined) row.category = patch.category;\n\tif (patch.tags !== undefined) row.tags = patch.tags ?? [];\n\tif (patch.coverImage !== undefined) row.cover_image = patch.coverImage;\n\tif (patch.projectId !== undefined) row.project_id = patch.projectId;\n\tif (patch.computeServerId !== undefined) row.compute_server_id = patch.computeServerId;\n\tif (patch.solveCacheLimit !== undefined) row.solve_cache_limit = patch.solveCacheLimit;\n\tif (patch.status !== undefined) row.status = patch.status;\n\tif (patch.ownerId !== undefined) row.owner_id = patch.ownerId;\n\tif (patch.sourceDocumentId !== undefined) row.source_document_id = patch.sourceDocumentId;\n\treturn row;\n}\n\nfunction rowToVersion(row: DefinitionVersionRow): DefinitionVersion {\n\treturn {\n\t\tid: row.id,\n\t\tdefinitionId: row.definition_guid,\n\t\tversionNumber: row.version_number,\n\t\tfileExt: row.file_ext,\n\t\tfileKey: row.file_key,\n\t\toriginalFilename: row.original_filename ?? undefined,\n\t\tuploadedBy: row.uploaded_by ?? ERASED_ACTOR_ID,\n\t\tuploadedAt: row.uploaded_at,\n\t\tchangeNote: row.change_note ?? undefined,\n\t\tschema: row.schema ?? undefined,\n\t\tschemaExtractedAt: row.schema_extracted_at ?? undefined,\n\t\tinventory: row.inventory ?? undefined,\n\t\tinventorySummary: row.inventory_summary ?? undefined,\n\t\tsavedValues: row.saved_values ?? undefined\n\t};\n}\n\nfunction versionToRow(v: DefinitionVersion): Record<string, unknown> {\n\tconst row: Record<string, unknown> = {\n\t\tid: v.id,\n\t\tdefinition_guid: v.definitionId,\n\t\tversion_number: v.versionNumber,\n\t\tfile_ext: v.fileExt,\n\t\tfile_key: v.fileKey,\n\t\toriginal_filename: v.originalFilename ?? null,\n\t\tuploaded_by: v.uploadedBy,\n\t\tuploaded_at: v.uploadedAt\n\t};\n\tif (v.changeNote !== undefined) row.change_note = v.changeNote;\n\tif (v.schema !== undefined) row.schema = v.schema;\n\tif (v.schemaExtractedAt !== undefined) row.schema_extracted_at = v.schemaExtractedAt;\n\tif (v.inventory !== undefined) row.inventory = v.inventory;\n\tif (v.inventorySummary !== undefined) row.inventory_summary = v.inventorySummary;\n\tif (v.savedValues !== undefined) row.saved_values = v.savedValues;\n\treturn row;\n}\n\nfunction definitionOrderColumn(orderBy: DefinitionListOptions['orderBy'] | undefined): string {\n\tswitch (orderBy) {\n\t\tcase 'name':\n\t\t\treturn 'display_name';\n\t\tcase 'solveCount':\n\t\t\treturn 'run_count';\n\t\tcase 'updatedAt':\n\t\t\treturn 'updated_at';\n\t\tcase 'createdAt':\n\t\tdefault:\n\t\t\treturn 'created_at';\n\t}\n}\n","import type {\n\tIInviteStore,\n\tIEventSink,\n\tInvite,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { NoopEventSink, actorOf } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, toRange } from './pagination.js';\n\n/** Explicit column list for `invites` — every field `rowToInvite` consumes. */\nconst INVITE_COLUMNS =\n\t'id, token_hash, email, org_id, org_role, org_permissions, platform_permissions, invited_by, created_at, expires_at, accepted_at, accepted_by_user_id';\n\n/**\n * Invite store. `getByTokenHash` routes through a SECURITY DEFINER RPC so an\n * unauthenticated caller (still validating an invite link) can resolve it\n * without RLS blocking them. The raw token is hashed at the route layer\n * (`invites/token.server.ts` in the selva app); this store only ever sees the\n * HMAC digest. Reads run as the caller, where RLS asks for `manage_org_members`;\n * writes run as the service role.\n */\nexport class SupabaseInviteStore implements IInviteStore {\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tprivate readonly events: IEventSink = new NoopEventSink()\n\t) {}\n\n\tasync create(ctx: RequestContext, invite: Invite): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient.from('invites').insert(inviteToRow(invite));\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.created',\n\t\t\tinviteId: invite.id,\n\t\t\torgId: invite.orgId,\n\t\t\temail: invite.email,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync getByTokenHash(ctx: RequestContext, tokenHash: string): Promise<Invite | null> {\n\t\t// SECURITY DEFINER RPC: the token itself is the capability, so an\n\t\t// unauthenticated caller on /accept-invite can still resolve it.\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.rpc('get_invite_by_token_hash', { h: tokenHash });\n\t\tif (error) throw mapPostgrestError(error);\n\t\t// PostgREST may wrap a scalar-returning RPC result in an array depending\n\t\t// on the function signature — normalize both shapes.\n\t\tconst row = Array.isArray(data) ? data[0] : data;\n\t\treturn row ? rowToInvite(row as InviteRow) : null;\n\t}\n\n\tasync listByOrg(ctx: RequestContext, orgId: string, opts?: ListOptions): Promise<Page<Invite>> {\n\t\tconst range = toRange(opts);\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('invites')\n\t\t\t.select(INVITE_COLUMNS, { count: 'exact' })\n\t\t\t.eq('org_id', orgId)\n\t\t\t.order('created_at', { ascending: (opts?.orderDir ?? 'desc') === 'asc' })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToInvite);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync markAccepted(ctx: RequestContext, id: string, userId: string): Promise<boolean> {\n\t\t// `.is('accepted_at', null)` makes this the claim: a second call matches nothing.\n\t\tconst now = new Date().toISOString();\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('invites')\n\t\t\t.update({ accepted_at: now, accepted_by_user_id: userId })\n\t\t\t.eq('id', id)\n\t\t\t.is('accepted_at', null)\n\t\t\t.gt('expires_at', now)\n\t\t\t.select('org_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst row = data?.[0];\n\t\tif (!row) return false;\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.accepted',\n\t\t\tinviteId: id,\n\t\t\torgId: (row as { org_id: string }).org_id,\n\t\t\tuserId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t\treturn true;\n\t}\n\n\tasync reopen(ctx: RequestContext, id: string, userId: string): Promise<boolean> {\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('invites')\n\t\t\t.update({ accepted_at: null, accepted_by_user_id: null })\n\t\t\t.eq('id', id)\n\t\t\t.eq('accepted_by_user_id', userId)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn (data?.length ?? 0) > 0;\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('invites')\n\t\t\t.delete()\n\t\t\t.eq('id', id)\n\t\t\t.is('accepted_at', null)\n\t\t\t.select('org_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst row = data?.[0];\n\t\tif (!row) return;\n\t\tawait this.events.emit({\n\t\t\ttype: 'invite.revoked',\n\t\t\tinviteId: id,\n\t\t\torgId: (row as { org_id: string }).org_id,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync revokePendingByEmail(ctx: RequestContext, orgId: string, email: string): Promise<string[]> {\n\t\t// Emails are stored lowercase at mint time; normalize the needle too so an\n\t\t// offboarding call with the address as the admin typed it still matches.\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('invites')\n\t\t\t.delete()\n\t\t\t.eq('org_id', orgId)\n\t\t\t.eq('email', email.trim().toLowerCase())\n\t\t\t.is('accepted_at', null)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst ids = (data ?? []).map((r) => (r as { id: string }).id);\n\t\tfor (const id of ids) {\n\t\t\tawait this.events.emit({\n\t\t\t\ttype: 'invite.revoked',\n\t\t\t\tinviteId: id,\n\t\t\t\torgId,\n\t\t\t\t...actorOf(ctx)\n\t\t\t});\n\t\t}\n\t\treturn ids;\n\t}\n\n\tasync deleteByOrg(ctx: RequestContext, orgId: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient.from('invites').delete().eq('org_id', orgId);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n}\n\ninterface InviteRow {\n\tid: string;\n\ttoken_hash: string;\n\temail: string;\n\torg_id: string;\n\torg_role: Invite['orgRole'];\n\torg_permissions: string[];\n\tplatform_permissions: string[];\n\tinvited_by: string;\n\tcreated_at: string;\n\texpires_at: string;\n\taccepted_at: string | null;\n\taccepted_by_user_id: string | null;\n}\n\nfunction rowToInvite(row: InviteRow): Invite {\n\treturn {\n\t\tid: row.id,\n\t\ttokenHash: row.token_hash,\n\t\temail: row.email,\n\t\torgId: row.org_id,\n\t\torgRole: row.org_role,\n\t\torgPermissions: row.org_permissions as Invite['orgPermissions'],\n\t\t// `?? []` covers a row read through a client whose projection predates the\n\t\t// column, not a null default — the column is `not null default '{}'`.\n\t\tplatformPermissions: (row.platform_permissions ?? []) as NonNullable<\n\t\t\tInvite['platformPermissions']\n\t\t>,\n\t\tinvitedBy: row.invited_by,\n\t\tcreatedAt: row.created_at,\n\t\texpiresAt: row.expires_at,\n\t\tacceptedAt: row.accepted_at ?? undefined,\n\t\tacceptedByUserId: row.accepted_by_user_id ?? undefined\n\t};\n}\n\nfunction inviteToRow(i: Invite): InviteRow {\n\treturn {\n\t\tid: i.id,\n\t\ttoken_hash: i.tokenHash,\n\t\temail: i.email,\n\t\torg_id: i.orgId,\n\t\torg_role: i.orgRole,\n\t\torg_permissions: i.orgPermissions,\n\t\tplatform_permissions: i.platformPermissions ?? [],\n\t\tinvited_by: i.invitedBy,\n\t\tcreated_at: i.createdAt,\n\t\texpires_at: i.expiresAt,\n\t\taccepted_at: i.acceptedAt ?? null,\n\t\taccepted_by_user_id: i.acceptedByUserId ?? null\n\t};\n}\n","import {\n\tisOrgServer,\n\tisPlatformServer,\n\tscopeConfigToOrg,\n\ttype IComputeServerStore,\n\ttype ComputeConfig,\n\ttype ComputeServerConfig,\n\ttype GetConfigOptions,\n\ttype RequestContext,\n\ttype SecretVerificationFailure,\n\ttype SecretVerificationReport,\n\ttype ILogger\n} from '@selvajs/platform';\nimport { NoopLogger } from '@selvajs/platform';\n// `node:crypto`-based, so it's a server-only subpath, not the root barrel.\nimport {\n\tdecryptWithKeys,\n\tencryptSecret,\n\tisEncryptedSecret,\n\tisLegacyEnvelope,\n\tisUnknownEnvelope,\n\ttype SecretBinding\n} from '@selvajs/platform/computeServer';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\n\n// Sessions have no SELECT on `api_key`, so this list is all a session can read.\n// Keys come from `readApiKeys`, after RLS has said which servers the caller sees.\nconst SERVER_COLUMNS = 'id, scope, owner_org_id, shared_with_all, label, server_url, has_api_key';\nconst SHARE_COLUMNS = 'server_id, org_id';\nconst ORG_DEFAULT_COLUMNS = 'org_id, default_server_id';\n\n/** The columns a key read needs: `server_url` is half the key's binding. */\ntype KeyRow = Pick<ServerRow, 'id' | 'label' | 'server_url' | 'api_key'>;\n\nconst bindingOf = (row: KeyRow): SecretBinding => ({ id: row.id, url: row.server_url });\n\n/**\n * Compute-server config backed by three tables:\n * - `compute_servers`: one row per server. `scope = 'platform' | 'org'`.\n * Platform rows carry a `shared_with_all` flag + `compute_server_shares`\n * allowlist; org rows carry `owner_org_id`.\n * - `compute_server_shares`: many-to-many for platform servers shared\n * with specific orgs (when `shared_with_all = false`).\n * - `compute_server_org_defaults`: per-org `orgDefaults[orgId]` choice.\n * - `compute_server_platform_default`: single-row sentinel for the global\n * `defaultServerId`.\n *\n * `getConfig` returns the full doc; the visibility predicate is applied by\n * callers (resolver, page loaders) using helpers in `@selvajs/platform`.\n */\nexport class SupabaseComputeServerStore implements IComputeServerStore {\n\t/**\n\t * `secretKey` (from `SELVA_AT_REST_KEY`) encrypts/decrypts `compute_servers.api_key`\n\t * so the Rhino.Compute credential never sits in the DB as plaintext. Optional\n\t * only for construction paths that never touch apiKeys — a store built\n\t * without a key throws if asked to write or read a secret.\n\t */\n\tprivate readonly logger: ILogger;\n\t/** Current key first; the previous one still opens rows sealed before a rotation. */\n\tprivate readonly keys: Buffer[];\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tprivate readonly secretKey?: Buffer,\n\t\tlogger?: ILogger,\n\t\tpreviousKey?: Buffer\n\t) {\n\t\tthis.logger = logger ?? new NoopLogger();\n\t\tthis.keys = secretKey ? (previousKey ? [secretKey, previousKey] : [secretKey]) : [];\n\t}\n\n\tasync getConfig(ctx: RequestContext, opts: GetConfigOptions = {}): Promise<ComputeConfig> {\n\t\tconst client = this.clients.forRequest(ctx);\n\t\tconst withKeys = opts.includeApiKeys === true;\n\n\t\tconst [serversRes, sharesRes, orgDefRes, platDefRes] = await Promise.all([\n\t\t\tclient.from('compute_servers').select(SERVER_COLUMNS),\n\t\t\tclient.from('compute_server_shares').select(SHARE_COLUMNS),\n\t\t\tclient.from('compute_server_org_defaults').select(ORG_DEFAULT_COLUMNS),\n\t\t\tclient\n\t\t\t\t.from('compute_server_platform_default')\n\t\t\t\t.select('default_server_id')\n\t\t\t\t.eq('singleton', true)\n\t\t\t\t.maybeSingle()\n\t\t]);\n\n\t\tif (serversRes.error) throw mapPostgrestError(serversRes.error);\n\t\tif (sharesRes.error) throw mapPostgrestError(sharesRes.error);\n\t\tif (orgDefRes.error) throw mapPostgrestError(orgDefRes.error);\n\t\tif (platDefRes.error) throw mapPostgrestError(platDefRes.error);\n\n\t\tconst sharedByServer = new Map<string, string[]>();\n\t\tfor (const row of sharesRes.data ?? []) {\n\t\t\tconst list = sharedByServer.get(row.server_id) ?? [];\n\t\t\tlist.push(row.org_id);\n\t\t\tsharedByServer.set(row.server_id, list);\n\t\t}\n\n\t\tconst rows: ServerRow[] = serversRes.data ?? [];\n\t\tconst keyed = withKeys ? await this.withApiKeys(rows) : rows;\n\t\tconst servers = keyed.map((row) => rowToServer(row, sharedByServer, withKeys));\n\n\t\tconst orgDefaults: Record<string, string> = {};\n\t\tfor (const row of orgDefRes.data ?? []) {\n\t\t\tif (row.default_server_id) orgDefaults[row.org_id] = row.default_server_id;\n\t\t}\n\n\t\tconst config: ComputeConfig = {\n\t\t\tservers,\n\t\t\tdefaultServerId: platDefRes.data?.default_server_id ?? undefined,\n\t\t\torgDefaults\n\t\t};\n\t\treturn opts.scopeToOrgId ? scopeConfigToOrg(config, opts.scopeToOrgId) : config;\n\t}\n\n\t/**\n\t * The solve path's entry point: one row lookup + one decrypt instead of\n\t * `getConfig`'s whole-table read. An unknown id or unreadable ciphertext\n\t * yields `undefined` rather than throwing.\n\t */\n\tasync getServerApiKey(ctx: RequestContext, serverId: string): Promise<string | undefined> {\n\t\tconst { data: visible, error: visibleError } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('compute_servers')\n\t\t\t.select('id')\n\t\t\t.eq('id', serverId)\n\t\t\t.maybeSingle();\n\t\tif (visibleError) throw mapPostgrestError(visibleError);\n\t\tif (!visible) return undefined;\n\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('compute_servers')\n\t\t\t.select('id, label, server_url, api_key')\n\t\t\t.eq('id', serverId)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data) return undefined;\n\t\treturn this.decryptRowApiKey(data as KeyRow).api_key ?? undefined;\n\t}\n\n\t/** `rows` must come from a session read: this reaches keys with the service role. */\n\tprivate async withApiKeys(rows: ServerRow[]): Promise<ServerRow[]> {\n\t\tif (rows.length === 0) return rows;\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('compute_servers')\n\t\t\t.select('id, label, api_key')\n\t\t\t.in(\n\t\t\t\t'id',\n\t\t\t\trows.map((r) => r.id)\n\t\t\t);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst keys = new Map((data ?? []).map((r) => [r.id as string, r.api_key as string | null]));\n\t\treturn rows.map((row) => this.decryptRowApiKey({ ...row, api_key: keys.get(row.id) ?? null }));\n\t}\n\n\tasync savePlatformServers(\n\t\tctx: RequestContext,\n\t\tservers: ComputeServerConfig[],\n\t\tdefaultServerId: string | undefined\n\t): Promise<void> {\n\t\tconst platformOnly = servers.filter(isPlatformServer);\n\t\tconst shares = platformOnly.flatMap((s) =>\n\t\t\ts.sharedWith === 'all'\n\t\t\t\t? []\n\t\t\t\t: s.sharedWith.map((orgId) => ({ server_id: s.id, org_id: orgId }))\n\t\t);\n\t\tconst { error } = await this.clients.serviceClient.rpc('save_platform_compute_servers', {\n\t\t\tservers: platformOnly.map((s) => serverToRow(this.encryptServerApiKey(s))),\n\t\t\tshares,\n\t\t\tdefault_server: defaultServerId ?? null\n\t\t});\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync saveOrgServers(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tservers: ComputeServerConfig[],\n\t\tdefaultServerId?: string | null\n\t): Promise<void> {\n\t\tconst orgOnly = servers.filter(isOrgServer).map((s) => ({ ...s, ownerOrgId: orgId }));\n\t\tconst { error } = await this.clients.serviceClient.rpc('save_org_compute_servers', {\n\t\t\to: orgId,\n\t\t\tservers: orgOnly.map((s) => serverToRow(this.encryptServerApiKey(s))),\n\t\t\tset_default: defaultServerId !== undefined,\n\t\t\tdefault_server: defaultServerId ?? null\n\t\t});\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync setOrgDefault(ctx: RequestContext, orgId: string, serverId: string | null): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tif (serverId === null) {\n\t\t\tconst { error } = await client\n\t\t\t\t.from('compute_server_org_defaults')\n\t\t\t\t.delete()\n\t\t\t\t.eq('org_id', orgId);\n\t\t\tif (error) throw mapPostgrestError(error);\n\t\t\treturn;\n\t\t}\n\t\tconst { error } = await client\n\t\t\t.from('compute_server_org_defaults')\n\t\t\t.upsert({ org_id: orgId, default_server_id: serverId });\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tasync deleteByOrg(ctx: RequestContext, orgId: string): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\n\t\t// Org soft-delete doesn't trigger the FK cascade from orgs(id), so\n\t\t// each dependent table needs an explicit delete here.\n\t\tconst { error: defErr } = await client\n\t\t\t.from('compute_server_org_defaults')\n\t\t\t.delete()\n\t\t\t.eq('org_id', orgId);\n\t\tif (defErr) throw mapPostgrestError(defErr);\n\n\t\tconst { error: srvErr } = await client\n\t\t\t.from('compute_servers')\n\t\t\t.delete()\n\t\t\t.eq('scope', 'org')\n\t\t\t.eq('owner_org_id', orgId);\n\t\tif (srvErr) throw mapPostgrestError(srvErr);\n\n\t\tconst { error: shErr } = await client\n\t\t\t.from('compute_server_shares')\n\t\t\t.delete()\n\t\t\t.eq('org_id', orgId);\n\t\tif (shErr) throw mapPostgrestError(shErr);\n\t}\n\n\t// ==========================================================================\n\t// At-rest secret handling\n\t// ==========================================================================\n\n\t/**\n\t * Encrypt a server's `apiKey` before it is written to the DB, bound to its id\n\t * and URL. Throws on a value that is already an envelope, and if the store was\n\t * built without a key, so we never silently persist plaintext.\n\t */\n\tprivate encryptServerApiKey(s: ComputeServerConfig): ComputeServerConfig {\n\t\tif (!s.apiKey) return s;\n\t\tif (!this.secretKey) {\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot store a compute-server apiKey: SELVA_AT_REST_KEY is not configured. ' +\n\t\t\t\t\t'Set it so secrets are encrypted at rest.'\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\t...s,\n\t\t\tapiKey: encryptSecret(s.apiKey, this.secretKey, { id: s.id, url: s.serverUrl })\n\t\t};\n\t}\n\n\t/**\n\t * Decrypt a row's `api_key` on read. Tolerant, mirroring the local provider:\n\t * a row whose ciphertext can't be authenticated under the current key is\n\t * returned with `api_key: null` and a warning logged, so the page keeps\n\t * rendering (solves against that server fail later at Rhino.Compute). A\n\t * plaintext value that predates encryption is passed through unchanged and\n\t * surfaced by `verifySecrets()` — never silently dropped.\n\t */\n\tprivate decryptRowApiKey<R extends KeyRow>(row: R): R {\n\t\tif (!row.api_key) return row;\n\t\tif (isUnknownEnvelope(row.api_key)) {\n\t\t\tthis.logger.warn(\n\t\t\t\t`Could not read api_key: it is sealed as ${row.api_key.slice(0, 6)}, a format this Selva version does not know. ` +\n\t\t\t\t\t'A newer version wrote it. This server is returned without an apiKey and solves against it will fail. ' +\n\t\t\t\t\t'Upgrade Selva again, or re-enter the key via /admin/compute',\n\t\t\t\t{ component: 'selva', serverLabel: row.label, serverId: row.id }\n\t\t\t);\n\t\t\treturn { ...row, api_key: null };\n\t\t}\n\t\tif (!isEncryptedSecret(row.api_key)) {\n\t\t\tthis.logger.warn(\n\t\t\t\t'Compute server row has a plaintext api_key; re-save it via /admin/compute so it is stored encrypted',\n\t\t\t\t{ component: 'selva', serverLabel: row.label, serverId: row.id }\n\t\t\t);\n\t\t\treturn row;\n\t\t}\n\t\tif (!this.secretKey) {\n\t\t\tthis.logger.warn(\n\t\t\t\t'Cannot decrypt api_key: SELVA_AT_REST_KEY is not configured. Returning without a key; solves will fail',\n\t\t\t\t{ component: 'selva', serverLabel: row.label, serverId: row.id }\n\t\t\t);\n\t\t\treturn { ...row, api_key: null };\n\t\t}\n\t\ttry {\n\t\t\treturn { ...row, api_key: decryptWithKeys(row.api_key, this.keys, bindingOf(row)).plaintext };\n\t\t} catch (cause) {\n\t\t\tthis.logger.warn(\n\t\t\t\t'Could not decrypt api_key: the stored ciphertext does not match the current SELVA_AT_REST_KEY. ' +\n\t\t\t\t\t'This server is returned without an apiKey and solves against it will fail. ' +\n\t\t\t\t\t'Re-enter the key via /admin/compute, or restore the original SELVA_AT_REST_KEY',\n\t\t\t\t{\n\t\t\t\t\tcomponent: 'selva',\n\t\t\t\t\tserverLabel: row.label,\n\t\t\t\t\tserverId: row.id,\n\t\t\t\t\terr: cause instanceof Error ? (cause.stack ?? cause.message) : String(cause)\n\t\t\t\t}\n\t\t\t);\n\t\t\treturn { ...row, api_key: null };\n\t\t}\n\t}\n\n\t/**\n\t * Boot-time integrity check over every `compute_servers` row. Uses the\n\t * service client (no request context at boot) to read raw ciphertext, then\n\t * attempts to decrypt each `api_key`. Does NOT throw — returns a structured\n\t * report for boot health to drive `/api/health`.\n\t */\n\tasync verifySecrets(): Promise<SecretVerificationReport> {\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('compute_servers')\n\t\t\t.select('id, label, server_url, api_key');\n\t\tif (error) throw mapPostgrestError(error);\n\n\t\tconst failures: SecretVerificationFailure[] = [];\n\t\tlet plaintextFound = false;\n\t\tlet onPreviousKey = 0;\n\t\tlet legacyEnvelopes = 0;\n\n\t\tfor (const row of (data ?? []) as KeyRow[]) {\n\t\t\tconst { api_key: apiKey, id, label } = row;\n\t\t\tif (!apiKey) continue;\n\t\t\tif (isUnknownEnvelope(apiKey)) {\n\t\t\t\tfailures.push({ serverId: id, serverLabel: label, reason: 'unknown_envelope' });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isEncryptedSecret(apiKey)) {\n\t\t\t\tplaintextFound = true;\n\t\t\t\tfailures.push({ serverId: id, serverLabel: label, reason: 'plaintext_on_disk' });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!this.secretKey) {\n\t\t\t\tfailures.push({\n\t\t\t\t\tserverId: id,\n\t\t\t\t\tserverLabel: label,\n\t\t\t\t\treason: 'key_mismatch',\n\t\t\t\t\tcause: 'SELVA_AT_REST_KEY is not configured'\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isLegacyEnvelope(apiKey)) legacyEnvelopes += 1;\n\t\t\ttry {\n\t\t\t\tif (decryptWithKeys(apiKey, this.keys, bindingOf(row)).keyIndex > 0) onPreviousKey += 1;\n\t\t\t} catch (cause) {\n\t\t\t\tfailures.push({\n\t\t\t\t\tserverId: id,\n\t\t\t\t\tserverLabel: label,\n\t\t\t\t\treason: 'key_mismatch',\n\t\t\t\t\tcause: cause instanceof Error ? cause.message : String(cause)\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tok: failures.length === 0,\n\t\t\tfailures,\n\t\t\tplaintextFound,\n\t\t\t...(this.keys.length > 1 ? { onPreviousKey } : {}),\n\t\t\t...(legacyEnvelopes > 0 ? { legacyEnvelopes } : {})\n\t\t};\n\t}\n\n\t/**\n\t * Re-seal, under the current key and the row's binding, every row only the\n\t * previous key opens or that sits in a legacy envelope. The update matches on\n\t * the old ciphertext and URL too, so a row an admin re-saved in between is\n\t * left alone rather than overwritten.\n\t */\n\tasync reencryptSecrets(): Promise<number> {\n\t\tif (!this.secretKey) return 0;\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('compute_servers')\n\t\t\t.select('id, label, server_url, api_key');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tlet changed = 0;\n\t\tfor (const row of (data ?? []) as KeyRow[]) {\n\t\t\tif (!row.api_key || !isEncryptedSecret(row.api_key)) continue;\n\t\t\tlet opened: { plaintext: string; keyIndex: number };\n\t\t\ttry {\n\t\t\t\topened = decryptWithKeys(row.api_key, this.keys, bindingOf(row));\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (opened.keyIndex === 0 && !isLegacyEnvelope(row.api_key)) continue;\n\t\t\tconst { error: updateError, count } = await this.clients.serviceClient\n\t\t\t\t.from('compute_servers')\n\t\t\t\t.update(\n\t\t\t\t\t{ api_key: encryptSecret(opened.plaintext, this.secretKey, bindingOf(row)) },\n\t\t\t\t\t{ count: 'exact' }\n\t\t\t\t)\n\t\t\t\t.eq('id', row.id)\n\t\t\t\t.eq('server_url', row.server_url)\n\t\t\t\t.eq('api_key', row.api_key);\n\t\t\tif (updateError) throw mapPostgrestError(updateError);\n\t\t\tchanged += count ?? 0;\n\t\t}\n\t\treturn changed;\n\t}\n}\n\ninterface ServerRow {\n\tid: string;\n\tscope: 'platform' | 'org';\n\towner_org_id: string | null;\n\tshared_with_all: boolean;\n\tlabel: string;\n\tserver_url: string;\n\t/** Absent unless the row went through `withApiKeys`. */\n\tapi_key?: string | null;\n\t/** Generated column — true when a key is stored, without reading it. */\n\thas_api_key?: boolean;\n}\n\n/**\n * `withKey` mirrors the projection the row was read with. It gates `apiKey`\n * explicitly rather than trusting the row's shape, so a key can never ride along\n * on a read that didn't ask for one.\n */\nfunction rowToServer(\n\trow: ServerRow,\n\tsharedByServer: Map<string, string[]>,\n\twithKey: boolean\n): ComputeServerConfig {\n\tconst common = {\n\t\tid: row.id,\n\t\tlabel: row.label,\n\t\tserverUrl: row.server_url,\n\t\tapiKey: withKey ? (row.api_key ?? undefined) : undefined,\n\t\thasApiKey: row.has_api_key ?? !!row.api_key\n\t};\n\tif (row.scope === 'platform') {\n\t\treturn {\n\t\t\t...common,\n\t\t\tscope: 'platform',\n\t\t\tsharedWith: row.shared_with_all ? 'all' : (sharedByServer.get(row.id) ?? [])\n\t\t};\n\t}\n\tif (!row.owner_org_id) {\n\t\tthrow new Error(`compute_servers row ${row.id} has scope='org' but null owner_org_id`);\n\t}\n\treturn { ...common, scope: 'org', ownerOrgId: row.owner_org_id };\n}\n\n/**\n * Insert shape. Deliberately not `ServerRow`: `has_api_key` is generated by the\n * database and rejected on write, so the writable columns are their own type.\n */\ntype ServerWriteRow = Omit<ServerRow, 'has_api_key'>;\n\nfunction serverToRow(s: ComputeServerConfig): ServerWriteRow {\n\tconst base = {\n\t\tid: s.id,\n\t\tlabel: s.label,\n\t\tserver_url: s.serverUrl,\n\t\tapi_key: s.apiKey ?? null\n\t};\n\tif (isPlatformServer(s)) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tscope: 'platform',\n\t\t\towner_org_id: null,\n\t\t\tshared_with_all: s.sharedWith === 'all'\n\t\t};\n\t}\n\treturn {\n\t\t...base,\n\t\tscope: 'org',\n\t\towner_org_id: s.ownerOrgId,\n\t\tshared_with_all: false\n\t};\n}\n","import type {\n\tIShareLinkStore,\n\tIEventSink,\n\tOrgShareLink,\n\tShareLink,\n\tRequestContext,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport { actorOf, NoopEventSink, ProviderError } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, toRange } from './pagination.js';\n\n/** Explicit column list for `share_links` — every field `rowToLink` consumes. */\nconst SHARE_LINK_COLUMNS =\n\t'id, definition_guid, channel, token_hash, name, created_by, created_at, expires_at, revoked_at, allow_solve, max_solves, solve_count';\n\n/**\n * Share-link store backed by Postgres.\n *\n * `getByTokenHash` and `tryIncrementSolveCount` go through the service-role\n * client and a SECURITY DEFINER RPC, bypassing RLS: the token itself is the\n * credential, not the authenticated user's identity.\n *\n * Reads filter `revoked_at` AND `expires_at` — a dead link must read dead\n * through the store, not only wherever a route remembers to re-check the date.\n * `try_increment_share_link_solve_count` already enforces both server-side.\n */\nexport class SupabaseShareLinkStore implements IShareLinkStore {\n\tprivate readonly events: IEventSink;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tevents: IEventSink = new NoopEventSink()\n\t) {\n\t\tthis.events = events;\n\t}\n\n\tasync create(ctx: RequestContext, link: ShareLink): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient.from('share_links').insert(linkToRow(link));\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'share_link.minted',\n\t\t\tlinkId: link.id,\n\t\t\tdefinitionId: link.definitionId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync listByDefinition(\n\t\tctx: RequestContext,\n\t\tdefinitionId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<ShareLink>> {\n\t\tconst range = toRange(opts);\n\t\tconst { data, error, count } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('share_links')\n\t\t\t.select(SHARE_LINK_COLUMNS, { count: 'exact' })\n\t\t\t.eq('definition_guid', definitionId)\n\t\t\t.is('revoked_at', null)\n\t\t\t.or(`expires_at.is.null,expires_at.gt.${new Date().toISOString()}`)\n\t\t\t.order('created_at', { ascending: false })\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = (data ?? []).map(rowToLink);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync listByOrg(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions\n\t): Promise<Page<OrgShareLink>> {\n\t\t// An RPC because `definitions` and `projects` RLS would hide private projects\n\t\t// from the leadership reading this, and those are the links offboarding needs.\n\t\tconst range = toRange(opts);\n\t\tconst { data, error } = await this.clients.forRequest(ctx).rpc('org_share_link_roster', {\n\t\t\to: orgId,\n\t\t\tpage_limit: range.limit,\n\t\t\tpage_offset: range.from\n\t\t});\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst rows = (data ?? []) as OrgShareLinkRow[];\n\t\tconst nextCursor = nextCursorFromRange(range, rows.length, rows[0]?.total_count ?? 0);\n\t\treturn { items: rows.map(rowToOrgLink), nextCursor };\n\t}\n\n\tasync getById(ctx: RequestContext, id: string): Promise<ShareLink | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('share_links')\n\t\t\t.select(SHARE_LINK_COLUMNS)\n\t\t\t.eq('id', id)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToLink(data) : null;\n\t}\n\n\tasync getByTokenHash(_ctx: RequestContext, tokenHash: string): Promise<ShareLink | null> {\n\t\t// Service-role: RLS would scope this to \"links the current user can see\",\n\t\t// but an anonymous caller resolving a token has no user to scope to.\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('share_links')\n\t\t\t.select(`${SHARE_LINK_COLUMNS}, definitions!inner(deleted_at)`)\n\t\t\t.eq('token_hash', tokenHash)\n\t\t\t.is('revoked_at', null)\n\t\t\t.or(`expires_at.is.null,expires_at.gt.${new Date().toISOString()}`)\n\t\t\t.is('definitions.deleted_at', null)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToLink(data) : null;\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst { data, error } = await client\n\t\t\t.from('share_links')\n\t\t\t.update({ revoked_at: new Date().toISOString() })\n\t\t\t.eq('id', id)\n\t\t\t.is('revoked_at', null)\n\t\t\t.select('id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tif (!data || data.length === 0) {\n\t\t\t// No rows means already revoked, which is fine, or no such link.\n\t\t\tconst { data: existing, error: readError } = await client\n\t\t\t\t.from('share_links')\n\t\t\t\t.select('revoked_at')\n\t\t\t\t.eq('id', id)\n\t\t\t\t.maybeSingle();\n\t\t\tif (readError) throw mapPostgrestError(readError);\n\t\t\tif (!existing) throw new ProviderError(`Share link '${id}' not found`, 404);\n\t\t\treturn;\n\t\t}\n\t\tawait this.events.emit({ type: 'share_link.revoked', linkId: id, ...actorOf(ctx) });\n\t}\n\n\tasync tryIncrementSolveCount(_ctx: RequestContext, id: string): Promise<number | null> {\n\t\t// Atomic check-and-increment in one RPC call: returns null if the link is\n\t\t// missing/revoked/expired/capped or its definition is soft-deleted, so\n\t\t// concurrent solves can't overshoot max_solves.\n\t\tconst { data, error } = await this.clients.serviceClient.rpc(\n\t\t\t'try_increment_share_link_solve_count',\n\t\t\t{ link_id: id }\n\t\t);\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn typeof data === 'number' ? data : null;\n\t}\n}\n\n// ============================================================================\n// Row ↔ domain mappers\n// ============================================================================\ninterface ShareLinkRow {\n\tid: string;\n\tdefinition_guid: string;\n\tchannel: 'live' | 'draft';\n\ttoken_hash: string;\n\tname: string | null;\n\tcreated_by: string;\n\tcreated_at: string;\n\texpires_at: string | null;\n\trevoked_at: string | null;\n\tallow_solve: boolean;\n\tmax_solves: number | null;\n\tsolve_count: number;\n}\n\n/** A row of the `org_share_link_roster` RPC. */\ninterface OrgShareLinkRow extends ShareLinkRow {\n\tdefinition_name: string;\n\tproject_id: string;\n\tproject_name: string;\n\ttotal_count: number;\n}\n\nfunction rowToOrgLink(row: OrgShareLinkRow): OrgShareLink {\n\t// `tokenHash` is dropped rather than carried: this row is built for a page\n\t// spanning every definition in the tenant.\n\tconst { tokenHash: _tokenHash, ...rest } = rowToLink(row);\n\treturn {\n\t\t...rest,\n\t\tdefinitionName: row.definition_name,\n\t\tprojectId: row.project_id,\n\t\tprojectName: row.project_name\n\t};\n}\n\nfunction rowToLink(row: ShareLinkRow): ShareLink {\n\treturn {\n\t\tid: row.id,\n\t\tdefinitionId: row.definition_guid,\n\t\tchannel: row.channel,\n\t\ttokenHash: row.token_hash,\n\t\tname: row.name ?? undefined,\n\t\tcreatedBy: row.created_by,\n\t\tcreatedAt: row.created_at,\n\t\texpiresAt: row.expires_at,\n\t\trevokedAt: row.revoked_at,\n\t\tallowSolve: row.allow_solve,\n\t\tmaxSolves: row.max_solves,\n\t\tsolveCount: row.solve_count\n\t};\n}\n\nfunction linkToRow(l: ShareLink): Record<string, unknown> {\n\treturn {\n\t\tid: l.id,\n\t\tdefinition_guid: l.definitionId,\n\t\tchannel: l.channel,\n\t\ttoken_hash: l.tokenHash,\n\t\tname: l.name ?? null,\n\t\tcreated_by: l.createdBy,\n\t\tcreated_at: l.createdAt,\n\t\texpires_at: l.expiresAt ?? null,\n\t\trevoked_at: l.revokedAt ?? null,\n\t\tallow_solve: l.allowSolve,\n\t\tmax_solves: l.maxSolves ?? null,\n\t\tsolve_count: l.solveCount\n\t};\n}\n","import type {\n\tApiToken,\n\tApiTokenRevokeReason,\n\tApiTokenSummary,\n\tIApiTokenStore,\n\tIEventSink,\n\tListOptions,\n\tPage,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopEventSink, actorOf } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\nimport { mapPostgrestError } from './errors.js';\nimport { nextCursorFromRange, toRange } from './pagination.js';\n\n/** Every column a session may read: the hash is granted to service role only. */\nconst SUMMARY_COLUMNS =\n\t'id, user_id, created_by, org_id, name, scopes, created_at, expires_at, last_used_at, revoked_at';\n\n/**\n * API token store. `getByTokenHash` and `touchLastUsed` are called with\n * `SYSTEM_CONTEXT`, so they run as service role. Every other call runs under\n * the caller's session, and RLS limits it to their own keys plus, for\n * `manage_org_members`, the org's roster.\n */\nexport class SupabaseApiTokenStore implements IApiTokenStore {\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tprivate readonly events: IEventSink = new NoopEventSink()\n\t) {}\n\n\tasync create(ctx: RequestContext, token: ApiToken): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient.from('api_tokens').insert(tokenToRow(token));\n\t\tif (error) throw mapPostgrestError(error);\n\t\tawait this.events.emit({\n\t\t\ttype: 'api_token.created',\n\t\t\tapiTokenId: token.id,\n\t\t\torgId: token.orgId,\n\t\t\tuserId: token.userId,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n\n\tasync getByTokenHash(ctx: RequestContext, tokenHash: string): Promise<ApiToken | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('api_tokens')\n\t\t\t.select(`${SUMMARY_COLUMNS}, token_hash`)\n\t\t\t.eq('token_hash', tokenHash)\n\t\t\t.is('revoked_at', null)\n\t\t\t.gt('expires_at', new Date().toISOString())\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToToken(data as ApiTokenRow) : null;\n\t}\n\n\tasync get(ctx: RequestContext, id: string): Promise<ApiTokenSummary | null> {\n\t\tconst { data, error } = await this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('api_tokens')\n\t\t\t.select(SUMMARY_COLUMNS)\n\t\t\t.eq('id', id)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapPostgrestError(error);\n\t\treturn data ? rowToSummary(data as SummaryRow) : null;\n\t}\n\n\tasync listByOrg(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\topts?: ListOptions & { userId?: string }\n\t): Promise<Page<ApiTokenSummary>> {\n\t\tconst range = toRange(opts);\n\t\tlet query = this.clients\n\t\t\t.forRequest(ctx)\n\t\t\t.from('api_tokens')\n\t\t\t.select(SUMMARY_COLUMNS, { count: 'exact' })\n\t\t\t.eq('org_id', orgId);\n\t\tif (opts?.userId) query = query.eq('user_id', opts.userId);\n\t\tconst { data, error, count } = await query\n\t\t\t.order('created_at', { ascending: (opts?.orderDir ?? 'desc') === 'asc' })\n\t\t\t.order('id')\n\t\t\t.range(range.from, range.to);\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst items = ((data ?? []) as SummaryRow[]).map(rowToSummary);\n\t\treturn { items, nextCursor: nextCursorFromRange(range, items.length, count) };\n\t}\n\n\tasync revoke(ctx: RequestContext, id: string, reason: ApiTokenRevokeReason): Promise<void> {\n\t\t// `.is('revoked_at', null)` keeps the first revocation time and makes a repeat a no-op.\n\t\tconst { data, error } = await this.clients.serviceClient\n\t\t\t.from('api_tokens')\n\t\t\t.update({ revoked_at: new Date().toISOString() })\n\t\t\t.eq('id', id)\n\t\t\t.is('revoked_at', null)\n\t\t\t.select('id, org_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tfor (const row of (data ?? []) as RevokedRow[]) await this.emitRevoked(ctx, row, reason);\n\t}\n\n\tasync revokeAllForUser(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\topts: { orgId?: string; reason: ApiTokenRevokeReason }\n\t): Promise<string[]> {\n\t\tlet query = this.clients.serviceClient\n\t\t\t.from('api_tokens')\n\t\t\t.update({ revoked_at: new Date().toISOString() })\n\t\t\t.eq('user_id', userId)\n\t\t\t.is('revoked_at', null);\n\t\tif (opts.orgId) query = query.eq('org_id', opts.orgId);\n\t\tconst { data, error } = await query.select('id, org_id');\n\t\tif (error) throw mapPostgrestError(error);\n\t\tconst rows = (data ?? []) as RevokedRow[];\n\t\tfor (const row of rows) await this.emitRevoked(ctx, row, opts.reason);\n\t\treturn rows.map((r) => r.id);\n\t}\n\n\tasync touchLastUsed(ctx: RequestContext, id: string, at: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('api_tokens')\n\t\t\t.update({ last_used_at: at })\n\t\t\t.eq('id', id);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\t/**\n\t * Deleting the auth user does this through the FKs already. This covers a\n\t * caller erasing the rows before (or without) deleting the identity.\n\t */\n\tasync eraseUser(_ctx: RequestContext, userId: string): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst deleted = await client.from('api_tokens').delete().eq('user_id', userId);\n\t\tif (deleted.error) throw mapPostgrestError(deleted.error);\n\t\tconst cleared = await client\n\t\t\t.from('api_tokens')\n\t\t\t.update({ created_by: null })\n\t\t\t.eq('created_by', userId);\n\t\tif (cleared.error) throw mapPostgrestError(cleared.error);\n\t}\n\n\tasync deleteByOrg(ctx: RequestContext, orgId: string): Promise<void> {\n\t\tconst { error } = await this.clients.serviceClient\n\t\t\t.from('api_tokens')\n\t\t\t.delete()\n\t\t\t.eq('org_id', orgId);\n\t\tif (error) throw mapPostgrestError(error);\n\t}\n\n\tprivate emitRevoked(\n\t\tctx: RequestContext,\n\t\trow: RevokedRow,\n\t\treason: ApiTokenRevokeReason\n\t): Promise<void> {\n\t\treturn this.events.emit({\n\t\t\ttype: 'api_token.revoked',\n\t\t\tapiTokenId: row.id,\n\t\t\torgId: row.org_id,\n\t\t\treason,\n\t\t\t...actorOf(ctx)\n\t\t});\n\t}\n}\n\ninterface SummaryRow {\n\tid: string;\n\tuser_id: string;\n\tcreated_by: string | null;\n\torg_id: string;\n\tname: string;\n\tscopes: string[];\n\tcreated_at: string;\n\texpires_at: string;\n\tlast_used_at: string | null;\n\trevoked_at: string | null;\n}\n\ninterface ApiTokenRow extends SummaryRow {\n\ttoken_hash: string;\n}\n\ninterface RevokedRow {\n\tid: string;\n\torg_id: string;\n}\n\nfunction rowToSummary(row: SummaryRow): ApiTokenSummary {\n\treturn {\n\t\tid: row.id,\n\t\tuserId: row.user_id,\n\t\tcreatedBy: row.created_by,\n\t\torgId: row.org_id,\n\t\tname: row.name,\n\t\tscopes: row.scopes,\n\t\tcreatedAt: row.created_at,\n\t\texpiresAt: row.expires_at,\n\t\tlastUsedAt: row.last_used_at,\n\t\trevokedAt: row.revoked_at\n\t};\n}\n\nfunction rowToToken(row: ApiTokenRow): ApiToken {\n\treturn { ...rowToSummary(row), tokenHash: row.token_hash };\n}\n\nfunction tokenToRow(t: ApiToken): ApiTokenRow {\n\treturn {\n\t\tid: t.id,\n\t\tuser_id: t.userId,\n\t\tcreated_by: t.createdBy,\n\t\torg_id: t.orgId,\n\t\tname: t.name,\n\t\ttoken_hash: t.tokenHash,\n\t\tscopes: t.scopes,\n\t\tcreated_at: t.createdAt,\n\t\texpires_at: t.expiresAt,\n\t\tlast_used_at: t.lastUsedAt,\n\t\trevoked_at: t.revokedAt\n\t};\n}\n","/**\n * Timestamp prefix of the newest file in `supabase/migrations/`. Bump this\n * whenever a migration is added — `migration-head.test.ts` asserts it\n * matches the migrations directory, so CI catches drift.\n */\nexport const EXPECTED_MIGRATION_HEAD = '20261120150000';\n\n/**\n * The oldest head this build runs on; the handshake fails below it. Behind\n * {@link EXPECTED_MIGRATION_HEAD} only while a migration has to land after the\n * app: `20261113120000` takes every write away from sessions, which an older\n * build still writes with, so the app updates first and `db push` follows.\n * Raise it to the newest head once nothing needs that order.\n */\nexport const REQUIRED_MIGRATION_HEAD = '20261108140000';\n","import { createClient, type SupabaseClient } from '@supabase/supabase-js';\nimport type { RequestContext } from '@selvajs/platform';\n\n/**\n * supabase-js surfaces the schema as a type generic, and the bare\n * `SupabaseClient` default is pinned to `'public'` — this alias is what a\n * client with `db: { schema: 'selva' }` actually type-checks as.\n */\nexport type SelvaSchemaClient = SupabaseClient<any, 'public', 'selva'>;\n\n/** Default schema every engine store targets. */\nexport const DEFAULT_SCHEMA = 'selva' as const;\n\n/** A client pinned to a caller-chosen schema (opaque generic for non-`'selva'` schemas). */\nexport type SchemaClient = SupabaseClient<any, string, any>;\n\nexport interface ForRequestOptions {\n\t/** Postgres schema this client targets. Defaults to `'selva'`. */\n\tschema?: string;\n}\n\n/**\n * `forRequest` picks one of three fail-closed modes:\n * - `ctx.system === true` → service-role, bypasses RLS. Never derive this\n * flag from a user session — it must come from an explicitly-trusted\n * server flow (admin paths, janitors, bootstrap).\n * - `ctx.adapterContext.sessionToken` set → user-scoped, `authenticated`\n * role, RLS enforces per-user visibility via `auth.uid()`.\n * - neither → anon role, RLS active, no `auth.uid()`. This is the safety\n * net: a context built without a forwarded session token and without\n * `system: true` is untrusted by default.\n *\n * An earlier version fell back to service-role when the session token was\n * missing — fail-OPEN, so a synthetic ctx (e.g. share-token resolve) could\n * silently bypass RLS. Opt into service-role explicitly now, or you get RLS.\n *\n * `forRequest` caches per `(RequestContext, schema)` in a WeakMap so\n * multiple store calls in one HTTP handler share a client — and its fetch\n * connection — without leaking auth across requests.\n */\nexport interface ClientBundle {\n\t/**\n\t * Long-lived service-role client, pinned to the `'selva'` schema. Bypasses RLS.\n\t * Every write to `selva` goes through it: `anon` and `authenticated` hold\n\t * SELECT only, so the caller's own client cannot write.\n\t */\n\tserviceClient: SelvaSchemaClient;\n\t/** The caller's client, for reads: RLS decides what comes back. */\n\tforRequest(ctx: RequestContext, opts?: ForRequestOptions): SchemaClient;\n}\n\nexport interface BuildClientOptions {\n\tsupabaseUrl: string;\n\tanonKey: string;\n\tserviceRoleKey: string;\n}\n\nexport function buildClientBundle(opts: BuildClientOptions): ClientBundle {\n\t// Stateless w.r.t. request identity, so one instance per schema is safe to share.\n\tconst serviceBySchema = new Map<string, SchemaClient>();\n\tconst anonBySchema = new Map<string, SchemaClient>();\n\n\tfunction serviceFor(schema: string): SchemaClient {\n\t\tlet client = serviceBySchema.get(schema);\n\t\tif (!client) {\n\t\t\tclient = createClient(opts.supabaseUrl, opts.serviceRoleKey, {\n\t\t\t\tdb: { schema },\n\t\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t\t});\n\t\t\tserviceBySchema.set(schema, client);\n\t\t}\n\t\treturn client;\n\t}\n\n\tfunction anonFor(schema: string): SchemaClient {\n\t\tlet client = anonBySchema.get(schema);\n\t\tif (!client) {\n\t\t\tclient = createClient(opts.supabaseUrl, opts.anonKey, {\n\t\t\t\tdb: { schema },\n\t\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t\t});\n\t\t\tanonBySchema.set(schema, client);\n\t\t}\n\t\treturn client;\n\t}\n\n\tconst serviceClient = serviceFor(DEFAULT_SCHEMA) as SelvaSchemaClient;\n\tconst perRequestCache = new WeakMap<RequestContext, Map<string, SchemaClient>>();\n\n\treturn {\n\t\tserviceClient,\n\t\tforRequest(ctx: RequestContext, forOpts?: ForRequestOptions): SchemaClient {\n\t\t\tconst schema = forOpts?.schema ?? DEFAULT_SCHEMA;\n\t\t\tif (ctx.system) return serviceFor(schema);\n\n\t\t\tconst token = extractSessionToken(ctx.adapterContext);\n\t\t\tif (!token) return anonFor(schema);\n\n\t\t\tlet bySchema = perRequestCache.get(ctx);\n\t\t\tif (!bySchema) {\n\t\t\t\tbySchema = new Map();\n\t\t\t\tperRequestCache.set(ctx, bySchema);\n\t\t\t}\n\t\t\tconst cached = bySchema.get(schema);\n\t\t\tif (cached) return cached;\n\n\t\t\tconst client = createClient(opts.supabaseUrl, opts.anonKey, {\n\t\t\t\tdb: { schema },\n\t\t\t\tauth: { persistSession: false, autoRefreshToken: false },\n\t\t\t\tglobal: {\n\t\t\t\t\theaders: { Authorization: `Bearer ${token}` }\n\t\t\t\t}\n\t\t\t});\n\t\t\tbySchema.set(schema, client);\n\t\t\treturn client;\n\t\t}\n\t};\n}\n\n/**\n * Reads only `SUPABASE_URL` / `SUPABASE_ANON_KEY` / `SUPABASE_SERVICE_ROLE_KEY`.\n * Deliberately does not require `SELVA_AT_REST_KEY` — that's only needed for\n * compute-server secret encryption, which an app building its own `'public'`\n * stores never touches. `SupabaseDataProvider.fromEnv` adds that requirement\n * on top.\n */\nexport function clientBundleFromEnv(env: Record<string, string | undefined>): ClientBundle {\n\tconst supabaseUrl = env.SUPABASE_URL;\n\tconst anonKey = env.SUPABASE_ANON_KEY;\n\tconst serviceRoleKey = env.SUPABASE_SERVICE_ROLE_KEY;\n\tif (!supabaseUrl) throw new Error('Missing required env var: SUPABASE_URL');\n\tif (!anonKey) throw new Error('Missing required env var: SUPABASE_ANON_KEY');\n\tif (!serviceRoleKey) throw new Error('Missing required env var: SUPABASE_SERVICE_ROLE_KEY');\n\treturn buildClientBundle({ supabaseUrl, anonKey, serviceRoleKey });\n}\n\nfunction extractSessionToken(adapterContext: unknown): string | undefined {\n\tif (!adapterContext || typeof adapterContext !== 'object') return undefined;\n\tconst maybe = (adapterContext as { sessionToken?: unknown }).sessionToken;\n\treturn typeof maybe === 'string' && maybe.length > 0 ? maybe : undefined;\n}\n","import {\n\tAUDIT_EVENT_VERSION,\n\tNoopLogger,\n\ttype BaseEvent,\n\ttype DomainEvent,\n\ttype IEventSink,\n\ttype ILogger\n} from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\n\n/**\n * Persists every domain event to `public.audit_events`. Writes use the\n * service-role client so RLS does not gate the audit trail — the sink runs\n * as a system process attached to whichever store emitted the event.\n *\n * Per the `IEventSink` contract, `emit` MUST NOT throw. The user-facing\n * mutation has already succeeded by the time we're here; a failed audit\n * write is logged and swallowed so the response still completes.\n */\nexport class SupabaseEventSink<E extends BaseEvent = DomainEvent> implements IEventSink<E> {\n\tprivate readonly logger: ILogger;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\topts: { logger?: ILogger } = {}\n\t) {\n\t\tthis.logger = opts.logger ?? new NoopLogger();\n\t}\n\n\tasync emit(event: E): Promise<void> {\n\t\ttry {\n\t\t\tconst { error } = await this.clients.serviceClient.from('audit_events').insert({\n\t\t\t\ttype: event.type,\n\t\t\t\tactor_id: event.actorId,\n\t\t\t\tevent_version: AUDIT_EVENT_VERSION,\n\t\t\t\tdata: event,\n\t\t\t\t// Only when set, so session traffic still writes against a database\n\t\t\t\t// that predates the column.\n\t\t\t\t...(event.tokenId ? { token_id: event.tokenId } : {})\n\t\t\t});\n\t\t\tif (error) {\n\t\t\t\t// Only the event's identifiers are logged, never the whole event: an\n\t\t\t\t// `invite.created` payload embeds the invitee's email address, and log\n\t\t\t\t// records outlive and out-travel the audit row itself.\n\t\t\t\tthis.logger.error('Audit event insert failed', {\n\t\t\t\t\tcomponent: 'SupabaseEventSink',\n\t\t\t\t\teventType: event.type,\n\t\t\t\t\tactorId: event.actorId,\n\t\t\t\t\terr: error.message\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthis.logger.error('Unexpected error writing audit event', {\n\t\t\t\tcomponent: 'SupabaseEventSink',\n\t\t\t\teventType: event.type,\n\t\t\t\tactorId: event.actorId,\n\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t});\n\t\t}\n\t}\n}\n","import type { ISolveMetricSink, RequestContext, SolveMetric } from '@selvajs/platform';\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\n\ntype MetricRow = {\n\tactor_id: string;\n\tdefinition_url: string;\n\tdefinition_id: string | null;\n\tversion_id: string | null;\n\tchannel: string;\n\torg_id: string | null;\n\tduration_ms: number;\n\tok: boolean;\n\tfailure_kind: string;\n\terror_count: number;\n\twarning_count: number;\n};\n\nexport interface SolveMetricSinkOptions {\n\t/** Flush once this many rows are buffered. */\n\tmaxBatchSize?: number;\n\t/** Flush a non-empty buffer after this many ms, even if under `maxBatchSize`. */\n\tflushIntervalMs?: number;\n\t/**\n\t * Hard cap on rows not yet written, counting batches waiting their turn. Past\n\t * this, the oldest rows are dropped so a stalled or failing backend cannot grow\n\t * memory without bound.\n\t */\n\tmaxBufferSize?: number;\n\t/**\n\t * Structured logger for flush failures and buffer drops. Optional; defaults to\n\t * `NoopLogger` so this library never writes to stdout unless the app wires one.\n\t */\n\tlogger?: ILogger;\n}\n\nconst DEFAULT_MAX_BATCH_SIZE = 100;\nconst DEFAULT_FLUSH_INTERVAL_MS = 2000;\nconst DEFAULT_MAX_BUFFER_SIZE = 10_000;\n\n/**\n * Persists solve timings to `selva.solve_metrics`. Writes go through the\n * service-role client — the sink is a system process attached to the compute\n * route, not the requesting user, so RLS doesn't apply.\n *\n * Rows are buffered and batch-written: slider scrubbing fires solves far\n * faster than they're worth individual round-trips against a Postgres that\n * also serves auth. A batch flushes at `maxBatchSize` rows or `flushIntervalMs`\n * elapsed, whichever comes first.\n *\n * `record` must never throw — it runs on the hot path after the solve\n * response is already sent, so it only buffers; a failed flush is logged and\n * swallowed. That means an unclean shutdown loses buffered metrics; call\n * `close()` to drain deliberately.\n */\nexport class SupabaseSolveMetricSink implements ISolveMetricSink {\n\tprivate buffer: MetricRow[] = [];\n\t/** Claimed batches, oldest first, not counting the one being written. */\n\tprivate queued: MetricRow[][] = [];\n\tprivate timer: ReturnType<typeof setTimeout> | null = null;\n\tprivate draining = false;\n\tprivate drained: Promise<void> = Promise.resolve();\n\tprivate closed = false;\n\n\tprivate readonly maxBatchSize: number;\n\tprivate readonly flushIntervalMs: number;\n\tprivate readonly maxBufferSize: number;\n\tprivate readonly logger: ILogger;\n\n\tconstructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\topts: SolveMetricSinkOptions = {}\n\t) {\n\t\tthis.maxBatchSize = opts.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;\n\t\tthis.flushIntervalMs = opts.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;\n\t\tthis.maxBufferSize = opts.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n\t\tthis.logger = opts.logger ?? new NoopLogger();\n\t}\n\n\tasync record(ctx: RequestContext, metric: SolveMetric): Promise<void> {\n\t\tif (this.closed) return;\n\n\t\tthis.buffer.push({\n\t\t\tactor_id: ctx.userId || 'system',\n\t\t\tdefinition_url: metric.definitionUrl,\n\t\t\tdefinition_id: metric.definitionId,\n\t\t\tversion_id: metric.versionId,\n\t\t\tchannel: metric.channel,\n\t\t\torg_id: metric.orgId,\n\t\t\tduration_ms: metric.durationMs,\n\t\t\tok: metric.ok,\n\t\t\tfailure_kind: metric.failureKind,\n\t\t\terror_count: metric.errorCount,\n\t\t\twarning_count: metric.warningCount\n\t\t});\n\n\t\tthis.enforceCap();\n\n\t\tif (this.buffer.length >= this.maxBatchSize) {\n\t\t\tvoid this.flush();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.scheduleFlush();\n\t}\n\n\t/**\n\t * Writes everything buffered and resolves once the write settles. Serialized\n\t * against any in-flight flush so batches cannot interleave. Never throws.\n\t */\n\tasync flush(): Promise<void> {\n\t\t// Claim the buffered rows synchronously, before yielding — otherwise a\n\t\t// record() landing between here and the write joins a batch already\n\t\t// counted as claimed, and the row is written twice or not at all.\n\t\tif (this.buffer.length > 0) this.queued.push(this.buffer);\n\t\tthis.buffer = [];\n\t\tthis.clearTimer();\n\t\tif (!this.draining) this.drained = this.drain();\n\t\treturn this.drained;\n\t}\n\n\t/** Rows held in memory waiting to be written. */\n\tget pendingRows(): number {\n\t\treturn this.buffer.length + this.queued.reduce((total, batch) => total + batch.length, 0);\n\t}\n\n\tprivate async drain(): Promise<void> {\n\t\tthis.draining = true;\n\t\tfor (let batch = this.queued.shift(); batch; batch = this.queued.shift()) {\n\t\t\tawait this.write(batch);\n\t\t}\n\t\tthis.draining = false;\n\t}\n\n\tprivate enforceCap(): void {\n\t\tconst overflow = this.pendingRows - this.maxBufferSize;\n\t\tif (overflow <= 0) return;\n\t\tlet remaining = overflow;\n\t\twhile (remaining > 0 && this.queued.length > 0) {\n\t\t\tconst oldest = this.queued[0];\n\t\t\tremaining -= oldest.splice(0, remaining).length;\n\t\t\tif (oldest.length === 0) this.queued.shift();\n\t\t}\n\t\tthis.buffer.splice(0, remaining);\n\t\tthis.logger.error('Metric buffer full, dropped oldest metrics', {\n\t\t\tcomponent: 'SupabaseSolveMetricSink',\n\t\t\tdropped: overflow\n\t\t});\n\t}\n\n\t/**\n\t * Stops the timer, drains the buffer, and makes further `record` calls no-ops.\n\t * Call on shutdown so the last partial batch isn't lost.\n\t */\n\tasync close(): Promise<void> {\n\t\tthis.closed = true;\n\t\tthis.clearTimer();\n\t\tawait this.flush();\n\t}\n\n\tprivate scheduleFlush(): void {\n\t\tif (this.timer) return;\n\t\tthis.timer = setTimeout(() => {\n\t\t\tthis.timer = null;\n\t\t\tvoid this.flush();\n\t\t}, this.flushIntervalMs);\n\t\t// Never hold the process open for telemetry.\n\t\tthis.timer.unref?.();\n\t}\n\n\tprivate clearTimer(): void {\n\t\tif (!this.timer) return;\n\t\tclearTimeout(this.timer);\n\t\tthis.timer = null;\n\t}\n\n\tprivate async write(batch: MetricRow[]): Promise<void> {\n\t\ttry {\n\t\t\tconst { error } = await this.clients.serviceClient.from('solve_metrics').insert(batch);\n\t\t\tif (error) {\n\t\t\t\tthis.logger.error('Metric batch insert failed', {\n\t\t\t\t\tcomponent: 'SupabaseSolveMetricSink',\n\t\t\t\t\tcount: batch.length,\n\t\t\t\t\terr: error.message\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthis.logger.error('Unexpected error writing metric batch', {\n\t\t\t\tcomponent: 'SupabaseSolveMetricSink',\n\t\t\t\tcount: batch.length,\n\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t});\n\t\t}\n\t}\n}\n","import type {\n\tAuditEventRow,\n\tAuditQueryFilters,\n\tAuditQueryResult,\n\tBaseEvent,\n\tDomainEvent,\n\tIAuditQuery,\n\tRequestContext\n} from '@selvajs/platform';\nimport { clampPageLimit } from '@selvajs/platform';\nimport type { ClientBundle } from './client.js';\n\nconst ISO_RE = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:?\\d{2})$/;\nconst UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n/**\n * Read-side for `audit_events`. Always uses the service-role client — RLS\n * blocks all reads by design, so the route layer is the sole trust boundary\n * and must gate callers on `instance_admin`.\n *\n * Pagination is keyset on `(occurred_at desc, id desc)`; the `id` tie-breaker\n * prevents skipped rows when multiple events land in the same millisecond.\n */\nexport class SupabaseAuditQuery<E extends BaseEvent = DomainEvent> implements IAuditQuery<E> {\n\tconstructor(private readonly clients: ClientBundle) {}\n\n\tasync list(_ctx: RequestContext, filters: AuditQueryFilters<E>): Promise<AuditQueryResult<E>> {\n\t\tconst limit = clampPageLimit(filters.limit);\n\n\t\tlet q = this.clients.serviceClient\n\t\t\t.from('audit_events')\n\t\t\t.select('id, type, actor_id, occurred_at, data')\n\t\t\t.order('occurred_at', { ascending: false })\n\t\t\t.order('id', { ascending: false })\n\t\t\t.limit(limit + 1); // one extra row to detect \"has more\" without a count query\n\n\t\tif (filters.types && filters.types.length > 0) {\n\t\t\tq = q.in('type', [...filters.types]);\n\t\t}\n\t\tif (filters.actorId) {\n\t\t\tq = q.eq('actor_id', filters.actorId);\n\t\t}\n\t\tif (filters.sinceIso) {\n\t\t\tq = q.gte('occurred_at', filters.sinceIso);\n\t\t}\n\t\tif (filters.untilIso) {\n\t\t\tq = q.lte('occurred_at', filters.untilIso);\n\t\t}\n\t\tif (filters.cursor) {\n\t\t\t// Expresses `(occurred_at, id) < (cursorTs, cursorId)` as a PostgREST\n\t\t\t// `.or()` string: strictly older, or same timestamp with a smaller id.\n\t\t\t// Both values get interpolated into that string, so a malformed cursor\n\t\t\t// could inject arbitrary PostgREST operators — validate shape first.\n\t\t\tconst ts = filters.cursor.occurredAt;\n\t\t\tconst id = filters.cursor.id;\n\t\t\tif (!ISO_RE.test(ts) || !UUID_RE.test(id)) {\n\t\t\t\tthrow new Error('audit_events query: malformed cursor');\n\t\t\t}\n\t\t\tq = q.or(`occurred_at.lt.${ts},and(occurred_at.eq.${ts},id.lt.${id})`);\n\t\t}\n\n\t\tconst { data, error } = await q;\n\t\tif (error) {\n\t\t\tthrow new Error(`audit_events query failed: ${error.message}`);\n\t\t}\n\n\t\tconst fetched = (data ?? []) as Array<{\n\t\t\tid: string;\n\t\t\ttype: string;\n\t\t\tactor_id: string;\n\t\t\toccurred_at: string;\n\t\t\tdata: E;\n\t\t}>;\n\n\t\tconst hasMore = fetched.length > limit;\n\t\tconst page = hasMore ? fetched.slice(0, limit) : fetched;\n\t\tconst last = page[page.length - 1];\n\n\t\treturn {\n\t\t\trows: page.map((r) => ({\n\t\t\t\tid: r.id,\n\t\t\t\ttype: r.type as E['type'],\n\t\t\t\tactorId: r.actor_id,\n\t\t\t\toccurredAt: r.occurred_at,\n\t\t\t\tdata: r.data\n\t\t\t})) satisfies AuditEventRow<E>[],\n\t\t\tnextCursor: hasMore && last ? { occurredAt: last.occurred_at, id: last.id } : null\n\t\t};\n\t}\n}\n","import type {\n\tIUserProfileStore,\n\tRecentRun,\n\tRequestContext,\n\tUserManagementResult,\n\tUserProfile\n} from '@selvajs/platform';\nimport { ProviderError } from '@selvajs/platform';\nimport { assertCanAccessProfile, MAX_RECENT_RUNS } from '@selvajs/platform/userProfile';\nimport type { ClientBundle } from '../data/client.js';\n\n/**\n * Backed by `public.user_profiles` (one row per `auth.users.id`), auto-seeded\n * by the `handle_new_auth_user` trigger on signup — this store never inserts,\n * only reads/updates. Service-role throughout since RLS here is too coarse\n * for server-side flows like the hooks.server.ts profile load; `assertCanAccessProfile`\n * enforces \"own profile only\" at the app layer instead.\n */\n\nexport class SupabaseUserProfileProvider implements IUserProfileStore {\n\tconstructor(private readonly clients: ClientBundle) {}\n\n\tprivate client() {\n\t\treturn this.clients.serviceClient;\n\t}\n\n\tasync getProfile(ctx: RequestContext, userId: string): Promise<UserProfile | null> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id, display_name, starred_definitions, recent_runs')\n\t\t\t.eq('user_id', userId)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapError(error);\n\t\treturn data ? rowToProfile(data) : null;\n\t}\n\n\tasync getProfiles(_ctx: RequestContext, userIds: readonly string[]): Promise<UserProfile[]> {\n\t\t// No assertCanAccessProfile: this serves display-name lookups across other users.\n\t\tif (userIds.length === 0) return [];\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id, display_name, starred_definitions, recent_runs')\n\t\t\t.in('user_id', [...userIds]);\n\t\tif (error) throw mapError(error);\n\t\treturn (data ?? []).map(rowToProfile);\n\t}\n\n\tasync updateProfile(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tpatch: { displayName?: string }\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\tconst row: Record<string, unknown> = {};\n\t\tif (patch.displayName !== undefined) row.display_name = patch.displayName;\n\t\tif (Object.keys(row).length === 0) return 'ok';\n\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.update(row)\n\t\t\t.eq('user_id', userId)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapError(error);\n\t\treturn data && data.length > 0 ? 'ok' : 'not_found';\n\t}\n\n\tasync starDefinition(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tdefinitionId: string\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\t// Read-modify-write races under concurrent starring; a SECURITY DEFINER\n\t\t// RPC using array_append + array_distinct would close it if that matters.\n\t\tconst existing = await this.getProfile(ctx, userId);\n\t\tif (!existing) return 'not_found';\n\t\tif (existing.starredDefinitions.includes(definitionId)) return 'ok';\n\n\t\tconst next = [...existing.starredDefinitions, definitionId];\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.update({ starred_definitions: next })\n\t\t\t.eq('user_id', userId)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapError(error);\n\t\treturn data && data.length > 0 ? 'ok' : 'not_found';\n\t}\n\n\tasync unstarDefinition(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tdefinitionId: string\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\tconst existing = await this.getProfile(ctx, userId);\n\t\tif (!existing) return 'not_found';\n\t\tif (!existing.starredDefinitions.includes(definitionId)) return 'ok';\n\n\t\tconst next = existing.starredDefinitions.filter((id) => id !== definitionId);\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.update({ starred_definitions: next })\n\t\t\t.eq('user_id', userId)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapError(error);\n\t\treturn data && data.length > 0 ? 'ok' : 'not_found';\n\t}\n\n\tasync recordRun(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\trun: RecentRun\n\t): Promise<UserManagementResult> {\n\t\tassertCanAccessProfile(ctx, userId);\n\t\tconst existing = await this.getProfile(ctx, userId);\n\t\tif (!existing) return 'not_found';\n\n\t\tconst filtered = existing.recentRuns.filter((r) => r.definitionId !== run.definitionId);\n\t\tconst next = [run, ...filtered].slice(0, MAX_RECENT_RUNS);\n\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.update({ recent_runs: next })\n\t\t\t.eq('user_id', userId)\n\t\t\t.select('user_id');\n\t\tif (error) throw mapError(error);\n\t\treturn data && data.length > 0 ? 'ok' : 'not_found';\n\t}\n}\n\ninterface ProfileRow {\n\tuser_id: string;\n\tdisplay_name: string | null;\n\tstarred_definitions: string[] | null;\n\trecent_runs: RecentRun[] | null;\n}\n\nfunction rowToProfile(row: ProfileRow): UserProfile {\n\treturn {\n\t\tuserId: row.user_id,\n\t\tdisplayName: row.display_name ?? undefined,\n\t\tstarredDefinitions: row.starred_definitions ?? [],\n\t\trecentRuns: row.recent_runs ?? []\n\t};\n}\n\ninterface PostgrestError {\n\tcode?: string;\n\tmessage?: string;\n}\n\nfunction mapError(e: unknown): Error {\n\tconst pg = e as PostgrestError;\n\tif (pg?.code === '23505') return new ProviderError(pg.message ?? 'Duplicate record', 409);\n\tif (pg?.code === '23503') return new ProviderError(pg.message ?? 'Foreign key violation', 409);\n\tif (e instanceof Error) return e;\n\tif (e && typeof e === 'object') {\n\t\tconst obj = e as { message?: string; code?: string };\n\t\treturn new Error(obj.code ? `[${obj.code}] ${obj.message ?? ''}` : (obj.message ?? String(e)));\n\t}\n\treturn new Error(String(e));\n}\n","import type {\n\tIPlatformPermissionStore,\n\tPlatformPermission,\n\tRequestContext,\n\tUserManagementResult\n} from '@selvajs/platform';\nimport { ProviderError, ALL_PLATFORM_PERMISSIONS } from '@selvajs/platform';\nimport {\n\tassertCanManagePermissions,\n\tassertCanReadPermissions,\n\tassertCanReadPermissionsBatch\n} from '@selvajs/platform/permissions';\nimport type { ClientBundle } from '../data/client.js';\n\n/**\n * Reads and writes `public.user_profiles.platform_permissions` (auto-seeded\n * by the `handle_new_auth_user` trigger). Service-role throughout — RLS on\n * `user_profiles` is too coarse for cross-user reads, so `assertCanManagePermissions` /\n * `assertCanReadPermissions` enforce the auth boundary here instead.\n *\n * `user_profiles.disabled` mirrors the user's ban and `app_metadata.disabled` via\n * the `sync_auth_user_disabled` trigger, so admin-count queries can exclude\n * disabled admins with a single indexed query instead of cross-referencing\n * the auth admin API per candidate.\n */\nexport class SupabasePlatformPermissionStore implements IPlatformPermissionStore {\n\tconstructor(private readonly clients: ClientBundle) {}\n\n\tprivate client() {\n\t\treturn this.clients.serviceClient;\n\t}\n\n\tasync getFor(ctx: RequestContext, userId: string): Promise<PlatformPermission[]> {\n\t\tassertCanReadPermissions(ctx, userId);\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('platform_permissions')\n\t\t\t.eq('user_id', userId)\n\t\t\t.maybeSingle();\n\t\tif (error) throw mapError(error);\n\t\treturn filterValid(data?.platform_permissions ?? []);\n\t}\n\n\tasync getForBatch(\n\t\tctx: RequestContext,\n\t\tuserIds: readonly string[]\n\t): Promise<Map<string, PlatformPermission[]>> {\n\t\tassertCanReadPermissionsBatch(ctx);\n\t\tconst out = new Map<string, PlatformPermission[]>();\n\t\tif (userIds.length === 0) return out;\n\t\tconst { data, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id, platform_permissions')\n\t\t\t.in('user_id', [...userIds]);\n\t\tif (error) throw mapError(error);\n\t\tfor (const row of data ?? []) {\n\t\t\tout.set(row.user_id as string, filterValid((row.platform_permissions ?? []) as string[]));\n\t\t}\n\t\treturn out;\n\t}\n\n\tasync set(\n\t\tctx: RequestContext,\n\t\tuserId: string,\n\t\tpermissions: readonly PlatformPermission[]\n\t): Promise<UserManagementResult> {\n\t\tassertCanManagePermissions(ctx);\n\n\t\t// The last-admin check runs inside the RPC, under the locks that guard the\n\t\t// write. A count here would let two demotions each see the other survive.\n\t\tconst { data, error } = await this.client().rpc('set_platform_permissions', {\n\t\t\tp_user_id: userId,\n\t\t\tp_permissions: [...permissions]\n\t\t});\n\t\tif (error) throw mapError(error);\n\t\tif ((data ?? 0) > 0) return 'ok';\n\n\t\t// Zero rows written: either the row is absent, or the predicate refused\n\t\t// the demotion. Only the second is `last_admin`, so disambiguate.\n\t\tconst { data: existing, error: fetchError } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id')\n\t\t\t.eq('user_id', userId)\n\t\t\t.maybeSingle();\n\t\tif (fetchError) throw mapError(fetchError);\n\t\treturn existing ? 'last_admin' : 'not_found';\n\t}\n\n\tasync claimFirstInstanceAdmin(\n\t\t_ctx: RequestContext,\n\t\tuserId: string,\n\t\tpermissions: readonly PlatformPermission[]\n\t): Promise<boolean> {\n\t\t// No `assertCanManagePermissions`: by definition nobody holds `instance_admin` when this\n\t\t// succeeds. The RPC takes an advisory lock and re-reads inside it, so a\n\t\t// second concurrent signer blocks and then correctly loses.\n\t\tconst { data, error } = await this.client().rpc('claim_first_instance_admin', {\n\t\t\tp_user_id: userId,\n\t\t\tp_permissions: [...permissions]\n\t\t});\n\t\tif (error) throw mapError(error);\n\t\treturn data === true;\n\t}\n\n\tasync hasInstanceAdmin(_ctx: RequestContext): Promise<boolean> {\n\t\tconst { count, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id', { count: 'exact', head: true })\n\t\t\t.contains('platform_permissions', ['instance_admin'])\n\t\t\t.eq('disabled', false);\n\t\tif (error) throw mapError(error);\n\t\treturn (count ?? 0) > 0;\n\t}\n\n\tasync countInstanceAdminsExcluding(_ctx: RequestContext, excludeUserId: string): Promise<number> {\n\t\treturn this.countOtherEnabledAdmins(excludeUserId);\n\t}\n\n\tprivate async countOtherEnabledAdmins(excludeUserId: string): Promise<number> {\n\t\tconst { count, error } = await this.client()\n\t\t\t.from('user_profiles')\n\t\t\t.select('user_id', { count: 'exact', head: true })\n\t\t\t.contains('platform_permissions', ['instance_admin'])\n\t\t\t.eq('disabled', false)\n\t\t\t.neq('user_id', excludeUserId);\n\t\tif (error) throw mapError(error);\n\t\treturn count ?? 0;\n\t}\n}\n\nconst VALID_PERMISSIONS = new Set<string>(ALL_PLATFORM_PERMISSIONS);\n\nfunction filterValid(raw: readonly string[]): PlatformPermission[] {\n\treturn raw.filter((p): p is PlatformPermission => VALID_PERMISSIONS.has(p));\n}\n\ninterface PostgrestError {\n\tcode?: string;\n\tmessage?: string;\n}\n\nfunction mapError(e: unknown): Error {\n\tconst pg = e as PostgrestError;\n\tif (pg?.code === '23505') return new ProviderError(pg.message ?? 'Duplicate record', 409);\n\tif (pg?.code === '23503') return new ProviderError(pg.message ?? 'Foreign key violation', 409);\n\tif (e instanceof Error) return e;\n\tif (e && typeof e === 'object') {\n\t\tconst obj = e as { message?: string; code?: string };\n\t\treturn new Error(obj.code ? `[${obj.code}] ${obj.message ?? ''}` : (obj.message ?? String(e)));\n\t}\n\treturn new Error(String(e));\n}\n","import type {\n\tIDataProvider,\n\tIEventSink,\n\tPurgeResult,\n\tRequestContext,\n\tRetentionCutoffs,\n\tSchemaVersionReport,\n\tUserErasureOptions\n} from '@selvajs/platform';\nimport { ERASED_ACTOR_ID, NoopLogger, ProviderError, type ILogger } from '@selvajs/platform';\nimport { readAtRestKeys } from '@selvajs/platform/computeServer';\nimport { EXPECTED_MIGRATION_HEAD, REQUIRED_MIGRATION_HEAD } from './migrationHead.js';\nimport type { ClientBundle, BuildClientOptions } from './client.js';\nimport { buildClientBundle, clientBundleFromEnv } from './client.js';\nimport { SupabaseEventSink } from './SupabaseEventSink.js';\nimport { SupabaseSolveMetricSink } from './SupabaseSolveMetricSink.js';\nimport { SupabaseAuditQuery } from './SupabaseAuditQuery.js';\nimport { SupabaseOrgStore } from './SupabaseOrgStore.js';\nimport { SupabaseProjectStore } from './SupabaseProjectStore.js';\nimport { SupabaseDefinitionStore } from './SupabaseDefinitionStore.js';\nimport { SupabaseInviteStore } from './SupabaseInviteStore.js';\nimport { SupabaseComputeServerStore } from './SupabaseComputeServerStore.js';\nimport { SupabaseShareLinkStore } from './SupabaseShareLinkStore.js';\nimport { SupabaseApiTokenStore } from './SupabaseApiTokenStore.js';\nimport { SupabaseUserProfileProvider } from '../userProfile/SupabaseUserProfileProvider.js';\nimport { SupabasePlatformPermissionStore } from '../permissions/SupabasePlatformPermissionStore.js';\nimport { SupabasePlatformProjectGrantStore } from './SupabasePlatformProjectGrantStore.js';\n\n/**\n * Composition of every data store for the Supabase backend. Builds one\n * `ClientBundle` and wires every store to it, so all stores in a process\n * share the same pooled clients.\n */\nexport class SupabaseDataProvider implements IDataProvider {\n\treadonly orgs: SupabaseOrgStore;\n\treadonly projects: SupabaseProjectStore;\n\treadonly definitions: SupabaseDefinitionStore;\n\treadonly invites: SupabaseInviteStore;\n\treadonly computeServer: SupabaseComputeServerStore;\n\treadonly shareLinks: SupabaseShareLinkStore;\n\treadonly apiTokens: SupabaseApiTokenStore;\n\treadonly userProfile: SupabaseUserProfileProvider;\n\treadonly permissions: SupabasePlatformPermissionStore;\n\treadonly platformProjectGrants: SupabasePlatformProjectGrantStore;\n\treadonly auditQuery: SupabaseAuditQuery;\n\treadonly events: IEventSink;\n\t/** Built from the same client bundle so wiring `SelvaConfig.solveMetrics` doesn't need a second Supabase client. */\n\treadonly solveMetrics: SupabaseSolveMetricSink;\n\n\tprivate constructor(\n\t\tprivate readonly clients: ClientBundle,\n\t\tevents: IEventSink,\n\t\tsecretKey?: Buffer,\n\t\tlogger: ILogger = new NoopLogger(),\n\t\tpreviousSecretKey?: Buffer\n\t) {\n\t\tthis.events = events;\n\t\tthis.solveMetrics = new SupabaseSolveMetricSink(clients, { logger });\n\t\tthis.orgs = new SupabaseOrgStore(clients, events);\n\t\tthis.projects = new SupabaseProjectStore(clients, events);\n\t\tthis.definitions = new SupabaseDefinitionStore(clients, events);\n\t\tthis.invites = new SupabaseInviteStore(clients, events);\n\t\tthis.computeServer = new SupabaseComputeServerStore(\n\t\t\tclients,\n\t\t\tsecretKey,\n\t\t\tlogger,\n\t\t\tpreviousSecretKey\n\t\t);\n\t\tthis.shareLinks = new SupabaseShareLinkStore(clients, events);\n\t\tthis.apiTokens = new SupabaseApiTokenStore(clients, events);\n\t\tthis.userProfile = new SupabaseUserProfileProvider(clients);\n\t\tthis.permissions = new SupabasePlatformPermissionStore(clients);\n\t\tthis.platformProjectGrants = new SupabasePlatformProjectGrantStore(clients);\n\t\tthis.auditQuery = new SupabaseAuditQuery(clients);\n\t}\n\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tevents?: IEventSink,\n\t\tlogger: ILogger = new NoopLogger()\n\t): SupabaseDataProvider {\n\t\tconst bundle = clientBundleFromEnv(env);\n\t\t// Same encryption-at-rest guarantee as the local provider's on-disk envelope.\n\t\tconst keys = readAtRestKeys(env);\n\t\treturn new SupabaseDataProvider(\n\t\t\tbundle,\n\t\t\tevents ?? new SupabaseEventSink(bundle, { logger }),\n\t\t\tkeys.current,\n\t\t\tlogger,\n\t\t\tkeys.previous\n\t\t);\n\t}\n\n\tstatic create(\n\t\topts: BuildClientOptions,\n\t\tevents?: IEventSink,\n\t\tsecretKey?: Buffer,\n\t\tlogger: ILogger = new NoopLogger()\n\t): SupabaseDataProvider {\n\t\tconst bundle = buildClientBundle(opts);\n\t\treturn new SupabaseDataProvider(\n\t\t\tbundle,\n\t\t\tevents ?? new SupabaseEventSink(bundle, { logger }),\n\t\t\tsecretKey,\n\t\t\tlogger\n\t\t);\n\t}\n\n\t/**\n\t * Build from a pre-existing `ClientBundle` — for tests or callers that need\n\t * to inject a custom event sink or share a bundle externally. Omit\n\t * `secretKey` only if the caller never touches compute-server apiKeys:\n\t * writes without a key throw rather than persist plaintext.\n\t */\n\tstatic fromBundle(\n\t\tbundle: ClientBundle,\n\t\tevents?: IEventSink,\n\t\tsecretKey?: Buffer,\n\t\tlogger: ILogger = new NoopLogger()\n\t): SupabaseDataProvider {\n\t\treturn new SupabaseDataProvider(\n\t\t\tbundle,\n\t\t\tevents ?? new SupabaseEventSink(bundle, { logger }),\n\t\t\tsecretKey,\n\t\t\tlogger\n\t\t);\n\t}\n\n\t/** Lets other providers in this package (storage, user profile, auth) share one set of clients per process. */\n\tgetClientBundle(): ClientBundle {\n\t\treturn this.clients;\n\t}\n\n\t/**\n\t * Calls `selva.migration_head()` (a SECURITY DEFINER RPC shipped in this\n\t * package's migrations) and compares it to the head this build expects.\n\t * Three failure shapes: the RPC is missing (handshake migration never\n\t * applied), the head is empty (no migrations pushed), or the head is\n\t * lexicographically behind {@link REQUIRED_MIGRATION_HEAD} (operator upgraded\n\t * the app but skipped `supabase db push`). A head between that and the newest\n\t * is ok, with a message naming what is pending. Never throws — boot health\n\t * consumes the report.\n\t */\n\tasync verifySchemaVersion(): Promise<SchemaVersionReport> {\n\t\tconst expected = EXPECTED_MIGRATION_HEAD;\n\t\tconst pushHint =\n\t\t\t'Apply the pending Supabase migrations: run `npx selva-supabase` to copy them ' +\n\t\t\t'into your project, then `npx supabase db push`.';\n\t\ttry {\n\t\t\tconst { data, error } = await this.clients.serviceClient.rpc('migration_head');\n\t\t\tif (error) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\texpected,\n\t\t\t\t\tactual: null,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`selva.migration_head() is not available (${error.message ?? error.code ?? 'unknown error'}) ` +\n\t\t\t\t\t\t`— the database schema is behind this app version. ${pushHint}`\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst actual = typeof data === 'string' ? data : '';\n\t\t\tif (!actual) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\texpected,\n\t\t\t\t\tactual: '',\n\t\t\t\t\tmessage: `The database reports no applied migrations. ${pushHint}`\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Timestamp prefixes are fixed-width, so string comparison is chronological.\n\t\t\t// A head ahead of the app (rolled-back app, newer DB) is tolerated — schema\n\t\t\t// changes are append-only by convention.\n\t\t\tif (actual < REQUIRED_MIGRATION_HEAD) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\texpected,\n\t\t\t\t\tactual,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`Database migration head ${actual} is behind ${REQUIRED_MIGRATION_HEAD}, ` +\n\t\t\t\t\t\t`the oldest this app runs on. ${pushHint}`\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\texpected,\n\t\t\t\tactual,\n\t\t\t\tmessage:\n\t\t\t\t\tactual < expected\n\t\t\t\t\t\t? `Migrations after ${actual} are pending; the app runs without them. ${pushHint}`\n\t\t\t\t\t\t: undefined\n\t\t\t};\n\t\t} catch (err) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\texpected,\n\t\t\t\tactual: null,\n\t\t\t\tmessage: `Schema handshake failed: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t};\n\t\t}\n\t}\n\n\t/** No-op: the `handle_new_auth_user` trigger seeds `user_profiles` on every `auth.users` insert. */\n\tasync ensureUser(): Promise<void> {\n\t\t// no-op\n\t}\n\n\t/**\n\t * FK cascade against `auth.users` already removes the profile, memberships,\n\t * and owned rows. Four classes of personal data aren't reachable by those\n\t * FKs and get scrubbed here explicitly, with the RLS-bypassing service client:\n\t *\n\t * 1. `audit_events` keyed by a plain-text `actor_id` (no FK) — deleted.\n\t * 2. The user's email in `invites.email` and in `invite.created` audit\n\t * payloads (`data->>'email'`). Invite rows are deleted; the audit email\n\t * is redacted in place — the fact that an invite was created stays, only\n\t * the PII goes.\n\t * 3. `solve_metrics.actor_id`, deliberately not FK-cascaded (retention\n\t * telemetry) — tombstoned to {@link ERASED_ACTOR_ID} so the row's\n\t * aggregate value survives without identifying the person.\n\t * 4. `platform_project_grants`, whose grantee has no FK: grants to the user\n\t * are deleted, and those they created lose `created_by`.\n\t *\n\t * Each step tolerates missing rows, so retrying is safe. Email scrubs are\n\t * skipped when `opts.email` is absent — the caller must capture it before\n\t * `deleteUser`.\n\t */\n\tasync onUserDeleted(\n\t\t_ctx: RequestContext,\n\t\tuserId: string,\n\t\topts?: UserErasureOptions\n\t): Promise<void> {\n\t\tconst client = this.clients.serviceClient;\n\t\t// Invites, and the `invite.created` payloads that copy them, hold the address lowercased.\n\t\tconst email = opts?.email?.trim().toLowerCase();\n\n\t\tconst deletedActions = await client.from('audit_events').delete().eq('actor_id', userId);\n\t\tif (deletedActions.error) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Failed to erase audit_events for user: ${deletedActions.error.message}`,\n\t\t\t\t500\n\t\t\t);\n\t\t}\n\n\t\tconst tombstoned = await client\n\t\t\t.from('solve_metrics')\n\t\t\t.update({ actor_id: ERASED_ACTOR_ID })\n\t\t\t.eq('actor_id', userId);\n\t\tif (tombstoned.error) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Failed to anonymize solve_metrics for user: ${tombstoned.error.message}`,\n\t\t\t\t500\n\t\t\t);\n\t\t}\n\n\t\tawait this.platformProjectGrants.eraseUser(userId);\n\n\t\tif (!email) return;\n\n\t\t// `invited_by` FK cascade only removes invites this user SENT, not ones addressed to them.\n\t\tconst deletedInvites = await client.from('invites').delete().eq('email', email);\n\t\tif (deletedInvites.error) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Failed to erase invites for user email: ${deletedInvites.error.message}`,\n\t\t\t\t500\n\t\t\t);\n\t\t}\n\n\t\tconst redacted = await client.rpc('redact_audit_event_email', { p_email: email });\n\t\tif (redacted.error) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t`Failed to redact audit_events email payloads: ${redacted.error.message}`,\n\t\t\t\t500\n\t\t\t);\n\t\t}\n\t}\n\n\tasync purgeExpired(_ctx: RequestContext, cutoffs: RetentionCutoffs): Promise<PurgeResult> {\n\t\tconst client = this.clients.serviceClient;\n\t\tconst purge = async (table: 'audit_events' | 'solve_metrics', before?: Date) => {\n\t\t\tif (!before) return 0;\n\t\t\t// Both tables carry an `occurred_at` index, so this is a range delete, not a scan.\n\t\t\tconst { error, count } = await client\n\t\t\t\t.from(table)\n\t\t\t\t.delete({ count: 'exact' })\n\t\t\t\t.lt('occurred_at', before.toISOString());\n\t\t\tif (error) throw new ProviderError(`Failed to purge ${table}: ${error.message}`, 500);\n\t\t\treturn count ?? 0;\n\t\t};\n\t\treturn {\n\t\t\tauditEvents: await purge('audit_events', cutoffs.auditEventsBefore),\n\t\t\tsolveMetrics: await purge('solve_metrics', cutoffs.solveMetricsBefore)\n\t\t};\n\t}\n}\n","import { createHmac, createPrivateKey, randomUUID, sign } from 'node:crypto';\nimport {\n\tNoopLogger,\n\tProviderError,\n\ttype DelegatedSessionStatus,\n\ttype IDelegatedSession,\n\ttype ILogger,\n\ttrimTrailing\n} from '@selvajs/platform';\n\nexport interface SupabaseDelegatedSessionConfig {\n\tsupabaseUrl: string;\n\tanonKey: string;\n\t/** `SUPABASE_JWT_SIGNING_KEY`: a private ES256 JWK the project trusts. Preferred. */\n\tsigningKey?: string;\n\t/** `SUPABASE_JWT_SECRET`: the legacy HS256 secret. Used only without `signingKey`. */\n\tjwtSecret?: string;\n\t/**\n\t * How long a minted session lives. It is minted once per request, so it must\n\t * outlive the slowest one (a solve), or the writes after it fail with an\n\t * expired JWT. Default 60.\n\t */\n\tttlSeconds?: number;\n\tlogger?: ILogger;\n\tfetch?: typeof fetch;\n\tnow?: () => number;\n}\n\nconst DEFAULT_TTL_SECONDS = 60;\n/** A failed check (network, or a key not yet rotated in) is retried after this long. */\nconst RECHECK_FAILED_MS = 30_000;\n\ninterface CheckEntry {\n\tresult: Promise<DelegatedSessionStatus>;\n\t/** Null after a success, which is never re-checked. */\n\tfailedAt: number | null;\n}\n\ninterface Signer {\n\talg: 'ES256' | 'HS256';\n\tkid?: string;\n\t/** Names the key for an operator, without any key material. */\n\tlabel: string;\n\thint: string;\n\tsign(data: Buffer): Buffer;\n}\n\n/**\n * Signs short-lived Supabase session JWTs so API-token requests run under the\n * owner's row security. The claims are fixed: `role` is always\n * `authenticated`, never caller-chosen, because the same key can sign a\n * `service_role` token that bypasses every policy.\n *\n * `aud` is required by GoTrue's `getUser` (400 without it); `session_id` is\n * omitted because GoTrue looks it up and rejects one with no session row.\n *\n * `selva_org` marks the session as delegated. `selva.is_instance_admin()`\n * returns false for any session carrying it, so an instance admin's key can't\n * reach other orgs through the policies' admin bypass.\n */\nexport class SupabaseDelegatedSession implements IDelegatedSession {\n\tprivate readonly signer: Signer | null;\n\tprivate readonly configError: string | null;\n\tprivate readonly logger: ILogger;\n\tprivate readonly fetchFn: typeof fetch;\n\tprivate readonly now: () => number;\n\tprivate readonly baseUrl: string;\n\tprivate check: CheckEntry | null = null;\n\n\tconstructor(private readonly config: SupabaseDelegatedSessionConfig) {\n\t\tthis.baseUrl = trimTrailing(config.supabaseUrl, '/');\n\t\tthis.logger = config.logger ?? new NoopLogger();\n\t\tthis.fetchFn = config.fetch ?? fetch;\n\t\tthis.now = config.now ?? Date.now;\n\t\tlet signer: Signer | null = null;\n\t\tlet configError: string | null = null;\n\t\ttry {\n\t\t\tsigner = config.signingKey\n\t\t\t\t? es256Signer(config.signingKey)\n\t\t\t\t: config.jwtSecret\n\t\t\t\t\t? hs256Signer(config.jwtSecret)\n\t\t\t\t\t: null;\n\t\t\tif (!signer) {\n\t\t\t\tconfigError =\n\t\t\t\t\t'API tokens need SUPABASE_JWT_SIGNING_KEY (or the legacy SUPABASE_JWT_SECRET) so Selva can act as the token owner under row security.';\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconfigError = err instanceof Error ? err.message : String(err);\n\t\t}\n\t\tthis.signer = signer;\n\t\tthis.configError = configError;\n\t}\n\n\tstatus(): Promise<DelegatedSessionStatus> {\n\t\tif (!this.signer) return Promise.resolve({ ok: false, message: this.configError! });\n\t\tconst current = this.check;\n\t\tif (\n\t\t\tcurrent &&\n\t\t\t(current.failedAt === null || this.now() - current.failedAt < RECHECK_FAILED_MS)\n\t\t) {\n\t\t\treturn current.result;\n\t\t}\n\t\tconst next = { failedAt: null } as CheckEntry;\n\t\tnext.result = this.probe(this.signer).then((status) => {\n\t\t\tif (!status.ok) {\n\t\t\t\tnext.failedAt = this.now();\n\t\t\t\tthis.logger.error('API tokens are off: delegated sessions failed their check', {\n\t\t\t\t\tcomponent: 'delegatedSession',\n\t\t\t\t\treason: status.message\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn status;\n\t\t});\n\t\tthis.check = next;\n\t\treturn next.result;\n\t}\n\n\tasync mint(userId: string, { orgId }: { orgId: string }): Promise<string> {\n\t\tconst status = await this.status();\n\t\tif (!status.ok) throw new ProviderError(status.message, 503);\n\t\treturn this.signFor(this.signer!, userId, orgId);\n\t}\n\n\t/**\n\t * Proves PostgREST accepts what this key signs, which a JWKS lookup alone\n\t * doesn't: Supabase lists a standby key in the JWKS but only trusts it once\n\t * the project has rotated to it. The random `sub` matches no rows, so the\n\t * read is empty either way; only a 401 means the key is refused.\n\t */\n\tprivate async probe(signer: Signer): Promise<DelegatedSessionStatus> {\n\t\ttry {\n\t\t\tconst res = await this.fetchFn(`${this.baseUrl}/rest/v1/orgs?select=id&limit=1`, {\n\t\t\t\theaders: {\n\t\t\t\t\tapikey: this.config.anonKey,\n\t\t\t\t\tAuthorization: `Bearer ${this.signFor(signer, randomUUID(), randomUUID())}`,\n\t\t\t\t\t'Accept-Profile': 'selva'\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (res.ok) return { ok: true };\n\t\t\tif (res.status === 401) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tmessage: `Supabase rejected a session signed with ${signer.label}. ${signer.hint}`\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: `Couldn't check ${signer.label}: Supabase answered ${res.status}.`\n\t\t\t};\n\t\t} catch (err) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: `Couldn't reach Supabase to check ${signer.label}: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate signFor(signer: Signer, userId: string, orgId: string): string {\n\t\tconst iat = Math.floor(this.now() / 1000);\n\t\tconst header = { alg: signer.alg, typ: 'JWT', ...(signer.kid ? { kid: signer.kid } : {}) };\n\t\tconst payload = {\n\t\t\tsub: userId,\n\t\t\trole: 'authenticated',\n\t\t\taud: 'authenticated',\n\t\t\tiat,\n\t\t\texp: iat + (this.config.ttlSeconds ?? DEFAULT_TTL_SECONDS),\n\t\t\tiss: `${this.baseUrl}/auth/v1`,\n\t\t\tselva_org: orgId\n\t\t};\n\t\tconst input = `${base64url(header)}.${base64url(payload)}`;\n\t\treturn `${input}.${signer.sign(Buffer.from(input)).toString('base64url')}`;\n\t}\n}\n\nfunction base64url(value: object): string {\n\treturn Buffer.from(JSON.stringify(value)).toString('base64url');\n}\n\ninterface EcJwk {\n\tkty?: string;\n\tcrv?: string;\n\tx?: string;\n\ty?: string;\n\td?: string;\n\tkid?: string;\n\tkey_ops?: string[];\n}\n\n/** Accepts the JWK `supabase gen signing-key` prints, or an array of them (a `signing_keys.json`). */\nfunction es256Signer(raw: string): Signer {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\tthrow new Error(\n\t\t\t'SUPABASE_JWT_SIGNING_KEY is not valid JSON. Expected the private JWK from `supabase gen signing-key --algorithm ES256`.'\n\t\t);\n\t}\n\tconst keys = (Array.isArray(parsed) ? parsed : [parsed]) as EcJwk[];\n\tconst jwk = keys.find((k) => k?.key_ops?.includes('sign')) ?? keys[0];\n\tif (!jwk || jwk.kty !== 'EC' || jwk.crv !== 'P-256' || !jwk.d || !jwk.x || !jwk.y) {\n\t\tthrow new Error(\n\t\t\t'SUPABASE_JWT_SIGNING_KEY must be a private ES256 key: kty \"EC\", crv \"P-256\", with \"d\".'\n\t\t);\n\t}\n\tif (!jwk.kid) {\n\t\tthrow new Error(\n\t\t\t'SUPABASE_JWT_SIGNING_KEY has no \"kid\". Supabase matches tokens to keys by it.'\n\t\t);\n\t}\n\tconst key = createPrivateKey({\n\t\tkey: { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y, d: jwk.d },\n\t\tformat: 'jwk'\n\t});\n\treturn {\n\t\talg: 'ES256',\n\t\tkid: jwk.kid,\n\t\tlabel: `SUPABASE_JWT_SIGNING_KEY (kid ${jwk.kid})`,\n\t\thint:\n\t\t\t'On hosted Supabase, import it as a standby key under Settings → JWT signing keys, then rotate to it. ' +\n\t\t\t'Self-hosted, it must be in JWT_KEYS and JWT_JWKS.',\n\t\t// JWS wants the raw r||s form, not DER.\n\t\tsign: (data) => sign('sha256', data, { key, dsaEncoding: 'ieee-p1363' })\n\t};\n}\n\n/** Legacy fallback. Stops working once the project revokes its legacy secret. */\nfunction hs256Signer(secret: string): Signer {\n\treturn {\n\t\talg: 'HS256',\n\t\tlabel: 'SUPABASE_JWT_SECRET',\n\t\thint: \"Check it matches the project's legacy JWT secret and that the secret hasn't been revoked.\",\n\t\tsign: (data) => createHmac('sha256', secret).update(data).digest()\n\t};\n}\n","import {\n\tcomposeManifest,\n\tdefineSetting,\n\tresolveConfig,\n\ttype EnvRecord\n} from '@selvajs/platform/config';\n\nexport const SUPABASE_SETTINGS = composeManifest([\n\tdefineSetting({\n\t\tkey: 'SUPABASE_URL',\n\t\tlabel: 'Supabase project',\n\t\ttype: 'url',\n\t\trequired: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'Supabase project URL.',\n\t\timpact: 'Pointing it at another project shows that project’s users and data.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_ANON_KEY',\n\t\tlabel: 'Supabase publishable key',\n\t\ttype: 'string',\n\t\trequired: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tdescription: 'Publishable key (sb_publishable_…).'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_SERVICE_ROLE_KEY',\n\t\tlabel: 'Supabase secret key',\n\t\ttype: 'string',\n\t\trequired: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tdescription: 'Secret key (sb_secret_…). Bypasses row security: server only.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_JWT_SIGNING_KEY',\n\t\tlabel: 'Supabase JWT signing key',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tdescription: 'Private ES256 JWK, one line. Needed for API tokens.',\n\t\timpact: 'Without it, or SUPABASE_JWT_SECRET, API tokens answer 503.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_JWT_SECRET',\n\t\tlabel: 'Supabase JWT secret (legacy)',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tdescription: 'Legacy HS256 JWT secret. Used only without SUPABASE_JWT_SIGNING_KEY.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_ENABLE_SELF_SIGNUP',\n\t\tlabel: 'Self sign-up',\n\t\ttype: 'bool',\n\t\tdefault: false,\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription: 'Allow self-service sign-up at /signup.',\n\t\tlegacy: { bool: 'exact-true' }\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_ALLOW_EMAIL_LINK_SIGNUP',\n\t\tlabel: 'Sign-up by email link',\n\t\ttype: 'bool',\n\t\tdefault: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription: 'A magic link to an unknown address creates an account.',\n\t\tlegacy: { bool: 'not-false' }\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_OAUTH_PROVIDERS',\n\t\tlabel: 'OAuth sign-in buttons',\n\t\ttype: 'list',\n\t\tdefault: [],\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription: 'OAuth buttons on the login page (google, github, azure, gitlab).'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_PUBLIC_BUCKET',\n\t\tlabel: 'Public files bucket',\n\t\ttype: 'string',\n\t\tdefault: 'selva-public',\n\t\tonInvalid: 'fail',\n\t\tclass: 'tunable',\n\t\tdescription: 'Storage bucket for public files.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SUPABASE_PRIVATE_BUCKET',\n\t\tlabel: 'Private files bucket',\n\t\ttype: 'string',\n\t\tdefault: 'selva-private',\n\t\tonInvalid: 'fail',\n\t\tclass: 'tunable',\n\t\tdescription: 'Storage bucket for private files.'\n\t})\n]);\n\n/** Resolve this provider's keys, throwing on the first fail-closed error. */\nexport function resolveSupabaseEnv(env: EnvRecord): Record<string, unknown> {\n\tconst { values, errors } = resolveConfig(SUPABASE_SETTINGS, env);\n\tif (errors.length > 0) {\n\t\tconst e = errors[0];\n\t\tthrow new Error(\n\t\t\te.problem === 'is required' ? `Missing required env var: ${e.key}` : `${e.key} ${e.problem}.`\n\t\t);\n\t}\n\treturn values;\n}\n","import { createClient, type SupabaseClient, type User } from '@supabase/supabase-js';\nimport { NoopLogger, clampPageLimit, type ILogger } from '@selvajs/platform';\nimport { DEFAULT_SCHEMA, type SelvaSchemaClient } from '../data/client.js';\nimport { SupabaseDelegatedSession } from './SupabaseDelegatedSession.js';\nimport { resolveSupabaseEnv } from '../config.js';\nimport type {\n\tIAuthProvider,\n\tIDelegatedSession,\n\tIEmailLinkAuth,\n\tIOAuthAuth,\n\tIPasswordAuth,\n\tISessionRefresh,\n\tAuthUser,\n\tLoginResult,\n\tUserManagementResult,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\n\n/**\n * Auth backed by Supabase Auth (GoTrue). Identity-only — platform permissions\n * live on `IPlatformPermissionStore`, profile state on `IUserProfileStore`.\n */\nexport interface SupabaseAuthProviderConfig {\n\tsupabaseUrl: string;\n\tanonKey: string;\n\tserviceRoleKey: string;\n\t/** Allow self-service signup via `passwordAuth.registerUser`. Default false. */\n\tenableSelfSignup?: boolean;\n\t/**\n\t * OAuth providers enabled in the Supabase dashboard (lowercased: \"google\",\n\t * \"github\", …), surfaced via `oauth.listProviders()`. Default empty.\n\t */\n\toauthProviders?: readonly string[];\n\t/**\n\t * Allow `emailLink.sendMagicLink` to create new users on first request.\n\t * Default true, matching Supabase's `signInWithOtp` default. Set false for\n\t * invite-only deployments; `sendMagicLink` for an unknown email then\n\t * returns `{ ok: false, reason: 'signup_disabled' }`.\n\t */\n\tallowEmailLinkSignup?: boolean;\n\t/**\n\t * How `verifyToken` validates session JWTs — see that method for the\n\t * rationale. `'hybrid'` (default) verifies locally and rechecks GoTrue\n\t * periodically; `'strict'` calls GoTrue on every request.\n\t */\n\ttokenVerification?: 'hybrid' | 'strict';\n\t/** Recheck window for `'hybrid'` verification, in ms. Default 60s. */\n\trevalidateMs?: number;\n\t/**\n\t * Private ES256 JWK the project trusts, for API-token requests. Without it\n\t * (or `jwtSecret`), API tokens are off; sign-in is unaffected.\n\t */\n\tjwtSigningKey?: string;\n\t/** Legacy HS256 secret, used only when `jwtSigningKey` is unset. */\n\tjwtSecret?: string;\n\t/** Lifetime of an API-token request's delegated session; see `SupabaseDelegatedSessionConfig.ttlSeconds`. */\n\tdelegatedSessionTtlSeconds?: number;\n\t/**\n\t * Sink for best-effort failures the provider swallows rather than throwing\n\t * (currently `touchLastLogin`). Defaults to `NoopLogger`. Only identifiers\n\t * are ever logged, never payloads.\n\t */\n\tlogger?: ILogger;\n}\n\nconst DEFAULT_REVALIDATE_MS = 60_000;\n\nexport class SupabaseAuthProvider implements IAuthProvider {\n\treadonly name = 'Supabase Auth';\n\treadonly passwordAuth: IPasswordAuth;\n\treadonly oauth: IOAuthAuth;\n\treadonly emailLink: IEmailLinkAuth;\n\treadonly sessionRefresh: ISessionRefresh;\n\treadonly delegatedSession: IDelegatedSession;\n\n\tprivate readonly admin: SupabaseClient;\n\t/**\n\t * Service-role client pinned to the `selva` schema. `this.admin` stays\n\t * unpinned because it only drives `auth.admin.*` (GoTrue's own REST\n\t * surface, unaffected by the PostgREST schema setting) — any table read\n\t * or write must go through `db` instead.\n\t */\n\tprivate readonly db: SelvaSchemaClient;\n\tprivate readonly anon: SupabaseClient;\n\tprivate readonly anonKey: string;\n\tprivate readonly supabaseUrl: string;\n\tprivate readonly tokenVerification: 'hybrid' | 'strict';\n\tprivate readonly revalidateMs: number;\n\tprivate readonly logger: ILogger;\n\n\t/**\n\t * Last GoTrue recheck per session (epoch ms), keyed by JWT `session_id`.\n\t * Swept lazily in `markRevalidated` so session churn can't leak memory.\n\t * Per-process — multi-instance drift is harmless, each instance rechecks\n\t * on its own schedule.\n\t */\n\tprivate readonly lastRevalidatedAt = new Map<string, number>();\n\t/**\n\t * When this process ended a user's sessions (sign-out, disable, delete), by\n\t * user id. A session last rechecked before that moment is rechecked on its\n\t * next request instead of riding out the window. Other instances still take\n\t * up to `revalidateMs`.\n\t */\n\tprivate readonly sessionsEndedAt = new Map<string, number>();\n\n\tconstructor(config: SupabaseAuthProviderConfig) {\n\t\tthis.supabaseUrl = config.supabaseUrl;\n\t\tthis.anonKey = config.anonKey;\n\t\tthis.tokenVerification = config.tokenVerification ?? 'hybrid';\n\t\tthis.revalidateMs = config.revalidateMs ?? DEFAULT_REVALIDATE_MS;\n\t\tthis.logger = config.logger ?? new NoopLogger();\n\t\tthis.admin = createClient(config.supabaseUrl, config.serviceRoleKey, {\n\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t});\n\t\tthis.db = createClient(config.supabaseUrl, config.serviceRoleKey, {\n\t\t\tdb: { schema: DEFAULT_SCHEMA },\n\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t}) as SelvaSchemaClient;\n\t\tthis.anon = createClient(config.supabaseUrl, config.anonKey, {\n\t\t\tauth: { persistSession: false, autoRefreshToken: false }\n\t\t});\n\t\tthis.passwordAuth = new SupabasePasswordAuth(\n\t\t\tthis.admin,\n\t\t\tthis.anon,\n\t\t\t(email, password) => this.signIn(email, password),\n\t\t\tconfig.enableSelfSignup ?? false,\n\t\t\t(user) => this.hydrate(user)\n\t\t);\n\t\tthis.sessionRefresh = new SupabaseSessionRefresh(\n\t\t\tthis.anon,\n\t\t\tthis.admin,\n\t\t\tthis.logger,\n\t\t\t(token) => {\n\t\t\t\tconst userId = unverifiedSubject(token);\n\t\t\t\tif (userId) this.markSessionsEnded(userId);\n\t\t\t}\n\t\t);\n\t\tthis.oauth = new SupabaseOAuthAuth(\n\t\t\tthis.anon,\n\t\t\t(user) => this.hydrate(user),\n\t\t\tconfig.oauthProviders ?? []\n\t\t);\n\t\tthis.emailLink = new SupabaseEmailLinkAuth(\n\t\t\tthis.anon,\n\t\t\t(user) => this.hydrate(user),\n\t\t\tconfig.allowEmailLinkSignup ?? true\n\t\t);\n\t\tthis.delegatedSession = new SupabaseDelegatedSession({\n\t\t\tsupabaseUrl: config.supabaseUrl,\n\t\t\tanonKey: config.anonKey,\n\t\t\t...(config.jwtSigningKey ? { signingKey: config.jwtSigningKey } : {}),\n\t\t\t...(config.jwtSecret ? { jwtSecret: config.jwtSecret } : {}),\n\t\t\t...(config.delegatedSessionTtlSeconds\n\t\t\t\t? { ttlSeconds: config.delegatedSessionTtlSeconds }\n\t\t\t\t: {}),\n\t\t\tlogger: this.logger\n\t\t});\n\t}\n\n\tstatic fromEnv(\n\t\tenv: Record<string, string | undefined>,\n\t\tlogger?: ILogger,\n\t\toptions: Pick<SupabaseAuthProviderConfig, 'delegatedSessionTtlSeconds'> = {}\n\t): SupabaseAuthProvider {\n\t\t// Strict parsing: a sign-up control that read anything but \"false\" as on\n\t\t// let `=no` open sign-ups. A bad value now stops boot.\n\t\tconst v = resolveSupabaseEnv(env);\n\t\tconst jwtSigningKey = v.SUPABASE_JWT_SIGNING_KEY as string | undefined;\n\t\tconst jwtSecret = v.SUPABASE_JWT_SECRET as string | undefined;\n\t\treturn new SupabaseAuthProvider({\n\t\t\tsupabaseUrl: v.SUPABASE_URL as string,\n\t\t\tanonKey: v.SUPABASE_ANON_KEY as string,\n\t\t\tserviceRoleKey: v.SUPABASE_SERVICE_ROLE_KEY as string,\n\t\t\tenableSelfSignup: v.SUPABASE_ENABLE_SELF_SIGNUP as boolean,\n\t\t\toauthProviders: (v.SUPABASE_OAUTH_PROVIDERS as string[]).map((p) => p.toLowerCase()),\n\t\t\tallowEmailLinkSignup: v.SUPABASE_ALLOW_EMAIL_LINK_SIGNUP as boolean,\n\t\t\t...(logger ? { logger } : {}),\n\t\t\t...(jwtSigningKey ? { jwtSigningKey } : {}),\n\t\t\t...(jwtSecret ? { jwtSecret } : {}),\n\t\t\t...options\n\t\t});\n\t}\n\n\t/**\n\t * Verify a session JWT and return the user, or null if invalid/disabled.\n\t * Runs on every authenticated request, so the fast path avoids a network\n\t * round-trip.\n\t *\n\t * `'hybrid'` (default): `getClaims(token)` verifies the JWT locally with\n\t * asymmetric signing keys (the modern Supabase default — the SDK checks\n\t * against the cached JWKS via Web Crypto, no GoTrue call). A legacy\n\t * symmetric HS256 token can only be checked by GoTrue, so it gets one\n\t * `getUser` per call, as in `'strict'`. For an asymmetric token, a\n\t * local check can't see a server-side sign-out or `disabled` flip that\n\t * happened after the token was issued — the claims are a snapshot — so we\n\t * also re-check against GoTrue via `getUser`, at most once per\n\t * `revalidateMs` per session, bounding revocation latency to that window\n\t * while skipping the network call on most requests.\n\t *\n\t * `'strict'`: `getUser` on every request. Instant revocation, one round\n\t * trip per request.\n\t */\n\tasync verifyToken(token: string): Promise<AuthUser | null> {\n\t\tif (!token) return null;\n\n\t\t// A symmetric (HS256) token has no local check: `getClaims` would ask GoTrue, and the\n\t\t// recheck would ask again. One `getUser` answers both.\n\t\tif (this.tokenVerification === 'strict' || isSymmetricJwt(token)) {\n\t\t\treturn this.verifyViaGetUser(token);\n\t\t}\n\n\t\tconst claims = await this.getClaimsOrNull(token);\n\t\tif (!claims) return null;\n\t\tif ((claims.app_metadata as { disabled?: boolean } | undefined)?.disabled === true) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst sessionId = typeof claims.session_id === 'string' ? claims.session_id : claims.sub;\n\t\tif (this.shouldRevalidate(sessionId, claims.sub)) {\n\t\t\t// Stamped with the start: a session ended while GoTrue was answering must\n\t\t\t// still read as older than that end.\n\t\t\tconst startedAt = Date.now();\n\t\t\tconst fresh = await this.verifyViaGetUser(token);\n\t\t\tif (!fresh) {\n\t\t\t\tthis.lastRevalidatedAt.delete(sessionId);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthis.markRevalidated(sessionId, startedAt);\n\t\t\treturn fresh;\n\t\t}\n\n\t\treturn {\n\t\t\tid: claims.sub,\n\t\t\temail: typeof claims.email === 'string' ? claims.email : undefined,\n\t\t\tdisabled: false,\n\t\t\tmetadata: claims.user_metadata\n\t\t};\n\t}\n\n\t/** Full network verify against GoTrue. Also the `'strict'`-mode path. */\n\tprivate async verifyViaGetUser(token: string): Promise<AuthUser | null> {\n\t\tconst { data, error } = await this.anon.auth.getUser(token);\n\t\tif (error || !data.user) return null;\n\t\tif (isDisabled(data.user)) return null;\n\t\treturn this.hydrate(data.user);\n\t}\n\n\t/** Local JWT verification. Returns the claims, or null if invalid/expired. */\n\tprivate async getClaimsOrNull(token: string) {\n\t\ttry {\n\t\t\tconst { data, error } = await this.anon.auth.getClaims(token);\n\t\t\tif (error || !data) return null;\n\t\t\treturn data.claims;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate shouldRevalidate(sessionId: string, userId: string): boolean {\n\t\tconst last = this.lastRevalidatedAt.get(sessionId);\n\t\tif (last === undefined || Date.now() - last >= this.revalidateMs) return true;\n\t\tconst ended = this.sessionsEndedAt.get(userId);\n\t\treturn ended !== undefined && last <= ended;\n\t}\n\n\tprivate markSessionsEnded(userId: string): void {\n\t\tconst now = Date.now();\n\t\t// Past one window every session has rechecked on its own schedule.\n\t\tfor (const [id, at] of this.sessionsEndedAt) {\n\t\t\tif (now - at > this.revalidateMs) this.sessionsEndedAt.delete(id);\n\t\t}\n\t\tthis.sessionsEndedAt.set(userId, now);\n\t}\n\n\tprivate markRevalidated(sessionId: string, at: number): void {\n\t\tconst now = Date.now();\n\t\tthis.lastRevalidatedAt.set(sessionId, at);\n\t\t// Lazy sweep so a churn of distinct sessions can't grow the map without\n\t\t// bound. Anything older than two windows is definitely stale (it would\n\t\t// revalidate on next use anyway). Cheap: only runs when the map is large.\n\t\tif (this.lastRevalidatedAt.size > 10_000) {\n\t\t\tconst cutoff = now - this.revalidateMs * 2;\n\t\t\tfor (const [id, ts] of this.lastRevalidatedAt) {\n\t\t\t\tif (ts < cutoff) this.lastRevalidatedAt.delete(id);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getUser(id: string): Promise<AuthUser | null> {\n\t\tconst { data, error } = await this.admin.auth.admin.getUserById(id);\n\t\tif (error || !data.user) return null;\n\t\treturn this.hydrate(data.user);\n\t}\n\n\tasync listUsers(opts?: ListOptions): Promise<Page<AuthUser> | null> {\n\t\t// GoTrue paginates by page number, not offset — translate our cursor. It\n\t\t// accepts any perPage, answers 0 with a 500 and refuses negatives: clamp here.\n\t\tconst perPage = clampPageLimit(opts?.limit);\n\t\tconst requested = opts?.cursor ? parseInt(opts.cursor, 10) : 1;\n\t\tconst page = Number.isFinite(requested) && requested >= 1 ? requested : 1;\n\t\tconst { data, error } = await this.admin.auth.admin.listUsers({ page, perPage });\n\t\tif (error) throw error;\n\n\t\tconst users = data.users;\n\t\tconst hydrated = users.map((u) => this.hydrate(u));\n\t\tconst nextCursor = users.length >= perPage ? String(page + 1) : undefined;\n\t\treturn { items: hydrated, nextCursor };\n\t}\n\n\tasync createUser(email: string): Promise<AuthUser> {\n\t\t// No password — the user signs in via magic link or OAuth.\n\t\tconst { data, error } = await this.admin.auth.admin.createUser({\n\t\t\temail,\n\t\t\temail_confirm: true\n\t\t});\n\t\tif (error) throw error;\n\t\tif (!data.user) throw new Error('createUser returned no user');\n\t\treturn this.hydrate(data.user);\n\t}\n\n\tasync deleteUser(id: string): Promise<UserManagementResult> {\n\t\t// Identity-only: the sole-instance_admin invariant lives on\n\t\t// IPlatformPermissionStore, which callers must consult before this.\n\t\tconst { error } = await this.admin.auth.admin.deleteUser(id);\n\t\tif (error) {\n\t\t\t// GoTrue's 404 shows up as either a status code or a message string.\n\t\t\tconst e = error as unknown as { status?: number; message?: string };\n\t\t\tif (e.status === 404 || /not.?found/i.test(e.message ?? '')) return 'not_found';\n\t\t\tthrow error;\n\t\t}\n\t\tthis.markSessionsEnded(id);\n\t\treturn 'ok';\n\t}\n\n\tasync disableUser(id: string): Promise<UserManagementResult> {\n\t\tconst { data: existing, error: fetchError } = await this.admin.auth.admin.getUserById(id);\n\t\tif (fetchError || !existing.user) return 'not_found';\n\t\t// The ban makes GoTrue refuse sign-in and refresh; the flag goes to app_metadata, which\n\t\t// only the service role writes (a user rewrites their own user_metadata at will).\n\t\tconst { error } = await this.admin.auth.admin.updateUserById(id, {\n\t\t\tban_duration: BAN_FOREVER,\n\t\t\tapp_metadata: { ...(existing.user.app_metadata ?? {}), disabled: true }\n\t\t});\n\t\tif (error) {\n\t\t\tconst e = error as unknown as { status?: number; message?: string };\n\t\t\tif (e.status === 404 || /not.?found/i.test(e.message ?? '')) return 'not_found';\n\t\t\tthrow error;\n\t\t}\n\t\tthis.markSessionsEnded(id);\n\t\treturn 'ok';\n\t}\n\n\tasync touchLastLogin(id: string): Promise<void> {\n\t\t// Debounced in a single UPDATE: the WHERE clause skips the write when the\n\t\t// stamp is recent, so a login storm from one user costs one no-op\n\t\t// round-trip instead of a select + conditional update.\n\t\tconst cutoff = new Date(Date.now() - 60_000).toISOString();\n\t\t// Must use `this.db`, not `this.admin` — `user_profiles` lives in `selva`,\n\t\t// and an unpinned client resolves against `public`, where the table\n\t\t// doesn't exist. That relation-not-found error previously went to an\n\t\t// unchecked await and the stamp silently never landed.\n\t\tconst { error } = await this.db\n\t\t\t.from('user_profiles')\n\t\t\t.update({ last_login_at: new Date().toISOString() })\n\t\t\t.eq('user_id', id)\n\t\t\t.or(`last_login_at.is.null,last_login_at.lt.${cutoff}`);\n\t\t// Never throws — a failed stamp must not block auth — but it's logged\n\t\t// now instead of swallowed, so a regression here doesn't stay invisible.\n\t\tif (error) {\n\t\t\tthis.logger.warn('touchLastLogin failed', {\n\t\t\t\tuserId: id,\n\t\t\t\tcode: error.code,\n\t\t\t\tmessage: error.message\n\t\t\t});\n\t\t}\n\t}\n\n\t// ============================================================================\n\t// Internals\n\t// ============================================================================\n\t/** Kept on the provider class so it can call `hydrate` without plumbing it through. */\n\tprivate async signIn(\n\t\temail: string,\n\t\tpassword: string\n\t): Promise<{ user: AuthUser; sessionToken: string } | null> {\n\t\tconst { data, error } = await this.anon.auth.signInWithPassword({ email, password });\n\t\tif (error || !data.user || !data.session) return null;\n\t\tif (isDisabled(data.user)) return null;\n\t\treturn { user: this.hydrate(data.user), sessionToken: data.session.access_token };\n\t}\n\n\t/** Map a GoTrue `User` to our identity-only `AuthUser`. */\n\tprivate hydrate(user: User): AuthUser {\n\t\treturn {\n\t\t\tid: user.id,\n\t\t\temail: user.email ?? undefined,\n\t\t\tcreatedAt: user.created_at ?? undefined,\n\t\t\tlastLoginAt: user.last_sign_in_at ?? undefined,\n\t\t\tdisabled: isDisabled(user),\n\t\t\tmetadata: user.user_metadata\n\t\t};\n\t}\n\n\t/** Lets other code (storage provider, per-request client factories) build user-scoped clients without a second config read. */\n\tgetAnonClientConfig(): { supabaseUrl: string; anonKey: string } {\n\t\treturn { supabaseUrl: this.supabaseUrl, anonKey: this.anonKey };\n\t}\n}\n\n/** Whether a JWT's header names an HMAC algorithm. Unverified: it only picks the check. */\nfunction isSymmetricJwt(token: string): boolean {\n\ttry {\n\t\tconst header = JSON.parse(Buffer.from(token.split('.')[0] ?? '', 'base64url').toString('utf8'));\n\t\treturn typeof header?.alg === 'string' && header.alg.startsWith('HS');\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nclass SupabasePasswordAuth implements IPasswordAuth {\n\tconstructor(\n\t\tprivate readonly admin: SupabaseClient,\n\t\tprivate readonly anon: SupabaseClient,\n\t\tprivate readonly signIn: (\n\t\t\temail: string,\n\t\t\tpassword: string\n\t\t) => Promise<{ user: AuthUser; sessionToken: string } | null>,\n\t\tprivate readonly enableSelfSignup: boolean,\n\t\tprivate readonly hydrate: (user: User) => AuthUser\n\t) {}\n\n\tasync verifyLogin(email: string, password: string): Promise<LoginResult> {\n\t\tconst result = await this.signIn(email, password);\n\t\tif (!result) return { kind: 'failed', reason: 'invalid_credentials' };\n\t\treturn { kind: 'success', user: result.user, sessionToken: result.sessionToken };\n\t}\n\n\tasync createUserWithPassword(email: string, password: string): Promise<AuthUser> {\n\t\tconst { data, error } = await this.admin.auth.admin.createUser({\n\t\t\temail,\n\t\t\tpassword,\n\t\t\temail_confirm: true\n\t\t});\n\t\tif (error) throw error;\n\t\tif (!data.user) throw new Error('createUserWithPassword returned no user');\n\t\treturn this.hydrate(data.user);\n\t}\n\n\tasync registerUser(email: string, password: string): Promise<AuthUser | null> {\n\t\tif (!this.enableSelfSignup) return null;\n\t\tconst { data, error } = await this.anon.auth.signUp({ email, password });\n\t\tif (error || !data.user) return null;\n\t\treturn this.hydrate(data.user);\n\t}\n}\n\n/**\n * Supabase-backed `IOAuthAuth`. Thin wrapper over GoTrue's `signInWithOAuth`\n * / `exchangeCodeForSession` — mapping failures to null vs throw is the only logic.\n */\nclass SupabaseOAuthAuth implements IOAuthAuth {\n\tconstructor(\n\t\tprivate readonly anon: SupabaseClient,\n\t\tprivate readonly hydrate: (user: User) => AuthUser,\n\t\tprivate readonly providers: readonly string[]\n\t) {}\n\n\tlistProviders(): readonly string[] {\n\t\treturn this.providers;\n\t}\n\n\tasync getOAuthAuthorizationUrl(\n\t\tprovider: 'google' | 'github' | 'azure' | 'gitlab',\n\t\tredirectTo: string\n\t): Promise<string> {\n\t\tconst { data, error } = await this.anon.auth.signInWithOAuth({\n\t\t\tprovider,\n\t\t\toptions: { redirectTo, skipBrowserRedirect: true }\n\t\t});\n\t\tif (error || !data.url) throw error ?? new Error('signInWithOAuth returned no URL');\n\t\treturn data.url;\n\t}\n\n\tasync exchangeOAuthCode(code: string): Promise<{\n\t\tuser: AuthUser;\n\t\tsessionToken: string;\n\t\trefreshToken: string;\n\t} | null> {\n\t\tconst { data, error } = await this.anon.auth.exchangeCodeForSession(code);\n\t\tif (error || !data.user || !data.session) return null;\n\t\tif (isDisabled(data.user)) return null;\n\t\treturn {\n\t\t\tuser: this.hydrate(data.user),\n\t\t\tsessionToken: data.session.access_token,\n\t\t\trefreshToken: data.session.refresh_token\n\t\t};\n\t}\n}\n\nconst BAN_FOREVER = '876000h';\n\n/** Disabled by an admin: flagged in app_metadata or banned. Never `user_metadata`, which the user writes. */\nfunction isDisabled(user: Pick<User, 'app_metadata' | 'banned_until'>): boolean {\n\tif (user.app_metadata?.disabled === true) return true;\n\treturn user.banned_until ? Date.parse(user.banned_until) > Date.now() : false;\n}\n\n/** The `sub` of a JWT, unverified: only ever used to force a recheck, never to trust. */\nfunction unverifiedSubject(token: string): string | null {\n\ttry {\n\t\tconst payload = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString());\n\t\treturn typeof payload?.sub === 'string' ? payload.sub : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Supabase-backed `ISessionRefresh`. `refreshSession` uses the anon client —\n * a refresh token authenticates itself. `revokeSession` uses the service-role\n * client — revoking someone else's session is privileged.\n */\nclass SupabaseSessionRefresh implements ISessionRefresh {\n\tconstructor(\n\t\tprivate readonly anon: SupabaseClient,\n\t\tprivate readonly admin: SupabaseClient,\n\t\tprivate readonly logger: ILogger,\n\t\tprivate readonly onRevoked: (token: string) => void\n\t) {}\n\n\tasync refreshSession(refreshToken: string): Promise<{\n\t\tsessionToken: string;\n\t\trefreshToken: string;\n\t} | null> {\n\t\tconst { data, error } = await this.anon.auth.refreshSession({ refresh_token: refreshToken });\n\t\tif (error || !data.session) return null;\n\t\t// Refresh runs after verifyToken has already failed, so it's the last gate\n\t\t// on an expired-access-token request. Without this check, a disabled user\n\t\t// could mint fresh access tokens forever — verifyToken's revalidateMs\n\t\t// bound never gets a chance to apply. GoTrue returns the user alongside\n\t\t// the session, so the check is free.\n\t\tif (data.user !== null && isDisabled(data.user)) return null;\n\t\treturn {\n\t\t\tsessionToken: data.session.access_token,\n\t\t\trefreshToken: data.session.refresh_token\n\t\t};\n\t}\n\n\tasync revokeSession(token: string): Promise<boolean> {\n\t\t// 'global': sign out every session for this user, not just the one this\n\t\t// JWT names. Logout on a shared machine shouldn't leave a sibling session\n\t\t// alive, and a token that reached us at all may already be leaked.\n\t\tconst { error } = await this.admin.auth.admin.signOut(token, 'global');\n\t\t// Whatever GoTrue answered, this process stops trusting its last recheck.\n\t\tthis.onRevoked(token);\n\t\tif (!error) return true;\n\t\t// A token GoTrue no longer recognizes (already signed out, expired,\n\t\t// malformed) is the desired end state, not a failure — report success so\n\t\t// the caller doesn't log noise on every double-logout.\n\t\tconst e = error as unknown as { status?: number; message?: string };\n\t\tif (e.status === 401 || e.status === 403 || e.status === 404) return true;\n\t\t// Anything else (5xx, network, misconfigured service-role key) means the\n\t\t// session may still be live. Never throw — a failed revoke must not\n\t\t// block the user from logging out.\n\t\tthis.logger.warn('revokeSession failed', { status: e.status, message: e.message });\n\t\treturn false;\n\t}\n}\n\n/**\n * Supabase-backed `IEmailLinkAuth`. Wraps GoTrue's `signInWithOtp` (send)\n * and `verifyOtp` (verify on click).\n *\n * Supabase emails the user `{callbackUrl}?token_hash=…&type=…`. The `type`\n * param picks which OTP variant `verifyOtp` runs (signup vs returning-user\n * magic link vs invite acceptance), so we pass it through unchanged.\n */\nclass SupabaseEmailLinkAuth implements IEmailLinkAuth {\n\tconstructor(\n\t\tprivate readonly anon: SupabaseClient,\n\t\tprivate readonly hydrate: (user: User) => AuthUser,\n\t\tprivate readonly allowSignup: boolean\n\t) {}\n\n\tasync sendMagicLink(\n\t\temail: string,\n\t\tcallbackUrl: string\n\t): Promise<\n\t\t{ ok: true } | { ok: false; reason: 'rate_limited' | 'signup_disabled' | 'invalid_email' }\n\t> {\n\t\tconst { error } = await this.anon.auth.signInWithOtp({\n\t\t\temail,\n\t\t\toptions: {\n\t\t\t\temailRedirectTo: callbackUrl,\n\t\t\t\tshouldCreateUser: this.allowSignup\n\t\t\t}\n\t\t});\n\t\tif (!error) return { ok: true };\n\n\t\t// Anything we don't recognize, throw — the route returns 500 with a\n\t\t// stack trace instead of us swallowing a real bug as \"rate limited\".\n\t\tconst status = (error as { status?: number }).status;\n\t\tconst code = (error as { code?: string }).code;\n\t\tconst message = error.message ?? '';\n\t\tif (status === 429 || /rate.?limit/i.test(message))\n\t\t\treturn { ok: false, reason: 'rate_limited' };\n\t\tif (\n\t\t\tcode === 'otp_disabled' ||\n\t\t\tcode === 'signup_disabled' ||\n\t\t\t/signup.*disabled/i.test(message)\n\t\t) {\n\t\t\treturn { ok: false, reason: 'signup_disabled' };\n\t\t}\n\t\tif (code === 'validation_failed' || /invalid.*email|email.*invalid/i.test(message)) {\n\t\t\treturn { ok: false, reason: 'invalid_email' };\n\t\t}\n\t\tthrow error;\n\t}\n\n\tasync verifyMagicLink(rawCallbackUrl: string): Promise<{\n\t\tuser: AuthUser;\n\t\tsessionToken: string;\n\t\trefreshToken?: string;\n\t} | null> {\n\t\tconst params = parseCallbackParams(rawCallbackUrl);\n\t\tif (!params) return null;\n\t\tconst { tokenHash, type } = params;\n\n\t\tconst { data, error } = await this.anon.auth.verifyOtp({\n\t\t\ttoken_hash: tokenHash,\n\t\t\ttype\n\t\t});\n\t\tif (error || !data.user || !data.session) return null;\n\t\tif (isDisabled(data.user)) return null;\n\t\treturn {\n\t\t\tuser: this.hydrate(data.user),\n\t\t\tsessionToken: data.session.access_token,\n\t\t\trefreshToken: data.session.refresh_token\n\t\t};\n\t}\n}\n\n/**\n * Pull `token_hash` + `type` from either a full callback URL or a bare\n * `token_hash=…&type=…` query string. Tolerant of both shapes so the route\n * layer can pass whichever form is convenient.\n *\n * Returns null when the inputs aren't recognizable — the caller treats null\n * as \"send the user back to /login\".\n */\nfunction parseCallbackParams(\n\traw: string\n): { tokenHash: string; type: 'magiclink' | 'email' | 'signup' | 'invite' | 'recovery' } | null {\n\tlet search: URLSearchParams;\n\ttry {\n\t\tsearch = new URL(raw).searchParams;\n\t} catch {\n\t\tsearch = new URLSearchParams(raw.startsWith('?') ? raw.slice(1) : raw);\n\t}\n\tconst tokenHash = search.get('token_hash');\n\tconst type = search.get('type');\n\tif (!tokenHash) return null;\n\tconst allowed = new Set(['magiclink', 'email', 'signup', 'invite', 'recovery']);\n\tif (!type || !allowed.has(type)) return null;\n\treturn {\n\t\ttokenHash,\n\t\ttype: type as 'magiclink' | 'email' | 'signup' | 'invite' | 'recovery'\n\t};\n}\n","import { randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { ProviderError } from '@selvajs/platform';\n\n/**\n * Allowlist row. Identity-only — per-user app state (permissions, profile,\n * starred definitions) lives in `user-data.json` owned by whatever data\n * provider is paired with this auth provider.\n *\n * The UPN is the lookup key the upstream proxy will send back on every\n * subsequent request. `email` and `displayName` start empty when an admin\n * pre-allowlists; they get filled in on the user's first visit from the\n * matching headers (one-time materialization).\n */\nexport interface AllowlistEntry {\n\tid: string;\n\t/** User Principal Name — case-folded for storage and lookup. */\n\tupn: string;\n\temail?: string;\n\tdisplayName?: string;\n\tcreatedAt: string;\n\tlastLoginAt?: string;\n\tdisabled?: boolean;\n\t/**\n\t * The proxy UPN that last signed in to this row, case-folded. Only that UPN\n\t * gets in through the email fallback; a UPN equal to `upn` always gets in and\n\t * takes the claim. Unset on a row nobody has signed in to yet, and on rows from\n\t * before the field existed: their next sign-in sets it.\n\t */\n\tclaimedByUpn?: string;\n}\n\ninterface AllowlistFile {\n\tusers: AllowlistEntry[];\n}\n\nconst empty = (): AllowlistFile => ({ users: [] });\n\nconst LAST_LOGIN_DEBOUNCE_MS = 60_000;\n\nasync function readFile(filePath: string): Promise<AllowlistFile> {\n\ttry {\n\t\tconst raw = await fs.readFile(filePath, 'utf-8');\n\t\treturn JSON.parse(raw) as AllowlistFile;\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === 'ENOENT') return empty();\n\t\tthrow err;\n\t}\n}\n\nasync function writeFile(filePath: string, data: AllowlistFile): Promise<void> {\n\tawait fs.mkdir(path.dirname(filePath), { recursive: true });\n\tconst tmp = `${filePath}.tmp`;\n\tawait fs.writeFile(tmp, JSON.stringify(data, null, '\\t'), 'utf-8');\n\tawait fs.rename(tmp, filePath);\n}\n\nexport interface AllowlistStore {\n\tfindByUpn(upn: string): Promise<AllowlistEntry | null>;\n\t/**\n\t * Look up by email rather than UPN. Used as a fallback on first login when\n\t * the proxy forwards a UPN that differs from the email an admin used to\n\t * pre-allowlist the user (common on Entra: UPN `x@tenant.onmicrosoft.com`\n\t * vs mail `x@company.com`). Without this, the UPN miss orphans the\n\t * org-member row that was keyed to the allowlist UUID at provision time.\n\t */\n\tfindByEmail(email: string): Promise<AllowlistEntry | null>;\n\tfindById(id: string): Promise<AllowlistEntry | null>;\n\tlistUsers(): Promise<AllowlistEntry[]>;\n\tcreateUser(upn: string): Promise<AllowlistEntry>;\n\t/**\n\t * Mirror identity fields from upstream-proxy headers. The proxy/IdP is the\n\t * source of truth for email and display name: a stored value is replaced\n\t * whenever the forwarded header differs, so IdP-side renames — and fixes to\n\t * a misconfigured proxy that used to forward the wrong claim (e.g. the OIDC\n\t * `sub` as display name) — heal the row on the user's next visit. An absent\n\t * header leaves the stored value untouched; hand-edits to these two fields\n\t * in the allowlist JSON do not survive the user's next login.\n\t */\n\tsyncFromHeaders(id: string, fields: { email?: string; displayName?: string }): Promise<void>;\n\t/**\n\t * Record `upn` as the row's claimant if it has none, or over the current one\n\t * with `replace`, and return the claimant now stored (null for a missing row).\n\t * Concurrent first sign-ins resolve to whichever wrote first.\n\t */\n\tclaim(id: string, upn: string, opts?: { replace?: boolean }): Promise<string | null>;\n\t/**\n\t * Repoint a row's UPN and claimant — for an operator correcting an allowlist\n\t * entry after a directory-side rename. No-ops if the new UPN already belongs\n\t * to a different row (a collision means manual operator cleanup — never\n\t * silently merge). Never called from `identifyFromHeaders`: headers don't\n\t * get to rewrite a claimed identity.\n\t */\n\trebindUpn(id: string, upn: string): Promise<void>;\n\tsetDisabled(id: string, disabled: boolean): Promise<void>;\n\ttouchLastLogin(id: string): Promise<void>;\n\tdeleteUser(id: string): Promise<void>;\n}\n\nexport function createAllowlistStore(filePath: string): AllowlistStore {\n\tconst norm = (upn: string) => upn.trim().toLowerCase();\n\n\t// Every writer rewrites the whole file through one temp name, so two at once lose\n\t// an entry or fail the rename with ENOENT.\n\tlet queue: Promise<unknown> = Promise.resolve();\n\tfunction locked<T>(fn: () => Promise<T>): Promise<T> {\n\t\tconst next = queue.then(fn, fn);\n\t\tqueue = next.catch(() => {});\n\t\treturn next;\n\t}\n\n\treturn {\n\t\tasync findByUpn(upn) {\n\t\t\tconst { users } = await readFile(filePath);\n\t\t\tconst key = norm(upn);\n\t\t\treturn users.find((u) => u.upn === key) ?? null;\n\t\t},\n\n\t\tasync findByEmail(email) {\n\t\t\tconst { users } = await readFile(filePath);\n\t\t\tconst key = norm(email);\n\t\t\t// Admins pre-allowlist via `createUser(email)`, which stores the email\n\t\t\t// AS the upn. The `email` column is not searched: proxy headers write\n\t\t\t// it, so it would hand a reassigned address to the departed holder.\n\t\t\treturn users.find((u) => u.upn === key) ?? null;\n\t\t},\n\n\t\tasync findById(id) {\n\t\t\tconst { users } = await readFile(filePath);\n\t\t\treturn users.find((u) => u.id === id) ?? null;\n\t\t},\n\n\t\tasync listUsers() {\n\t\t\tconst { users } = await readFile(filePath);\n\t\t\treturn users;\n\t\t},\n\n\t\tcreateUser(upn) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst key = norm(upn);\n\t\t\t\tif (file.users.some((u) => u.upn === key)) {\n\t\t\t\t\tthrow new ProviderError(`User with UPN \"${upn}\" already exists`, 409);\n\t\t\t\t}\n\t\t\t\tconst entry: AllowlistEntry = {\n\t\t\t\t\tid: randomUUID(),\n\t\t\t\t\tupn: key,\n\t\t\t\t\tcreatedAt: new Date().toISOString()\n\t\t\t\t};\n\t\t\t\tfile.users.push(entry);\n\t\t\t\tawait writeFile(filePath, file);\n\t\t\t\treturn entry;\n\t\t\t});\n\t\t},\n\n\t\tsyncFromHeaders(id, fields) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\t\tif (!user) return;\n\t\t\t\tlet dirty = false;\n\t\t\t\tif (fields.email && user.email !== fields.email) {\n\t\t\t\t\tuser.email = fields.email;\n\t\t\t\t\tdirty = true;\n\t\t\t\t}\n\t\t\t\tif (fields.displayName && user.displayName !== fields.displayName) {\n\t\t\t\t\tuser.displayName = fields.displayName;\n\t\t\t\t\tdirty = true;\n\t\t\t\t}\n\t\t\t\tif (dirty) await writeFile(filePath, file);\n\t\t\t});\n\t\t},\n\n\t\tclaim(id, upn, opts) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\t\tif (!user) return null;\n\t\t\t\tconst key = norm(upn);\n\t\t\t\tif (!user.claimedByUpn || (opts?.replace && user.claimedByUpn !== key)) {\n\t\t\t\t\tuser.claimedByUpn = key;\n\t\t\t\t\tawait writeFile(filePath, file);\n\t\t\t\t}\n\t\t\t\treturn user.claimedByUpn;\n\t\t\t});\n\t\t},\n\n\t\trebindUpn(id, upn) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst key = norm(upn);\n\t\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\t\tif (!user || (user.upn === key && user.claimedByUpn === key)) return;\n\t\t\t\t// Don't merge into an existing row — a UPN collision is an operator\n\t\t\t\t// data issue, not something to paper over by reassigning identity.\n\t\t\t\tif (file.users.some((u) => u.id !== id && u.upn === key)) return;\n\t\t\t\tuser.upn = key;\n\t\t\t\tuser.claimedByUpn = key;\n\t\t\t\tawait writeFile(filePath, file);\n\t\t\t});\n\t\t},\n\n\t\tsetDisabled(id, disabled) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\t\tif (!user) throw new ProviderError(`User \"${id}\" not found`, 404);\n\t\t\t\tuser.disabled = disabled;\n\t\t\t\tawait writeFile(filePath, file);\n\t\t\t});\n\t\t},\n\n\t\ttouchLastLogin(id) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst user = file.users.find((u) => u.id === id);\n\t\t\t\tif (!user) return;\n\t\t\t\tconst now = Date.now();\n\t\t\t\tif (user.lastLoginAt) {\n\t\t\t\t\tconst prev = Date.parse(user.lastLoginAt);\n\t\t\t\t\tif (Number.isFinite(prev) && now - prev < LAST_LOGIN_DEBOUNCE_MS) return;\n\t\t\t\t}\n\t\t\t\tuser.lastLoginAt = new Date(now).toISOString();\n\t\t\t\tawait writeFile(filePath, file);\n\t\t\t});\n\t\t},\n\n\t\tdeleteUser(id) {\n\t\t\treturn locked(async () => {\n\t\t\t\tconst file = await readFile(filePath);\n\t\t\t\tconst before = file.users.length;\n\t\t\t\tfile.users = file.users.filter((u) => u.id !== id);\n\t\t\t\tif (file.users.length === before) throw new ProviderError(`User \"${id}\" not found`, 404);\n\t\t\t\tawait writeFile(filePath, file);\n\t\t\t});\n\t\t}\n\t};\n}\n","import * as path from 'node:path';\nimport type {\n\tIAuthProvider,\n\tIProxyAuth,\n\tAuthUser,\n\tUserManagementResult,\n\tListOptions,\n\tPage\n} from '@selvajs/platform';\nimport {\n\tNoopLogger,\n\tProviderError,\n\tclampPageLimit,\n\tdecodeOffsetCursor,\n\tencodeOffsetCursor,\n\ttype ILogger\n} from '@selvajs/platform';\nimport { createAllowlistStore } from './users.js';\nimport type { AllowlistStore, AllowlistEntry } from './users.js';\n\n// ============================================================================\n// HeaderAuthProvider — forward-auth via trusted upstream proxy\n// ============================================================================\n//\n// ⚠ TRUST BOUNDARY ⚠\n//\n// This provider trusts the headers it reads from incoming requests. That is\n// only safe when the deployment guarantees:\n//\n// 1. A reverse proxy (Caddy `forward_auth`, oauth2-proxy, Authelia, …) is\n// the ONLY network path to the app process. Bind to 127.0.0.1 or\n// firewall the port.\n// 2. The proxy authenticates against the upstream IdP before forwarding.\n// 3. The proxy STRIPS any client-supplied copies of the trusted headers\n// from inbound requests before adding its own.\n//\n// If any of those fails, anyone on the network can spoof the headers and\n// become anyone. The working Caddy config is in\n// docs/self-hosting/providers/header-auth-entra.md; the curl-based self-test\n// is in README.md.\n//\n// One of the three is partly self-detecting: a proxy that doesn't strip (3)\n// leaves two values in the UPN header, which `identifyFromHeaders` refuses\n// with a warning naming the cause. Nothing detects a breach of (1) — a\n// request reaching the process directly carries one clean header and is\n// indistinguishable from a proxied one. Closing that needs a shared secret\n// between proxy and app, deliberately not added: it is a second control over\n// the same failure, and an operator who misconfigured header stripping is no\n// likelier to have configured a secret correctly. Network isolation is the\n// control; the deployment IS the security boundary.\n// ============================================================================\n\ninterface HeaderNames {\n\tupn: string;\n\temail: string;\n\tdisplayName: string;\n}\n\nconst DEFAULT_HEADERS: HeaderNames = {\n\tupn: 'SELVA-UserPrincipalName',\n\temail: 'SELVA-Email',\n\tdisplayName: 'SELVA-DisplayName'\n};\n\n/**\n * Decides whether an unrecognized UPN coming through the proxy should be\n * auto-allowlisted as the bootstrap admin. Returning `true` lets the provider\n * create the allowlist row on the fly; returning `false` keeps the strict\n * \"must be pre-allowlisted\" behavior. The caller is responsible for narrowing\n * this to first-run + matching-email so the deployment can't be hijacked\n * after the initial setup.\n *\n * Pure: no I/O inside the callback. The hook layer that wires it up checks\n * `hasInstanceAdmin` and `BOOTSTRAP_INSTANCE_ADMIN_EMAIL` itself.\n */\nexport type BootstrapAllowlistPolicy = (params: {\n\tupn: string;\n\temail: string | undefined;\n}) => boolean | Promise<boolean>;\n\nexport interface HeaderAuthProviderConfig {\n\t/** Absolute path to the allowlist JSON file (e.g. `/data/header-allowlist.json`). */\n\tallowlistFilePath: string;\n\t/**\n\t * Header names the proxy sets. Defaults match the Caddyfile in\n\t * docs/self-hosting/providers/header-auth-entra.md\n\t * (`SELVA-UserPrincipalName`, `SELVA-Email`, `SELVA-DisplayName`). Override\n\t * to match a different proxy (e.g. oauth2-proxy sends the UPN as\n\t * `X-Auth-Request-Preferred-Username`; its `X-Auth-Request-User` is the OIDC `sub`).\n\t */\n\theaders?: Partial<HeaderNames>;\n\t/**\n\t * Optional bootstrap policy. When set AND the policy returns true for an\n\t * unrecognized UPN, the provider auto-allowlists that UPN before completing\n\t * identification. Used to break the chicken-and-egg on fresh deployments\n\t * where no admin exists yet. The caller must scope this tightly — see\n\t * `BootstrapAllowlistPolicy`.\n\t */\n\tbootstrapAllowlistPolicy?: BootstrapAllowlistPolicy;\n\t/**\n\t * Structured logger for proxy-misconfiguration diagnostics. Optional; defaults\n\t * to `NoopLogger` so this library stays silent unless the app wires one in.\n\t */\n\tlogger?: ILogger;\n}\n\nfunction toAuthUser(u: AllowlistEntry): AuthUser {\n\treturn {\n\t\tid: u.id,\n\t\t// Pre-first-login rows have no materialized email yet — the UPN is what\n\t\t// the admin typed when allowlisting (their email, for Entra/M365) and is\n\t\t// the only human-readable identifier available. Fall back so user lists\n\t\t// show an address instead of a bare UUID until the real email arrives\n\t\t// via header materialization.\n\t\temail: u.email ?? u.upn,\n\t\tmetadata: { upn: u.upn, displayName: u.displayName },\n\t\tcreatedAt: u.createdAt,\n\t\tlastLoginAt: u.lastLoginAt,\n\t\tdisabled: u.disabled\n\t};\n}\n\nclass HeaderProxyAuth implements IProxyAuth {\n\tprivate bootstrapPolicy: BootstrapAllowlistPolicy | undefined;\n\t// One-shot diagnostic flag. Flipped the first time we see a request that\n\t// carries none of the configured SELVA-* headers, so deploys with a\n\t// misconfigured proxy get a single loud warning in the logs without\n\t// spamming on every anonymous request. Reset is intentional — the\n\t// process restarts and you see the warning again next deploy.\n\tprivate missingHeadersWarned = false;\n\n\t// Same one-shot treatment for the opposite misconfiguration: identity\n\t// headers arriving more than once per request.\n\tprivate duplicateUpnWarned = false;\n\tprivate duplicateEmailWarned = false;\n\tprivate claimWriteWarned = false;\n\n\tconstructor(\n\t\tprivate readonly users: AllowlistStore,\n\t\tprivate readonly headers: HeaderNames,\n\t\tbootstrapPolicy: BootstrapAllowlistPolicy | undefined,\n\t\tprivate readonly logger: ILogger = new NoopLogger()\n\t) {\n\t\tthis.bootstrapPolicy = bootstrapPolicy;\n\t}\n\n\tsetBootstrapPolicy(policy: BootstrapAllowlistPolicy | null): void {\n\t\tthis.bootstrapPolicy = policy ?? undefined;\n\t}\n\n\t/**\n\t * Names of the configured identity headers, in priority order. Exposed so\n\t * the hook layer can emit per-page diagnostics (\"you hit /login without\n\t * these headers\") without having to know provider internals.\n\t */\n\tget configuredHeaderNames(): readonly string[] {\n\t\treturn [this.headers.upn, this.headers.email, this.headers.displayName];\n\t}\n\n\t/** True iff none of the configured identity headers are present. */\n\thasNoIdentityHeaders(headers: Headers): boolean {\n\t\treturn (\n\t\t\t!headers.get(this.headers.upn) &&\n\t\t\t!headers.get(this.headers.email) &&\n\t\t\t!headers.get(this.headers.displayName)\n\t\t);\n\t}\n\n\t/**\n\t * The email header, or undefined when it carries more than one value. Email\n\t * can select a row through the fallback, so a joined value (a proxy appending\n\t * its copy to the client's) is the same spoofing signal as on the UPN.\n\t */\n\tprivate singleValuedEmail(headers: Headers): string | undefined {\n\t\tconst email = headers.get(this.headers.email)?.trim() || undefined;\n\t\tif (!email?.includes(',')) return email;\n\t\tif (!this.duplicateEmailWarned) {\n\t\t\tthis.duplicateEmailWarned = true;\n\t\t\tthis.logger.warn(\n\t\t\t\t'Multiple values arrived in the email identity header on one request. The ' +\n\t\t\t\t\t'forward-auth proxy is not stripping client-supplied copies of the trusted ' +\n\t\t\t\t\t'headers. Ignoring the email header. Strip the configured headers at site ' +\n\t\t\t\t\t'scope, above forward_auth — see the @selvajs/header-auth-provider README.',\n\t\t\t\t{ component: 'HeaderAuth', header: this.headers.email }\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Claims the row, or returns null when the allowlist can't be written. A failed\n\t * claim must not fail the sign-in: that would lock every unclaimed user out of\n\t * a deployment whose allowlist is read-only or has the wrong owner. The row\n\t * then stays unclaimed, and the email fallback still admits any UPN to it.\n\t */\n\tprivate async tryClaim(id: string, upn: string, replace: boolean): Promise<string | null> {\n\t\ttry {\n\t\t\treturn await this.users.claim(id, upn, { replace });\n\t\t} catch (err) {\n\t\t\tif (!this.claimWriteWarned) {\n\t\t\t\tthis.claimWriteWarned = true;\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t'Could not record which UPN signed in to an allowlisted user: the allowlist ' +\n\t\t\t\t\t\t'file is not writable. Sign-in continues, but until it is writable the email ' +\n\t\t\t\t\t\t'header can still select any user whose UPN is an address.',\n\t\t\t\t\t{ component: 'HeaderAuth', userId: id, code: (err as NodeJS.ErrnoException).code }\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tasync identifyFromHeaders(headers: Headers): Promise<AuthUser | null> {\n\t\tconst upn = headers.get(this.headers.upn);\n\t\tif (!upn || !upn.trim()) {\n\t\t\t// Distinguish \"proxy never touched this request\" (no SELVA-* headers\n\t\t\t// at all → forward-auth misconfigured or being bypassed) from \"proxy\n\t\t\t// is here but didn't populate UPN\" (one of the other SELVA-* headers\n\t\t\t// arrived). The first case is the silent-failure mode operators\n\t\t\t// struggle to diagnose, so we log it once per process.\n\t\t\tif (!this.missingHeadersWarned && this.hasNoIdentityHeaders(headers)) {\n\t\t\t\tthis.missingHeadersWarned = true;\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t'No identity headers received on the first non-authed request. ' +\n\t\t\t\t\t\t'If you reach the app through your forward-auth proxy, this means the proxy is not ' +\n\t\t\t\t\t\t'forwarding the configured headers — check your forward_auth / copy_headers config. ' +\n\t\t\t\t\t\t\"If you're hitting the app directly (bypassing the proxy), bind the process to \" +\n\t\t\t\t\t\t'127.0.0.1 and only reach it through the proxy. See @selvajs/header-auth-provider README',\n\t\t\t\t\t{\n\t\t\t\t\t\tcomponent: 'HeaderAuth',\n\t\t\t\t\t\texpectedHeaders: [this.headers.upn, this.headers.email, this.headers.displayName]\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\t// A UPN header carrying more than one value means the proxy is not\n\t\t// stripping client-supplied copies before adding its own: `Headers.get`\n\t\t// joins repeats with \", \", so a spoofing attempt arrives as\n\t\t// \"attacker@x.com, real@y.com\". A UPN is a single directory identifier\n\t\t// and never contains a comma, so this can only be the duplicate case.\n\t\t//\n\t\t// The lookup below would miss anyway — no allowlisted UPN has a comma —\n\t\t// so refusing here changes no outcome. What it adds is a named cause in\n\t\t// the logs for a failure that otherwise looks like \"user not\n\t\t// allowlisted\", which is what makes this misconfiguration so hard to\n\t\t// diagnose. Checked on the UPN only: display names legitimately contain\n\t\t// commas (\"Doe, Jane\" is standard Entra formatting).\n\t\tif (upn.includes(',')) {\n\t\t\tif (!this.duplicateUpnWarned) {\n\t\t\t\tthis.duplicateUpnWarned = true;\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t'Multiple values arrived in the UPN identity header on one request. The ' +\n\t\t\t\t\t\t'forward-auth proxy is not stripping client-supplied copies of the trusted ' +\n\t\t\t\t\t\t'headers before setting its own, so a visitor can submit their own identity ' +\n\t\t\t\t\t\t'alongside the real one. Refusing to identify. Strip the configured headers at ' +\n\t\t\t\t\t\t'site scope, above forward_auth — see the @selvajs/header-auth-provider README.',\n\t\t\t\t\t{ component: 'HeaderAuth', header: this.headers.upn }\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\tconst email = this.singleValuedEmail(headers);\n\t\tconst displayName = headers.get(this.headers.displayName)?.trim() || undefined;\n\n\t\tlet entry = await this.users.findByUpn(upn);\n\t\tlet matchedByUpn = entry !== null;\n\n\t\t// Fallback: the proxy's UPN didn't match, but an admin may have\n\t\t// pre-allowlisted this person by EMAIL (Entra UPN ≠ mail is common).\n\t\t// Adopt that row so the org membership + permissions provisioned\n\t\t// against its UUID survive. The claim check below keeps this to the\n\t\t// UPN that claimed the row.\n\t\tif (!entry && email) {\n\t\t\tconst byEmail = await this.users.findByEmail(email);\n\t\t\tif (byEmail) entry = byEmail;\n\t\t}\n\n\t\t// Bootstrap path: when there's no allowlist row yet AND a bootstrap\n\t\t// policy is configured AND it green-lights this UPN, create the row.\n\t\t// The policy owner (the hook layer) is responsible for restricting\n\t\t// this to first-run + matching-email so the deployment can't be\n\t\t// hijacked once admin exists.\n\t\tif (!entry && this.bootstrapPolicy) {\n\t\t\tconst allowed = await this.bootstrapPolicy({ upn, email });\n\t\t\tif (allowed) {\n\t\t\t\ttry {\n\t\t\t\t\tentry = await this.users.createUser(upn);\n\t\t\t\t} catch {\n\t\t\t\t\t// Race: another concurrent request beat us to it. Re-read.\n\t\t\t\t\tentry = await this.users.findByUpn(upn);\n\t\t\t\t}\n\t\t\t\tmatchedByUpn = entry !== null;\n\t\t\t}\n\t\t}\n\n\t\tif (!entry || entry.disabled) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// A sign-in claims its row for its UPN, and the email fallback admits only\n\t\t// that UPN. Without this, the fallback would hand any row whose UPN is an\n\t\t// address (most of them, on Entra) to whoever presents that address in the\n\t\t// email header. A UPN equal to the row's own is the identity the operator\n\t\t// allowlisted, so it always gets in and takes the claim: that keeps a UPN\n\t\t// cleanup working, and evicts anyone who claimed the row with a spoofed email.\n\t\tconst presented = upn.trim().toLowerCase();\n\t\tlet claimant = entry.claimedByUpn;\n\t\tif (!claimant || (matchedByUpn && claimant !== presented)) {\n\t\t\tclaimant = (await this.tryClaim(entry.id, upn, matchedByUpn)) ?? undefined;\n\t\t}\n\t\t// Logged on every refusal, not once: each names a different locked-out user\n\t\t// or a probe of the email fallback, and the operator needs to see which.\n\t\tif (claimant && claimant !== presented) {\n\t\t\tthis.logger.warn(\n\t\t\t\t'Refused a sign-in to an allowlisted user already claimed by a different UPN. ' +\n\t\t\t\t\t\"If that user's UPN changed in the directory, set upn on their row in the \" +\n\t\t\t\t\t'allowlist file to the new one; their next sign-in claims it.',\n\t\t\t\t{ component: 'HeaderAuth', userId: entry.id }\n\t\t\t);\n\t\t\treturn null;\n\t\t}\n\n\t\t// Mirror email / display-name from the proxy whenever they drift. The\n\t\t// IdP is the source of truth, so IdP renames and corrected proxy\n\t\t// header mappings propagate on the next visit instead of the first\n\t\t// materialized value sticking forever.\n\t\tif ((email && entry.email !== email) || (displayName && entry.displayName !== displayName)) {\n\t\t\tawait this.users.syncFromHeaders(entry.id, { email, displayName }).catch(() => {});\n\t\t\tif (email) entry.email = email;\n\t\t\tif (displayName) entry.displayName = displayName;\n\t\t}\n\n\t\tawait this.users.touchLastLogin(entry.id).catch(() => {});\n\t\treturn toAuthUser(entry);\n\t}\n}\n\nexport class HeaderAuthProvider implements IAuthProvider {\n\tprivate readonly users: AllowlistStore;\n\tprivate readonly headers: HeaderNames;\n\n\treadonly name = 'Header (Forward Auth)';\n\treadonly proxyAuth: IProxyAuth;\n\n\tconstructor(config: HeaderAuthProviderConfig) {\n\t\tthis.users = createAllowlistStore(config.allowlistFilePath);\n\t\tthis.headers = { ...DEFAULT_HEADERS, ...config.headers };\n\t\tthis.proxyAuth = new HeaderProxyAuth(\n\t\t\tthis.users,\n\t\t\tthis.headers,\n\t\t\tconfig.bootstrapAllowlistPolicy,\n\t\t\tconfig.logger ?? new NoopLogger()\n\t\t);\n\t}\n\n\t/**\n\t * Late-bind a bootstrap-allowlist policy. Useful when the policy needs\n\t * runtime state the platform layer owns (e.g. `hasInstanceAdmin`) and\n\t * therefore can't be wired up at provider construction time. Pass `null`\n\t * to clear.\n\t */\n\tsetBootstrapAllowlistPolicy(policy: BootstrapAllowlistPolicy | null): void {\n\t\t(this.proxyAuth as HeaderProxyAuth).setBootstrapPolicy(policy);\n\t}\n\n\tstatic fromEnv(env: Record<string, string | undefined>, logger?: ILogger): HeaderAuthProvider {\n\t\tconst dir = env.HEADER_AUTH_DATA_DIR ?? env.DATA_PATH;\n\t\tif (!dir) {\n\t\t\tthrow new Error(\n\t\t\t\t'Missing required env var: HEADER_AUTH_DATA_DIR (or DATA_PATH as fallback). ' +\n\t\t\t\t\t'This directory holds header-allowlist.json — the pre-provisioned UPN list.'\n\t\t\t);\n\t\t}\n\t\treturn new HeaderAuthProvider({\n\t\t\tallowlistFilePath: path.join(dir, 'header-allowlist.json'),\n\t\t\theaders: {\n\t\t\t\tupn: env.HEADER_AUTH_UPN_HEADER ?? DEFAULT_HEADERS.upn,\n\t\t\t\temail: env.HEADER_AUTH_EMAIL_HEADER ?? DEFAULT_HEADERS.email,\n\t\t\t\tdisplayName: env.HEADER_AUTH_DISPLAY_NAME_HEADER ?? DEFAULT_HEADERS.displayName\n\t\t\t},\n\t\t\tlogger\n\t\t});\n\t}\n\n\t/**\n\t * No tokens are issued by this provider — identity rides on every request\n\t * via the trusted-proxy headers. Always returns null; the hook layer\n\t * falls through to `proxyAuth.identifyFromHeaders`.\n\t */\n\tasync verifyToken(_token: string): Promise<AuthUser | null> {\n\t\treturn null;\n\t}\n\n\tasync getUser(id: string): Promise<AuthUser | null> {\n\t\tconst u = await this.users.findById(id);\n\t\treturn u ? toAuthUser(u) : null;\n\t}\n\n\tasync listUsers(opts?: ListOptions): Promise<Page<AuthUser> | null> {\n\t\tconst all = await this.users.listUsers();\n\t\tconst limit = clampPageLimit(opts?.limit);\n\t\tconst offset = decodeOffsetCursor(opts?.cursor);\n\t\tconst slice = all.slice(offset, offset + limit).map(toAuthUser);\n\t\tconst nextOffset = offset + slice.length;\n\t\treturn {\n\t\t\titems: slice,\n\t\t\tnextCursor: nextOffset < all.length ? encodeOffsetCursor(nextOffset) : undefined\n\t\t};\n\t}\n\n\t/**\n\t * Allowlist a UPN. Admin POST `/api/admin/users` with `{ email }`; the\n\t * email IS the UPN for M365 / Entra deployments where they match. For\n\t * other IdPs, document the UPN format in your README/onboarding.\n\t */\n\tasync createUser(upn: string): Promise<AuthUser> {\n\t\treturn toAuthUser(await this.users.createUser(upn));\n\t}\n\n\tasync deleteUser(id: string): Promise<UserManagementResult> {\n\t\tconst target = await this.users.findById(id);\n\t\tif (!target) return 'not_found';\n\t\ttry {\n\t\t\tawait this.users.deleteUser(id);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync disableUser(id: string): Promise<UserManagementResult> {\n\t\tconst target = await this.users.findById(id);\n\t\tif (!target) return 'not_found';\n\t\ttry {\n\t\t\tawait this.users.setDisabled(id, true);\n\t\t\treturn 'ok';\n\t\t} catch (err) {\n\t\t\tif (err instanceof ProviderError && err.statusCode === 404) return 'not_found';\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync touchLastLogin(id: string): Promise<void> {\n\t\tawait this.users.touchLastLogin(id);\n\t}\n}\n","import { randomUUID } from 'node:crypto';\nimport type {\n\tIDataProvider,\n\tILogger,\n\tIStorageProvider,\n\tRequestContext,\n\tDefinitionRecord,\n\tDefinitionFileExt,\n\tDefinitionVersion,\n\tDocumentInventory,\n\tUpdateMetadataInput,\n\tUISchema\n} from '@selvajs/platform';\nimport { summarizeInventory } from '@selvajs/schemas';\nimport { savedValuesToRecord, type SavedValues } from './saved-values.js';\nimport {\n\tNoopLogger,\n\tProviderError,\n\tdefinitionPaths,\n\ttoSourceDocumentId,\n\twithCacheBust\n} from '@selvajs/platform';\n\nconst inventoryFields = (inventory: DocumentInventory | null | undefined) =>\n\tinventory ? { inventory, inventorySummary: summarizeInventory(inventory) } : {};\n\n/**\n * The values saved in an uploaded file: read already, or a read still running, whose values are\n * stored on the version once it lands. A failed read leaves none, and the render path reads them.\n */\nexport type UploadSavedValues = SavedValues | Promise<SavedValues> | null | undefined;\n\n// An empty read is not stored: Compute may have opened the file with a plugin missing, and a\n// stored `{}` would stop every later render from asking again.\nconst savedValuesField = (values: UploadSavedValues) =>\n\tvalues instanceof Map && values.size > 0 ? { savedValues: savedValuesToRecord(values) } : {};\n\n/**\n * Not the HTTP body — that's `CreateDefinitionInputSchema` in\n * `@selvajs/platform/definitions`, which has no guid/ownerId because those are\n * derived server-side.\n */\nexport interface CreateDefinitionRecord {\n\tguid: string;\n\tprojectId: string;\n\townerId: string;\n\tfileExt: DefinitionFileExt;\n\toriginalFilename?: string;\n\tdisplayName: string;\n\tdescription?: string;\n\tcategory?: string;\n\ttags?: string[];\n\tcoverImage?: string;\n\tcomputeServerId?: string;\n}\n\n/**\n * Orchestrates writes spanning IDataProvider + IStorageProvider. Application\n * orchestration, not platform contract — hence not in @selvajs/platform.\n *\n * Methods that write both metadata and blobs order the two so a mid-flight\n * failure leaves a state the API can still serve; those reasons sit inline at\n * each write. `publish` and `updateMeta` flip pointers/metadata only and touch\n * storage not at all.\n */\nexport class DefinitionService {\n\tconstructor(\n\t\tprivate data: IDataProvider,\n\t\tprivate storage: IStorageProvider,\n\t\tprivate logger: ILogger = new NoopLogger()\n\t) {}\n\n\tasync create(\n\t\tctx: RequestContext,\n\t\tinput: CreateDefinitionRecord,\n\t\tfile: Uint8Array,\n\t\tschema: UISchema,\n\t\tinventory?: DocumentInventory | null,\n\t\tsavedValues?: UploadSavedValues\n\t): Promise<{ record: DefinitionRecord; version: DefinitionVersion }> {\n\t\tconst now = new Date().toISOString();\n\t\tconst actor = ctx.userId || input.ownerId;\n\t\tconst record: DefinitionRecord = {\n\t\t\tguid: input.guid,\n\t\t\tprojectId: input.projectId,\n\t\t\townerId: input.ownerId,\n\t\t\tcreatedBy: actor,\n\t\t\tupdatedBy: actor,\n\t\t\tdisplayName: input.displayName,\n\t\t\tdescription: input.description,\n\t\t\tcategory: input.category,\n\t\t\ttags: input.tags,\n\t\t\tcoverImage: input.coverImage,\n\t\t\tcomputeServerId: input.computeServerId,\n\t\t\tstatus: 'pending',\n\t\t\tsolveCount: 0,\n\t\t\t// v1 is created below with versionNumber 1, so the next upload reserves 2.\n\t\t\tnextVersionNumber: 2,\n\t\t\tliveVersionId: null,\n\t\t\tdraftVersionId: null,\n\t\t\tsourceDocumentId: toSourceDocumentId(schema.documentId) ?? undefined,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t};\n\n\t\t// Metadata first — if this fails there's nothing to clean up.\n\t\tawait this.data.definitions.create(ctx, record);\n\n\t\t// If the blob write fails, the record stays 'pending' and is hidden from\n\t\t// default list queries.\n\t\tconst versionId = randomUUID();\n\t\tconst fileKey = definitionPaths.version(input.guid, 1, input.fileExt);\n\t\tawait this.storage.put(fileKey, file, 'application/octet-stream');\n\n\t\tconst version: DefinitionVersion = {\n\t\t\tid: versionId,\n\t\t\tdefinitionId: input.guid,\n\t\t\tversionNumber: 1,\n\t\t\tfileExt: input.fileExt,\n\t\t\tfileKey,\n\t\t\toriginalFilename: input.originalFilename,\n\t\t\tuploadedBy: actor,\n\t\t\tuploadedAt: now,\n\t\t\tschema,\n\t\t\tschemaExtractedAt: now,\n\t\t\t...inventoryFields(inventory),\n\t\t\t...savedValuesField(savedValues)\n\t\t};\n\t\tawait this.data.definitions.createVersion(ctx, version);\n\t\tthis.storeSavedValuesLater(ctx, versionId, savedValues);\n\n\t\t// Points both channels at v1 and flips status='draft' in ONE store\n\t\t// operation. Doing it as three writes leaves a partial state on failure:\n\t\t// status='draft' with null pointers, or 'pending' with pointers set.\n\t\tawait this.data.definitions.attachInitialVersion(ctx, input.guid, versionId);\n\n\t\treturn {\n\t\t\trecord: { ...record, status: 'draft', liveVersionId: versionId, draftVersionId: versionId },\n\t\t\tversion\n\t\t};\n\t}\n\n\t/**\n\t * Advances the draft pointer only — `live` is unchanged. Use `publish` to\n\t * promote.\n\t */\n\tasync uploadVersion(\n\t\tctx: RequestContext,\n\t\tguid: string,\n\t\tfile: Uint8Array,\n\t\text: DefinitionFileExt,\n\t\toriginalName: string,\n\t\tschema: UISchema,\n\t\tchangeNote?: string,\n\t\tinventory?: DocumentInventory | null,\n\t\tsavedValues?: UploadSavedValues\n\t): Promise<DefinitionVersion> {\n\t\tconst existing = await this.data.definitions.get(ctx, guid);\n\t\tif (!existing) throw new ProviderError(`Definition not found: ${guid}`, 404);\n\n\t\t// Monotonic counter, NOT max(existing)+1 — the latter reuses a number after\n\t\t// delete-latest and collides the `fileKey`, serving a stale blob for new\n\t\t// content.\n\t\tconst next = await this.data.definitions.reserveNextVersionNumber(ctx, guid);\n\n\t\tconst versionId = randomUUID();\n\t\tconst fileKey = definitionPaths.version(guid, next, ext);\n\t\tawait this.storage.put(fileKey, file, 'application/octet-stream');\n\n\t\tconst now = new Date().toISOString();\n\t\tconst actor = ctx.userId || existing.ownerId;\n\t\tconst version: DefinitionVersion = {\n\t\t\tid: versionId,\n\t\t\tdefinitionId: guid,\n\t\t\tversionNumber: next,\n\t\t\tfileExt: ext,\n\t\t\tfileKey,\n\t\t\toriginalFilename: originalName,\n\t\t\tuploadedBy: actor,\n\t\t\tuploadedAt: now,\n\t\t\tchangeNote: changeNote?.trim() || undefined,\n\t\t\tschema,\n\t\t\tschemaExtractedAt: now,\n\t\t\t...inventoryFields(inventory),\n\t\t\t...savedValuesField(savedValues)\n\t\t};\n\t\tawait this.data.definitions.createVersion(ctx, version);\n\t\tthis.storeSavedValuesLater(ctx, versionId, savedValues);\n\t\tawait this.data.definitions.setDraftVersion(ctx, guid, versionId);\n\t\t// A schema without a GUID leaves the old one: it says nothing about which file this is.\n\t\tconst sourceDocumentId = toSourceDocumentId(schema.documentId);\n\t\tif (sourceDocumentId && sourceDocumentId !== existing.sourceDocumentId) {\n\t\t\tawait this.data.definitions.update(ctx, guid, { sourceDocumentId });\n\t\t}\n\n\t\treturn version;\n\t}\n\n\t// Best-effort and after the response: a failed read or write leaves the version without\n\t// stored values, and the render path reads them from Compute instead.\n\tprivate storeSavedValuesLater(\n\t\tctx: RequestContext,\n\t\tversionId: string,\n\t\tvalues: UploadSavedValues\n\t): void {\n\t\tif (!(values instanceof Promise)) return;\n\t\tvalues\n\t\t\t.then((read) => {\n\t\t\t\tif (read.size === 0) return;\n\t\t\t\treturn this.data.definitions.setVersionSavedValues(\n\t\t\t\t\tctx,\n\t\t\t\t\tversionId,\n\t\t\t\t\tsavedValuesToRecord(read)\n\t\t\t\t);\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tthis.logger.warn('Saved values write failed', {\n\t\t\t\t\tcomponent: 'definitionService',\n\t\t\t\t\tversionId,\n\t\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t\t});\n\t\t\t});\n\t}\n\n\t/**\n\t * Moves the live channel to `versionId`, or to the current draft if omitted.\n\t * Any version id is accepted, so this rolls backward as well as forward.\n\t */\n\tasync publish(ctx: RequestContext, guid: string, versionId?: string): Promise<DefinitionVersion> {\n\t\tconst existing = await this.data.definitions.get(ctx, guid);\n\t\tif (!existing) throw new ProviderError(`Definition not found: ${guid}`, 404);\n\n\t\tconst target = versionId ?? existing.draftVersionId;\n\t\tif (!target) throw new ProviderError('No version to publish', 400);\n\n\t\tconst version = await this.data.definitions.getVersion(ctx, target);\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tthrow new ProviderError(`Version '${target}' not found for this definition`, 404);\n\t\t}\n\n\t\tawait this.data.definitions.setLiveVersion(ctx, guid, target);\n\t\t// Flip status to 'published' the first time live moves off pending/draft.\n\t\tif (existing.status === 'draft' || existing.status === 'pending') {\n\t\t\tawait this.data.definitions.update(ctx, guid, { status: 'published' });\n\t\t}\n\t\treturn version;\n\t}\n\n\tasync deleteVersion(ctx: RequestContext, guid: string, versionId: string): Promise<void> {\n\t\tconst version = await this.data.definitions.getVersion(ctx, versionId);\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tthrow new ProviderError(`Version '${versionId}' not found for this definition`, 404);\n\t\t}\n\t\t// Store enforces the live/draft reference check; if it throws, blob stays.\n\t\tawait this.data.definitions.deleteVersion(ctx, versionId);\n\t\tawait this.storage.delete(version.fileKey);\n\t}\n\n\tasync updateMeta(ctx: RequestContext, guid: string, patch: UpdateMetadataInput): Promise<void> {\n\t\tawait this.data.definitions.update(ctx, guid, patch);\n\t}\n\n\tasync saveCoverImage(ctx: RequestContext, guid: string, imageData: Uint8Array): Promise<string> {\n\t\tconst path = definitionPaths.image(guid);\n\t\tawait this.storage.put(path, imageData, 'image/webp');\n\t\t// Same path every time, so a new cover needs a new URL or caches keep the old one.\n\t\tconst url = withCacheBust(this.storage.getPublicUrl(path), Date.now());\n\t\tawait this.data.definitions.update(ctx, guid, { coverImage: url });\n\t\treturn url;\n\t}\n\n\tasync delete(ctx: RequestContext, guid: string): Promise<void> {\n\t\t// Metadata is soft-deleted (audit trail, restorable by clearing\n\t\t// `deleted_at`); blobs are HARD-deleted.\n\t\t//\n\t\t// Metadata first, so the API hides the record immediately. A failed blob\n\t\t// wipe then leaves orphan storage that no reader can reach, for a\n\t\t// retention sweep to collect. The reverse order leaves the record alive\n\t\t// with its blobs gone — a 404 for any in-flight reader.\n\t\tawait this.data.definitions.delete(ctx, guid);\n\t\tawait this.storage.deletePrefix(definitionPaths.prefix(guid));\n\t}\n}\n","import { createHash } from 'node:crypto';\nimport type { IOrgStore, IStorageProvider, OrgAssetKind, RequestContext } from '@selvajs/platform';\nimport { orgPaths, ProviderError, withCacheBust } from '@selvajs/platform';\n\n/**\n * Orchestrates org-asset writes that span IStorageProvider + IOrgStore — one\n * service for every asset kind (logo, favicon, …).\n *\n * Every upload is rasterized to WebP by the shared transcoder inside\n * `IStorageProvider.put`, so the stored blob is always\n * `orgs/{id}/branding/{kind}.webp` (the `branding/` segment marks the public\n * asset class — see `classifyAssetPath`). SVG inputs are flattened to a raster\n * of at most 1200px — no vector blob is persisted, which keeps the served bytes\n * XSS-free without a sanitizer. Re-uploads overwrite in place. The org's\n * `assets` map is the source of truth for which kinds exist and their public\n * URLs; we read-merge-write it so concurrent edits to *different* kinds don't\n * clobber each other within a kind.\n *\n * Re-uploads overwrite the same path, so the stored URL would be identical\n * across replaces and a cached browser/CDN would keep serving the old bytes.\n * The content-derived `?v=` token (`withCacheBust`) gives a *different* image a\n * *different* URL, while an identical re-upload keeps its URL and stays cached.\n */\nexport class OrgAssetService {\n\tconstructor(\n\t\tprivate orgs: IOrgStore,\n\t\tprivate storage: IStorageProvider\n\t) {}\n\n\t/**\n\t * Store `kind`'s blob and point the org's `assets[kind]` at its public URL.\n\t * `contentType` must be the *original* upload type (e.g. `image/svg+xml`) so\n\t * the transcoder recognizes the bytes as an image. Returns the public URL.\n\t */\n\tasync saveAsset(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tkind: OrgAssetKind,\n\t\tdata: Uint8Array,\n\t\tcontentType: string\n\t): Promise<string> {\n\t\tconst path = orgPaths.asset(orgId, kind);\n\t\tawait this.storage.put(path, data, contentType);\n\t\t// Content-derived token, not a timestamp: an identical re-upload to the\n\t\t// same path keeps the same URL and stays cached; a changed image gets a\n\t\t// new URL and refetches immediately. 8 hex chars is enough to distinguish\n\t\t// versions without bloating the URL.\n\t\tconst token = createHash('sha256').update(data).digest('hex').slice(0, 8);\n\t\tconst url = withCacheBust(this.storage.getPublicUrl(path), token);\n\t\tawait this.orgs.updateOrg(ctx, orgId, {\n\t\t\tassets: await this.mergedAssets(ctx, orgId, kind, url)\n\t\t});\n\t\treturn url;\n\t}\n\n\t/** Remove `kind`'s blob and drop it from the org's `assets` map. No-op-safe. */\n\tasync removeAsset(ctx: RequestContext, orgId: string, kind: OrgAssetKind): Promise<void> {\n\t\tawait this.storage.delete(orgPaths.asset(orgId, kind));\n\t\tawait this.orgs.updateOrg(ctx, orgId, {\n\t\t\tassets: await this.mergedAssets(ctx, orgId, kind, undefined)\n\t\t});\n\t}\n\n\t/**\n\t * Read the org's current `assets` and return a copy with `kind` set to `url`\n\t * (or removed when `url` is undefined). Keeps the other kinds intact.\n\t */\n\tprivate async mergedAssets(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tkind: OrgAssetKind,\n\t\turl: string | undefined\n\t): Promise<Record<string, string>> {\n\t\tconst org = await this.orgs.getOrg(ctx, orgId);\n\t\tif (!org) throw new ProviderError(`Org '${orgId}' not found`, 404);\n\t\tconst next = { ...(org.assets ?? {}) } as Record<string, string>;\n\t\tif (url === undefined) delete next[kind];\n\t\telse next[kind] = url;\n\t\treturn next;\n\t}\n}\n","/**\n * What an error tracker may receive: identifiers, never payloads. Applied to Sentry-shaped\n * events (`beforeSend`, `beforeSendTransaction`, `beforeBreadcrumb`) without importing Sentry,\n * so a host wires them into whichever SDK it runs, server or browser.\n *\n * No cookie, auth header, API key, request body or query string leaves: a query carries share\n * tokens and search text, a body definitions and inputs. A user is its id. Console breadcrumbs\n * stay local, since they can quote any of the above.\n */\n\n/** The parts of a Sentry event these read. Structural, so any SDK version's events fit. */\nexport interface ScrubbableEvent {\n\trequest?: {\n\t\turl?: string;\n\t\tcookies?: unknown;\n\t\tdata?: unknown;\n\t\tquery_string?: unknown;\n\t\theaders?: Record<string, string>;\n\t};\n\tuser?: { id?: string | number } & Record<string, unknown>;\n\tbreadcrumbs?: ScrubbableBreadcrumb[];\n\ttransaction?: string;\n\tspans?: { description?: string; data?: Record<string, unknown> }[];\n}\n\nexport interface ScrubbableBreadcrumb {\n\tcategory?: string;\n\tdata?: Record<string, unknown>;\n}\n\n// Headers that say what the request was, never who sent it.\nconst KEPT_HEADERS = new Set(['accept', 'content-type', 'content-length', 'user-agent']);\nconst URL_KEYS = ['url', 'to', 'from', 'http.url', 'server.address.full'];\n\n/** `https://h/p?q=1#f` → `https://h/p`; a relative path likewise. Anything else as it was. */\nexport function withoutQuery(url: string): string {\n\tconst cut = url.search(/[?#]/);\n\treturn cut === -1 ? url : url.slice(0, cut);\n}\n\nfunction scrubData(data: Record<string, unknown> | undefined): void {\n\tif (!data) return;\n\tfor (const key of URL_KEYS) {\n\t\tconst value = data[key];\n\t\tif (typeof value === 'string') data[key] = withoutQuery(value);\n\t}\n\tdelete data['http.query'];\n\tdelete data['http.fragment'];\n}\n\nexport function scrubBreadcrumb<B extends ScrubbableBreadcrumb>(crumb: B): B | null {\n\tif (crumb.category === 'console') return null;\n\tscrubData(crumb.data);\n\treturn crumb;\n}\n\n/** For `beforeSend` and `beforeSendTransaction` alike. Mutates and returns `event`. */\nexport function scrubEvent<E extends ScrubbableEvent>(event: E): E {\n\tconst request = event.request;\n\tif (request) {\n\t\tdelete request.cookies;\n\t\tdelete request.data;\n\t\tdelete request.query_string;\n\t\tif (request.url) request.url = withoutQuery(request.url);\n\t\tif (request.headers) {\n\t\t\trequest.headers = Object.fromEntries(\n\t\t\t\tObject.entries(request.headers).filter(([k]) => KEPT_HEADERS.has(k.toLowerCase()))\n\t\t\t);\n\t\t}\n\t}\n\tif (event.user) event.user = event.user.id === undefined ? {} : { id: event.user.id };\n\tif (event.breadcrumbs) {\n\t\tevent.breadcrumbs = event.breadcrumbs.flatMap((b) => scrubBreadcrumb(b) ?? []);\n\t}\n\tfor (const span of event.spans ?? []) {\n\t\tif (span.description) span.description = withoutQuery(span.description);\n\t\tscrubData(span.data);\n\t}\n\tif (event.transaction) event.transaction = withoutQuery(event.transaction);\n\treturn event;\n}\n\n/** A sample-rate env value → 0–1; unset or unreadable is 0, out of range clamped. */\nexport function sampleRate(raw: string | undefined): number {\n\tconst rate = Number(raw);\n\treturn raw !== undefined && Number.isFinite(rate) ? Math.min(1, Math.max(0, rate)) : 0;\n}\n","import type { ErrorContext, IErrorReporter } from '@selvajs/platform';\nimport { sampleRate, scrubBreadcrumb, scrubEvent } from './scrub.js';\n\n/**\n * `IErrorReporter` backed by Sentry. `@sentry/node` is an OPTIONAL peer dependency: a\n * deployment without a DSN never loads it, so the surface below is narrowed to the calls used\n * here and the import stays dynamic — a static one would make the package mandatory.\n *\n * A host that already runs a Sentry SDK (a framework one that also traces requests) hands it\n * to `fromClient` instead, so Sentry is initialized once.\n */\nexport interface SentryLike {\n\tcaptureException(\n\t\terror: unknown,\n\t\tcontext?: {\n\t\t\ttags?: Record<string, string>;\n\t\t\tuser?: { id?: string };\n\t\t\tlevel?: 'fatal' | 'error' | 'warning';\n\t\t\tfingerprint?: string[];\n\t\t}\n\t): unknown;\n}\n\ninterface SentryNodeLike extends SentryLike {\n\tinit(options: {\n\t\tdsn: string;\n\t\tenvironment?: string;\n\t\trelease?: string;\n\t\ttracesSampleRate: number;\n\t\ttraceLifecycle?: 'static' | 'stream';\n\t\tbeforeSend: typeof scrubEvent;\n\t\tbeforeSendTransaction: typeof scrubEvent;\n\t\tbeforeBreadcrumb: typeof scrubBreadcrumb;\n\t}): void;\n}\n\nexport class SentryErrorReporter implements IErrorReporter {\n\tprivate constructor(private readonly sentry: SentryLike) {}\n\n\t/** A reporter over an SDK the host initialized itself; it should pass `scrub.ts`'s hooks. */\n\tstatic fromClient(sentry: SentryLike): SentryErrorReporter {\n\t\treturn new SentryErrorReporter(sentry);\n\t}\n\n\t/**\n\t * Initialize `@sentry/node` with the scrubbing hooks and return a reporter, or `null` when\n\t * it won't load. Never throws — a broken error-tracker must not take down boot.\n\t */\n\tstatic async create(opts: {\n\t\tdsn: string;\n\t\tenvironment?: string;\n\t\trelease?: string;\n\t\t/** `SENTRY_TRACES_SAMPLE_RATE` as read from env; unset is 0, error tracking only. */\n\t\ttracesSampleRate?: string | number;\n\t}): Promise<SentryErrorReporter | null> {\n\t\ttry {\n\t\t\t// `@vite-ignore` stops the bundler resolving an absent package at build\n\t\t\t// time. `@ts-ignore` rather than `@ts-expect-error` because the module\n\t\t\t// is a real dep in some installs and missing in others, so we can't\n\t\t\t// assert the error is always there for `expect-error` to consume.\n\t\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t\t// @ts-ignore -- optional dependency, may be absent at type-check time\n\t\t\tconst sentry = (await import(/* @vite-ignore */ '@sentry/node')) as unknown as SentryNodeLike;\n\t\t\tsentry.init({\n\t\t\t\tdsn: opts.dsn,\n\t\t\t\tenvironment: opts.environment,\n\t\t\t\trelease: opts.release,\n\t\t\t\ttracesSampleRate:\n\t\t\t\t\ttypeof opts.tracesSampleRate === 'number'\n\t\t\t\t\t\t? sampleRate(String(opts.tracesSampleRate))\n\t\t\t\t\t\t: sampleRate(opts.tracesSampleRate),\n\t\t\t\t// Streamed spans skip beforeSendTransaction, so the scrubber would never see them.\n\t\t\t\ttraceLifecycle: 'static',\n\t\t\t\tbeforeSend: scrubEvent,\n\t\t\t\tbeforeSendTransaction: scrubEvent,\n\t\t\t\tbeforeBreadcrumb: scrubBreadcrumb\n\t\t\t});\n\t\t\treturn new SentryErrorReporter(sentry);\n\t\t} catch (err) {\n\t\t\tconsole.error(\n\t\t\t\t'[ErrorReporter] A Sentry DSN is set but @sentry/node could not be loaded. ' +\n\t\t\t\t\t'Install it (`pnpm add @sentry/node`) or unset the DSN. Falling back to no-op.',\n\t\t\t\terr\n\t\t\t);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tcapture(error: unknown, context?: ErrorContext): void {\n\t\ttry {\n\t\t\tconst tags: Record<string, string> = { ...context?.tags };\n\t\t\tif (context?.method) tags.method = context.method;\n\t\t\tif (context?.route) tags.route = context.route;\n\t\t\tif (context?.orgId) tags.orgId = context.orgId;\n\t\t\tif (context?.kind) tags.kind = context.kind;\n\t\t\tthis.sentry.captureException(error, {\n\t\t\t\ttags,\n\t\t\t\tuser: context?.userId ? { id: context.userId } : undefined,\n\t\t\t\t...(context?.level && { level: context.level }),\n\t\t\t\t// One issue per fault kind, split as Sentry would split it by stack.\n\t\t\t\t...(context?.kind && { fingerprint: ['{{ default }}', context.kind] })\n\t\t\t});\n\t\t} catch (err) {\n\t\t\t// Best-effort, and this sits on the error path — letting a second\n\t\t\t// failure escape would mask the first.\n\t\t\tconsole.error('[ErrorReporter] Failed to capture error:', err);\n\t\t}\n\t}\n}\n","import { readBool } from '../compute/limits.js';\n\nexport interface SmtpConfig {\n\thost: string;\n\tport: number;\n\tsecure: boolean;\n\tauth?: { user: string; pass: string };\n\tfrom: string;\n}\n\n/** The env vars this provider reads. The app passes `process.env` or its framework equivalent. */\nexport interface SmtpEnv {\n\tSMTP_HOST?: string;\n\tSMTP_PORT?: string;\n\tSMTP_USER?: string;\n\tSMTP_PASS?: string;\n\tSMTP_FROM?: string;\n\tSMTP_SECURE?: string;\n\t// Callers hand over a whole env bag (`process.env`, `$env/dynamic/private`),\n\t// which carries far more than these keys. Without this, an env bag typed as a\n\t// bare index signature has no declared property in common with an all-optional\n\t// interface, and TS's weak-type check rejects it at every call site.\n\t[key: string]: string | undefined;\n}\n\nfunction parsePort(raw: string | undefined): number {\n\tconst n = Number(raw ?? 587);\n\treturn Number.isInteger(n) && n > 0 && n < 65536 ? n : 587;\n}\n\n/**\n * Read SMTP settings from an env bag. Taken as a parameter rather than read\n * from `process.env` directly: under `vite dev` the framework does not mirror\n * `.env` into `process.env`, so the app must hand over its own resolved env\n * (`$env/dynamic/private` in SvelteKit) or overrides silently fall back to\n * defaults.\n *\n * Returns null when mail is not configured — the caller treats that as \"no\n * mail\", not as an error.\n *\n * Throws only when `SMTP_HOST` is set but `SMTP_FROM` is missing: that\n * combination is a half-finished config, and failing loudly beats silently\n * never sending. Every message needs an envelope sender, and guessing one\n * produces mail that fails SPF at the recipient.\n */\nexport function readSmtpConfig(env: SmtpEnv): SmtpConfig | null {\n\tconst host = env.SMTP_HOST?.trim();\n\tif (!host) return null;\n\n\tconst from = env.SMTP_FROM?.trim();\n\tif (!from) {\n\t\tthrow new Error('SMTP_HOST is set but SMTP_FROM is missing — mail needs a sender address.');\n\t}\n\n\tconst port = parsePort(env.SMTP_PORT);\n\tconst user = env.SMTP_USER?.trim();\n\tconst pass = env.SMTP_PASS;\n\n\treturn {\n\t\thost,\n\t\tport,\n\t\t// Port 465 is implicit TLS; 587 and 25 start plaintext and upgrade via\n\t\t// STARTTLS, which nodemailer does on its own when `secure` is false. Parsed\n\t\t// with the manifest's boolean words, so what `selva config show` reports runs.\n\t\tsecure: readBool({ SMTP_SECURE: env.SMTP_SECURE }, 'SMTP_SECURE', port === 465),\n\t\tauth: user && pass ? { user, pass } : undefined,\n\t\tfrom\n\t};\n}\n","import { createHmac, randomBytes } from 'node:crypto';\nimport {\n\tNoopLogger,\n\ttype ILogger,\n\ttype INotificationProvider,\n\ttype OutboundMessage,\n\ttype SendResult\n} from '@selvajs/platform';\nimport { readSmtpConfig, type SmtpEnv } from './smtp-config.js';\n\n// Per process: the hash only has to match up within one run of the logs.\nconst RECIPIENT_HASH_KEY = randomBytes(32);\n\nfunction recipientHash(to: string): string {\n\treturn createHmac('sha256', RECIPIENT_HASH_KEY).update(to).digest('hex').slice(0, 16);\n}\n\n/**\n * SMTP transport. Any server works — a transactional provider, an internal\n * relay, or a mailbox with an app password.\n *\n * Settings are read per send rather than cached, so a restart is the only\n * thing needed to reconfigure and a rotated password takes effect without\n * anyone remembering there is a cache.\n */\nexport class SmtpNotificationProvider implements INotificationProvider {\n\treadonly name = 'SMTP';\n\n\tconstructor(private readonly env: SmtpEnv) {}\n\n\tasync send(message: OutboundMessage, log: ILogger = new NoopLogger()): Promise<SendResult> {\n\t\tlet config;\n\t\ttry {\n\t\t\tconfig = readSmtpConfig(this.env);\n\t\t} catch (err) {\n\t\t\tlog.error('SMTP is misconfigured', {\n\t\t\t\tcomponent: 'SmtpNotificationProvider',\n\t\t\t\terror: err instanceof Error ? err.message : String(err)\n\t\t\t});\n\t\t\treturn { status: 'failed', reason: 'misconfigured' };\n\t\t}\n\t\tif (!config) return { status: 'not-configured' };\n\n\t\ttry {\n\t\t\t// Lazy: an instance with no SMTP_HOST never pays to load nodemailer.\n\t\t\tconst { createTransport } = await import('nodemailer');\n\t\t\tconst transport = createTransport({\n\t\t\t\thost: config.host,\n\t\t\t\tport: config.port,\n\t\t\t\tsecure: config.secure,\n\t\t\t\tauth: config.auth\n\t\t\t});\n\n\t\t\tawait transport.sendMail({\n\t\t\t\tfrom: config.from,\n\t\t\t\tto: message.to,\n\t\t\t\tsubject: message.subject,\n\t\t\t\ttext: message.text,\n\t\t\t\thtml: message.html\n\t\t\t});\n\t\t\treturn { status: 'sent' };\n\t\t} catch (err) {\n\t\t\t// Never the raw message: an SMTP rejection quotes the address, and erasure\n\t\t\t// can't reach stdout. The keyed hash still matches up failures to one person.\n\t\t\tconst { code, responseCode } = err as { code?: string; responseCode?: number };\n\t\t\tlog.warn('Failed to send mail', {\n\t\t\t\tcomponent: 'SmtpNotificationProvider',\n\t\t\t\trecipient: recipientHash(message.to),\n\t\t\t\tkind: message.kind,\n\t\t\t\tcode,\n\t\t\t\tresponseCode\n\t\t\t});\n\t\t\treturn { status: 'failed', reason: code ?? 'send-failed' };\n\t\t}\n\t}\n\n\tisConfigured(): boolean {\n\t\ttry {\n\t\t\treturn readSmtpConfig(this.env) !== null;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n}\n","import { composeManifest, defineSetting } from '@selvajs/platform/config';\n\nconst header = (key: string, fallback: string, slot: string) =>\n\tdefineSetting({\n\t\tkey,\n\t\tlabel: `${slot[0].toUpperCase()}${slot.slice(1)} header`,\n\t\ttype: 'string',\n\t\tdefault: fallback,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: `Header the proxy puts the user's ${slot} in.`,\n\t\timpact: 'A name the proxy never sends signs nobody in. Override all three or none.'\n\t});\n\nexport const HEADER_AUTH_SETTINGS = composeManifest([\n\tdefineSetting({\n\t\tkey: 'HEADER_AUTH_DATA_DIR',\n\t\tlabel: 'Allowlist folder',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'Directory holding header-allowlist.json. Falls back to DATA_PATH.'\n\t}),\n\theader('HEADER_AUTH_UPN_HEADER', 'SELVA-UserPrincipalName', 'UPN'),\n\theader('HEADER_AUTH_EMAIL_HEADER', 'SELVA-Email', 'email'),\n\theader('HEADER_AUTH_DISPLAY_NAME_HEADER', 'SELVA-DisplayName', 'display name')\n]);\n","import { composeManifest, defineSetting } from '@selvajs/platform/config';\n\nexport const LOCAL_SETTINGS = composeManifest([\n\tdefineSetting({\n\t\tkey: 'DATA_PATH',\n\t\tlabel: 'Data folder',\n\t\ttype: 'string',\n\t\trequired: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'Folder on this server holding users, orgs, projects and uploads. Back it up.',\n\t\timpact: 'Pointing it elsewhere starts an empty instance; the old data stays where it was.'\n\t})\n]);\n","import {\n\tbuildConfigReport,\n\tcomposeManifest,\n\tpreviousKey,\n\treadSetting,\n\ttype KeyRotation,\n\tdefineSetting,\n\ttakeSnapshot,\n\ttype ConfigReport,\n\ttype ConfigSnapshot,\n\ttype EnvRecord,\n\ttype Manifest\n} from '@selvajs/platform/config';\nimport { ENGINE_SETTINGS } from '@selvajs/server/config';\nimport { HEADER_AUTH_SETTINGS } from '@selvajs/header-auth-provider/config';\nimport { LOCAL_SETTINGS } from '@selvajs/local-provider/config';\nimport { SUPABASE_SETTINGS } from '@selvajs/supabase-provider/config';\n\nconst COMPUTE_DEBUG = defineSetting({\n\tkey: 'SELVA_FLAG_COMPUTE_DEBUG',\n\tlabel: 'Compute debug logging',\n\ttype: 'string',\n\tdefault: 'off',\n\tonInvalid: 'default',\n\tclass: 'setting',\n\tdescription:\n\t\t'off, on (cache and timing lines per solve) or verbose (adds Compute’s raw error bodies).',\n\timpact: 'verbose can write what was solved to the log, which erasure cannot reach.'\n});\n\n/** `SELVA_FLAG_COMPUTE_DEBUG`: `verbose`, or on and off in the manifest's boolean words. */\nexport function computeDebugMode(env: EnvRecord): 'off' | 'on' | 'verbose' {\n\tif ((readSetting(COMPUTE_DEBUG, env) as string).toLowerCase() === 'verbose') return 'verbose';\n\treturn readSetting({ ...COMPUTE_DEBUG, type: 'bool', default: false }, env) ? 'on' : 'off';\n}\n\n/** Keys only this app reads. adapter-node's own keys are here too: they decide whether it works. */\nexport const APP_SETTINGS = composeManifest([\n\tdefineSetting({\n\t\tkey: 'ORIGIN',\n\t\tlabel: 'Public address',\n\t\ttype: 'url',\n\t\torigin: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'The URL people use to reach Selva, such as https://selva.example.com.',\n\t\timpact:\n\t\t\t'Wrong or unset behind a proxy: form posts fail the CSRF check and invite links carry an internal host.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'PORT',\n\t\tlabel: 'Port',\n\t\ttype: 'int',\n\t\tmin: 1,\n\t\tmax: 65535,\n\t\tdefault: 3000,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'Port the app listens on.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'HOST',\n\t\tlabel: 'Listen address',\n\t\ttype: 'string',\n\t\tdefault: '0.0.0.0',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription:\n\t\t\t'Which network address the app accepts connections on. 127.0.0.1 when a proxy sits in front.',\n\t\timpact: 'Under header auth, anything that reaches the port directly can claim to be any user.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'BODY_SIZE_LIMIT',\n\t\tlabel: 'Max request size',\n\t\ttype: 'string',\n\t\tdefault: '512K',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'Largest request the server accepts at all, uploads included (K, M or G suffix).',\n\t\timpact: 'Below COMPUTE_REQUEST_MAX_BYTES, uploads and file inputs fail with 413.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'ADDRESS_HEADER',\n\t\tlabel: 'Visitor IP header',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription:\n\t\t\t'Header your proxy uses to pass on the visitor’s IP address. Usually X-Forwarded-For.',\n\t\timpact: 'Unset behind a proxy: every client shares one rate-limit bucket.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'XFF_DEPTH',\n\t\tlabel: 'Proxies in front',\n\t\ttype: 'int',\n\t\tmin: 1,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'How many proxies sit between visitors and the app. Usually 1.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'PROTOCOL_HEADER',\n\t\tlabel: 'Protocol header',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'Header carrying the original protocol, when ORIGIN is unset.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'HOST_HEADER',\n\t\tlabel: 'Host header',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'Header carrying the original host, when ORIGIN is unset.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'NODE_ENV',\n\t\tlabel: 'Run mode',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'production in deployments: hides stack traces and makes cookies Secure.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'ALLOW_INSECURE_COOKIES',\n\t\tlabel: 'Allow sign-in over http',\n\t\ttype: 'bool',\n\t\tdefault: false,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'Drop the Secure cookie flag so sign-in works over plain http.',\n\t\tlegacy: { bool: 'exact-true' }\n\t}),\n\tdefineSetting({\n\t\tkey: 'INSTALL_DIR',\n\t\tlabel: 'Install folder',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription:\n\t\t\t'Deployment directory the admin updater runs in. Defaults to the working directory.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'NPM_CONFIG_REGISTRY',\n\t\tlabel: 'npm registry',\n\t\ttype: 'url',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription:\n\t\t\t'Registry updates are checked against and installed from. Defaults to registry.npmjs.org.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SELVA_EVENT_CALLBACK_ORIGIN',\n\t\tlabel: 'Solve event callback address',\n\t\ttype: 'url',\n\t\torigin: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription:\n\t\t\t'Origin Rhino.Compute posts live solve events to, when it differs from the browser’s.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'MCP_ALLOWED_ORIGINS',\n\t\tlabel: 'Extra MCP origins',\n\t\ttype: 'list',\n\t\tdefault: [],\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription: 'Browser origins /mcp accepts besides its own.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'MCP_PREVIEW_BROWSER',\n\t\tlabel: 'MCP preview browser',\n\t\ttype: 'string',\n\t\tdefault: '',\n\t\tonInvalid: 'default',\n\t\tclass: 'setting',\n\t\tdescription:\n\t\t\t\"Chromium or Chrome executable that selva_capture_preview renders with. Empty: Playwright's own Chromium, else an installed Chrome, Edge or distro Chromium.\"\n\t}),\n\tdefineSetting({\n\t\tkey: 'LOG_LEVEL',\n\t\tlabel: 'Log level',\n\t\ttype: 'enum',\n\t\tvalues: ['debug', 'info', 'warn', 'error'],\n\t\tonInvalid: 'default',\n\t\tclass: 'setting',\n\t\tdescription: 'Lowest severity written to the log. Default info (debug in development).'\n\t}),\n\tCOMPUTE_DEBUG,\n\tdefineSetting({\n\t\tkey: 'SENTRY_DSN',\n\t\tlabel: 'Sentry error reporting',\n\t\ttype: 'url',\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tdescription:\n\t\t\t'Ship unexpected server errors to Sentry, scrubbed of cookies, auth headers, bodies and query strings.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SENTRY_TRACES_SAMPLE_RATE',\n\t\tlabel: 'Sentry trace sampling',\n\t\ttype: 'string',\n\t\tdefault: '0',\n\t\tonInvalid: 'default',\n\t\tclass: 'tunable',\n\t\tdescription:\n\t\t\t'Share of requests traced to Sentry, 0–1 (out of range is clamped). 0 sends errors only.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SELVA_RELEASE',\n\t\tlabel: 'Release tag',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'tunable',\n\t\tdescription: 'Release tag on Sentry events and log records.'\n\t})\n]);\n\n/** Prefixes whose undeclared keys are reported as unknown (likely typos). */\nexport const WATCHED_PREFIXES = [\n\t'SELVA_',\n\t'SUPABASE_',\n\t'COMPUTE_',\n\t'SMTP_',\n\t'HEADER_AUTH_',\n\t'API_TOKEN_',\n\t'MAX_',\n\t'REMOTE_DEFINITION_',\n\t'SIGN_IN_',\n\t'BOOTSTRAP_'\n] as const;\n\n/** Read by tooling, not by the app: not unknown, not reported. */\nexport const EXTERNAL_KEYS = ['SELVA_REQUIRE_SUPABASE'] as const;\n\n/**\n * Keys no release reads any more, with what took their place. Boot and doctor\n * name them instead of calling them typos; `selva migrate` removes them.\n */\nexport const RETIRED_KEYS: Readonly<Record<string, string>> = {\n\tSELVA_FLAG_COMPUTE_DEBUG_VERBOSE: 'use SELVA_FLAG_COMPUTE_DEBUG=verbose',\n\tCOMPUTE_RATE_LIMIT_WINDOW_MS: 'fixed at 100 s',\n\tAPI_TOKEN_RATE_LIMIT_WINDOW_MS: 'fixed at 60 s',\n\tMAX_IMAGE_FILE_SIZE_BYTES: 'fixed at 10 MB',\n\tCOMPUTE_REQUEST_MAX_BYTES: 'fixed at 256 MB',\n\tCOMPUTE_RESPONSE_MAX_BYTES: 'fixed at 300 MB',\n\tREMOTE_DEFINITION_FETCH_TIMEOUT_MS: 'fixed at 30 s',\n\tREMOTE_DEFINITION_CACHE_TTL_MS: 'fixed at 5 min',\n\tDEFINITION_CACHE_TTL_MS: 'fixed at 5 min',\n\tSUPABASE_TOKEN_VERIFICATION: 'always hybrid',\n\tSUPABASE_REVALIDATE_MS: 'fixed at 60 s',\n\tSUPABASE_PRIVATE_URL_PREFIX: 'fixed at /api/files',\n\tCOMPUTE_SOLVE_DEADLINE_MS: 'set --timeout (RHINO_COMPUTE_TIMEOUT) on the compute server',\n\tMAX_SOLVE_DURATION_MS: 'set --timeout (RHINO_COMPUTE_TIMEOUT) on the compute server',\n\tCOMPUTE_REUSE_DEFINITION_CACHE: 'on whenever the compute server reports /limits',\n\tCOMPUTE_CACHE_ERRORED_SOLVES: 'removed'\n};\n\n/**\n * The manifest for this deployment: engine and app keys, plus the slices of\n * the providers it selects. A provider's required keys only apply when it is\n * in use, so slices are chosen here rather than all composed at once.\n */\nexport function deploymentManifest(env: EnvRecord): Manifest {\n\tconst chosen = new Set(\n\t\t(['SELVA_AUTH_PROVIDER', 'SELVA_DATA_PROVIDER', 'SELVA_STORAGE_PROVIDER'] as const).map((k) =>\n\t\t\t(env[k] ?? 'local').toLowerCase()\n\t\t)\n\t);\n\treturn composeManifest([\n\t\tENGINE_SETTINGS,\n\t\tAPP_SETTINGS,\n\t\t...(chosen.has('local') ? [LOCAL_SETTINGS] : []),\n\t\t...(chosen.has('supabase') ? [SUPABASE_SETTINGS] : []),\n\t\t...(chosen.has('header') ? [HEADER_AUTH_SETTINGS] : [])\n\t]);\n}\n\n/** Every key any slice declares, whichever providers are chosen. */\nexport const ALL_SETTINGS: Manifest = composeManifest([\n\tENGINE_SETTINGS,\n\tAPP_SETTINGS,\n\tLOCAL_SETTINGS,\n\tSUPABASE_SETTINGS,\n\tHEADER_AUTH_SETTINGS\n]);\n\n/** The report for this deployment. Keys of providers it doesn't use are known, not typos. */\nexport function deploymentReport(env: EnvRecord): ConfigReport {\n\tconst manifest = deploymentManifest(env);\n\tconst active = new Set(manifest.flatMap((s) => [s.key, ...(s.aliases ?? [])]));\n\tconst inactive = ALL_SETTINGS.flatMap((s) => [s.key, ...(s.aliases ?? [])]).filter(\n\t\t(k) => !active.has(k)\n\t);\n\treturn buildConfigReport(manifest, env, {\n\t\tprefixes: WATCHED_PREFIXES,\n\t\texternal: [...EXTERNAL_KEYS, ...Object.keys(RETIRED_KEYS), ...inactive]\n\t});\n}\n\n// Set by the process manager (pm2's ecosystem file), never by .env, so the CLI\n// comparing .env with the last boot would report it as drift forever.\nconst NOT_FROM_ENV_FILE = new Set(['NODE_ENV']);\n\n/** What the boot snapshot and the CLI's drift check compare. */\nexport function deploymentSnapshot(env: EnvRecord, salt?: string): ConfigSnapshot {\n\tconst manifest = deploymentManifest(env).filter((s) => !NOT_FROM_ENV_FILE.has(s.key));\n\treturn takeSnapshot(manifest, env, salt);\n}\n\n/** The rotation overlap of each root key: what the admin page and doctor count down. */\nexport function keyRotationStatus(env: EnvRecord, now: number = Date.now()): KeyRotation[] {\n\treturn (['SELVA_HMAC_KEY', 'SELVA_AT_REST_KEY'] as const).map((key) => {\n\t\tconst p = previousKey(env, key, now);\n\t\t// The previous key itself never leaves the server.\n\t\treturn {\n\t\t\tkey,\n\t\t\tstate: p.state,\n\t\t\t...('expires' in p ? { expires: p.expires } : {}),\n\t\t\t...('daysLeft' in p ? { daysLeft: p.daysLeft } : {})\n\t\t};\n\t});\n}\n","import { env } from '#lib/server/env.js';\nimport type {\n\tIErrorReporter,\n\tIEventSink,\n\tILogger,\n\tINotificationProvider,\n\tISolveMetricSink,\n\tLogFields,\n\tLogLevel,\n\tSelvaBranding,\n\tSelvaConfig,\n\tSelvaFlags,\n\tTenancyMode\n} from '@selvajs/platform';\nimport { NoopErrorReporter, NoopEventSink } from '@selvajs/platform';\nimport { createSelvaProviders, type ProviderRegistry } from '@selvajs/server/providers';\nimport * as local from '@selvajs/local-provider';\nimport * as supa from '@selvajs/supabase-provider';\nimport * as header from '@selvajs/header-auth-provider';\nimport { DefinitionService } from '@selvajs/server/definitions';\nimport { MAX_SOLVE_DEADLINE_MS } from '@selvajs/solve/server';\nimport { OrgAssetService } from '@selvajs/server/organizations';\nimport { SentryErrorReporter } from '@selvajs/server/errors';\nimport { SmtpNotificationProvider } from '@selvajs/server/notifications';\nimport { ConsoleLogger, createLogger, renderThrown } from '@selvajs/server/logging';\nimport { computeDebugMode } from '#lib/server/config/settings.js';\n\n// Provider wiring lives in `@selvajs/server/providers` (`createSelvaProviders`):\n// env-driven selection over the registry below, an external `selva.config.js`\n// override via SELVA_CONFIG_PATH, and lazy memoized instantiation (nothing\n// touches provider secrets at import/build time). This file is the app's\n// composition root: bundled provider implementations, service singletons,\n// and error reporting.\n\n// Forwards to whatever the root logger currently is, rather than capturing it.\n// `_logger` starts as a console placeholder and is swapped for pino once its\n// async load resolves (see Logging below); a provider handed `getLogger()`\n// directly at construction would pin the placeholder for the process's whole\n// life, so long-lived providers get this indirection instead.\nexport const lazyLogger: ILogger = {\n\tdebug: (m: string, f?: LogFields) => getLogger().debug(m, f),\n\tinfo: (m: string, f?: LogFields) => getLogger().info(m, f),\n\twarn: (m: string, f?: LogFields) => getLogger().warn(m, f),\n\terror: (m: string, f?: LogFields) => getLogger().error(m, f),\n\tchild: (f: LogFields) => getLogger().child(f)\n};\n\n/** The provider implementations bundled with the Selva app. */\nconst registry: ProviderRegistry = {\n\tauth: {\n\t\tlocal: (e) => local.LocalAuthProvider.fromEnv(e),\n\t\tsupabase: (e) =>\n\t\t\tsupa.SupabaseAuthProvider.fromEnv(e, lazyLogger, {\n\t\t\t\t// The session minted for an API-token request must outlive its solve, whichever\n\t\t\t\t// server runs it.\n\t\t\t\tdelegatedSessionTtlSeconds: MAX_SOLVE_DEADLINE_MS / 1000 + 60\n\t\t\t}),\n\t\theader: (e) => header.HeaderAuthProvider.fromEnv(e, lazyLogger)\n\t},\n\tdata: {\n\t\tlocal: (e) => local.LocalDataProvider.fromEnv(e),\n\t\t// `events` (2nd param) stays defaulted — the app wires its event sink\n\t\t// separately, see getEventSink below.\n\t\tsupabase: (e) => supa.SupabaseDataProvider.fromEnv(e, undefined, lazyLogger)\n\t},\n\tstorage: {\n\t\tlocal: (e) => local.LocalStorageProvider.fromEnv(e),\n\t\tsupabase: (e) => supa.SupabaseStorageProvider.fromEnv(e)\n\t}\n};\n\nconst runtime = await createSelvaProviders(env, {\n\tregistry,\n\tconfigPath: env.SELVA_CONFIG_PATH,\n\tlogger: lazyLogger\n});\n\n// Memoized: first call instantiates providers from env (may throw if\n// required secrets are missing) and later calls return the cached config.\n// Importing this module has no side effects — init happens lazily on the\n// first request, never at build time.\nexport function resolveProviders(): SelvaConfig {\n\treturn runtime.resolve();\n}\n\n/**\n * @deprecated Prefer {@link resolveProviders}. Kept as a property accessor so\n * existing `import { providers }` call sites resolve lazily instead of at\n * import time.\n */\nexport const providers = new Proxy({} as SelvaConfig, {\n\tget(_t, prop) {\n\t\treturn Reflect.get(resolveProviders(), prop);\n\t}\n});\n\nexport function getTenancy(): TenancyMode {\n\treturn runtime.tenancy();\n}\n\n// Every field has a default so the UI never has to null-check. Override via SELVA_BRAND_* env vars.\nexport function getBranding(): Required<SelvaBranding> {\n\treturn runtime.branding();\n}\n\n// Use this rather than reading flags directly — omitted flags resolve to false.\nexport function flag(name: keyof SelvaFlags): boolean {\n\treturn runtime.flag(name);\n}\n\nlet _definitionService: DefinitionService | undefined;\nexport function getDefinitionService(): DefinitionService {\n\tif (!_definitionService) {\n\t\tconst p = resolveProviders();\n\t\t_definitionService = new DefinitionService(p.data, p.storage, lazyLogger);\n\t}\n\treturn _definitionService;\n}\n\nlet _orgAssetService: OrgAssetService | undefined;\nexport function getOrgAssetService(): OrgAssetService {\n\tif (!_orgAssetService) {\n\t\tconst p = resolveProviders();\n\t\t_orgAssetService = new OrgAssetService(p.data.orgs, p.storage);\n\t}\n\treturn _orgAssetService;\n}\n\nexport function getAuthProvider() {\n\treturn resolveProviders().auth;\n}\n\nexport function getStorageProvider() {\n\treturn resolveProviders().storage;\n}\n\nexport function getDataProvider() {\n\treturn resolveProviders().data;\n}\n\nexport function getOrganizationProvider() {\n\treturn resolveProviders().data.orgs;\n}\n\nexport function getProjectProvider() {\n\treturn resolveProviders().data.projects;\n}\n\nexport function getDefinitionMeta() {\n\treturn resolveProviders().data.definitions;\n}\n\nexport function getComputeServerConfigStore() {\n\treturn resolveProviders().data.computeServer;\n}\n\nexport function getUserProfileStore() {\n\treturn resolveProviders().data.userProfile;\n}\n\nexport function getShareLinkStore() {\n\treturn resolveProviders().data.shareLinks;\n}\n\nexport function getInviteStore() {\n\treturn resolveProviders().data.invites;\n}\n\nexport function getPermissionStore() {\n\treturn resolveProviders().data.permissions;\n}\n\nexport function getPlatformProjectGrantStore() {\n\treturn resolveProviders().data.platformProjectGrants;\n}\n\n// Defaults to `NoopSolveMetricSink` when the config omits `solveMetrics`, so the compute route always records unconditionally.\nexport function getSolveMetricSink(): ISolveMetricSink {\n\treturn runtime.solveMetricSink();\n}\n\n// Null on deployments where the audit log isn't queryable (local-provider\n// stays on `NoopEventSink`). Callers must handle null and degrade their UI.\nexport function getAuditQuery() {\n\treturn providers.data.auditQuery ?? null;\n}\n\nconst noopEventSink = new NoopEventSink();\n\n// Write-side sink for routes with no store mutation to piggyback on (e.g.\n// self-update lifecycle events). Prefers SelvaConfig.events, then the data\n// provider's own sink, then a no-op.\nexport function getEventSink(): IEventSink {\n\tconst p = resolveProviders();\n\treturn p.events ?? p.data.events ?? noopEventSink;\n}\n\n// ============================================================================\n// Logging\n// ============================================================================\n\n// Same eager-init-then-swap shape as the error reporter below, but the\n// placeholder here is a real ConsoleLogger, never a no-op: logging must not\n// have a window where warnings vanish while an operator is debugging a boot\n// failure. Records written before pino resolves land on the console; the\n// swap only upgrades the formatting.\nconst LOG_LEVEL: LogLevel = parseLogLevel(env.LOG_LEVEL);\n\nlet _logger: ILogger = new ConsoleLogger({}, LOG_LEVEL);\n\n// Pino-backed when `pino` is installed (ships with the app; the base\n// `@selvajs/server` install treats it as an optional peer and falls back to\n// console). Prefer a request-scoped child (`event.locals.log`) in route\n// handlers so records carry `requestId`/`route` — use this root logger for\n// boot, shutdown, and background work with no request.\nexport function getLogger(): ILogger {\n\treturn _logger;\n}\n\nlet _notifications: INotificationProvider | null = null;\n\n// SMTP-backed; sends nothing when `SMTP_HOST` is unset, which is a supported\n// deployment — callers fall back to sharing links by hand. `env` is passed\n// rather than read inside the provider: under `vite dev`, Vite doesn't\n// mirror `.env` into `process.env`, so reading it directly would silently\n// ignore every override.\nexport function getNotificationProvider(): INotificationProvider {\n\t_notifications ??= new SmtpNotificationProvider(env);\n\treturn _notifications;\n}\n\n// `LOG_LEVEL` is operator input — an unrecognized value must not crash boot\n// or silently disable logging. Defaults to `info`, `debug` in dev.\nfunction parseLogLevel(raw: string | undefined): LogLevel {\n\tconst value = raw?.trim().toLowerCase();\n\tif (value === 'debug' || value === 'info' || value === 'warn' || value === 'error') return value;\n\t// An operator who set SELVA_FLAG_COMPUTE_DEBUG asked for debug output in so\n\t// many words — honor it without also requiring LOG_LEVEL=debug, since the\n\t// flag would otherwise silently do nothing in production.\n\tif (computeDebugMode(env) !== 'off') return 'debug';\n\treturn env.NODE_ENV === 'development' ? 'debug' : 'info';\n}\n\n// Eager, fire-and-forget: `getLogger()` stays sync for the same reason\n// `getErrorReporter()` does below — callers (hooks, process handlers) can't await.\nvoid createLogger({\n\tlevel: LOG_LEVEL,\n\t// Pretty in dev, newline-delimited JSON in production. `pino-pretty` is a\n\t// devDependency, so this degrades to JSON if it's absent.\n\tpretty: env.NODE_ENV === 'development',\n\tbase: { service: 'selva', release: env.SELVA_RELEASE }\n}).then((logger) => {\n\t_logger = logger;\n});\n\n// ============================================================================\n// Error reporting\n// ============================================================================\n\n// Starts as the no-op reporter, swapped for a Sentry-backed one once async\n// init resolves. `getErrorReporter()` is synchronous — called from\n// `handleError` and process error hooks, which can't await — so reports go\n// to the no-op during the sub-second boot window before Sentry loads.\n// Acceptable: only errors thrown in that window are lost.\nlet _errorReporter: IErrorReporter = new NoopErrorReporter();\n\n// Ships errors off-box (Sentry) only when `SENTRY_DSN` is configured;\n// otherwise a no-op, so self-hosters opt in via env and the base install\n// carries no error-tracking dependency. Only genuinely unexpected errors\n// reach here — see `handleError` in hooks.server.ts for what's filtered out.\nexport function getErrorReporter(): IErrorReporter {\n\treturn _errorReporter;\n}\n\n// Eager, fire-and-forget init at module load. Kept out of `getErrorReporter()`\n// so the getter stays sync and allocation-free on the hot error path.\nif (env.SENTRY_DSN) {\n\tvoid SentryErrorReporter.create({\n\t\tdsn: env.SENTRY_DSN,\n\t\tenvironment: env.NODE_ENV,\n\t\trelease: env.SELVA_RELEASE,\n\t\ttracesSampleRate: env.SENTRY_TRACES_SAMPLE_RATE\n\t}).then((reporter) => {\n\t\tif (reporter) {\n\t\t\t_errorReporter = reporter;\n\t\t\tgetLogger().info('Sentry error tracking enabled', { component: 'ErrorReporter' });\n\t\t}\n\t});\n}\n\n// Process-level safety net. `handleError` only sees errors on the request\n// path; a rejected promise with no awaiter, or a throw outside any request,\n// bypasses it and would otherwise vanish. Report both, then let Node's\n// default behavior stand (logs uncaughtException and exits — we don't\n// swallow it and pretend the process is healthy). Guarded so repeated module\n// evaluation in dev/HMR doesn't stack duplicate listeners.\nconst ERROR_HOOKS_FLAG = '__selvaProcessErrorHooksRegistered';\nif (!(globalThis as Record<string, unknown>)[ERROR_HOOKS_FLAG]) {\n\t(globalThis as Record<string, unknown>)[ERROR_HOOKS_FLAG] = true;\n\tprocess.on('unhandledRejection', (reason) => {\n\t\tgetLogger().error('Unhandled promise rejection', {\n\t\t\tcomponent: 'process',\n\t\t\torigin: 'unhandledRejection',\n\t\t\terr: renderThrown(reason)\n\t\t});\n\t\tgetErrorReporter().capture(reason, { tags: { origin: 'unhandledRejection' } });\n\t});\n\tprocess.on('uncaughtException', (error) => {\n\t\t// Also write straight to the console here: Node is about to exit, and a\n\t\t// buffered/async log transport may never flush. The duplicate line is a\n\t\t// cheap price for not losing the record that explains the crash.\n\t\t// Rendered, not raw — handing the object to stdout would print whatever\n\t\t// a provider adapter stashed on `cause` (connection details, sometimes a\n\t\t// DSN) where pino's redaction never runs.\n\t\tconsole.error('[uncaughtException]', renderThrown(error));\n\t\tgetLogger().error('Uncaught exception', {\n\t\t\tcomponent: 'process',\n\t\t\torigin: 'uncaughtException',\n\t\t\terr: renderThrown(error)\n\t\t});\n\t\tgetErrorReporter().capture(error, { tags: { origin: 'uncaughtException' } });\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,kBACf,UACA,KACA,UAA0B,CAAC,GACZ;CACf,MAAM,WAAW,cAAc,UAAU,KAAK,OAAO;CACrD,MAAM,OAAoB,SAAS,KAAK,SAAS;EAChD,MAAM,IAAI,SAAS,KAAK,KAAK;EAC7B,OAAO;GACN,KAAK,KAAK;GACV,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,M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O;EACP,SAAS;EACT,aACC;EACD,QAAQ;CACT,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,SAAS;EACT,WAAW;EACX,OAAO;EACP,SAAS;EACT,aAAa;EACb,QAAQ;CACT,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,SAAS;EACT,aACC;EACD,QAAQ;CACT,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,KAAK;EACL,WAAW;EACX,OAAO;EACP,SAAS;EACT,aAAa;CACd,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aAAa;CACd,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aAAa;CACd,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aAAa;CACd,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,SAAS;EACT,WAAW;EACX,OAAO;EACP,aAAa;EACb,QAAQ,EAAE,MAAM,aAAa;CAC9B,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aACC;CACF,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aACC;CACF,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,QAAQ;EACR,WAAW;EACX,OAAO;EACP,aACC;CACF,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,SAAS,CAAC;EACV,WAAW;EACX,OAAO;EACP,aAAa;CACd,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,SAAS;EACT,WAAW;EACX,OAAO;EACP,aACC;CAC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