@selvajs/selva 4.20.0 → 4.20.1-beta.1
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.2jDm0bqh.css +2 -0
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css.br +0 -0
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css.gz +0 -0
- package/build/client/_app/immutable/assets/{21.CZQvs3vE.css → 21.DDgTnace.css} +1 -1
- package/build/client/_app/immutable/assets/21.DDgTnace.css.br +0 -0
- package/build/client/_app/immutable/assets/21.DDgTnace.css.gz +0 -0
- package/build/client/_app/immutable/chunks/{DbTdXFSI.js → BDYCH-_Q.js} +1 -1
- package/build/client/_app/immutable/chunks/BDYCH-_Q.js.br +0 -0
- package/build/client/_app/immutable/chunks/BDYCH-_Q.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{6oDkMEbX.js → D-SwRD80.js} +62 -39
- package/build/client/_app/immutable/chunks/D-SwRD80.js.br +0 -0
- package/build/client/_app/immutable/chunks/D-SwRD80.js.gz +0 -0
- package/build/client/_app/immutable/chunks/Dvq2vJj6.js +1 -0
- package/build/client/_app/immutable/chunks/Dvq2vJj6.js.br +1 -0
- package/build/client/_app/immutable/chunks/Dvq2vJj6.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{DVcao28H.js → DzxE3j6C.js} +1 -1
- package/build/client/_app/immutable/chunks/DzxE3j6C.js.br +0 -0
- package/build/client/_app/immutable/chunks/DzxE3j6C.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{DyqtDkQe.js → qi43d-TM.js} +1 -1
- package/build/client/_app/immutable/chunks/qi43d-TM.js.br +0 -0
- package/build/client/_app/immutable/chunks/qi43d-TM.js.gz +0 -0
- package/build/client/_app/immutable/chunks/zJ-SFdYZ.js +1 -0
- package/build/client/_app/immutable/chunks/zJ-SFdYZ.js.br +0 -0
- package/build/client/_app/immutable/chunks/zJ-SFdYZ.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.CN37JsEV.js → app.hg2qyLJU.js} +2 -2
- package/build/client/_app/immutable/entry/app.hg2qyLJU.js.br +0 -0
- package/build/client/_app/immutable/entry/app.hg2qyLJU.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{2.c6X0ddnS.js → 2.CUNbzjI_.js} +1 -1
- package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.br +0 -0
- package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{20.CyrNl6i7.js → 20.9OIre0ah.js} +1 -1
- package/build/client/_app/immutable/nodes/20.9OIre0ah.js.br +0 -0
- package/build/client/_app/immutable/nodes/20.9OIre0ah.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.gGT7QEb1.js +1 -0
- package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.br +1 -0
- package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{30.Bz0cB9UL.js → 30.BBuL_XNB.js} +2 -2
- package/build/client/_app/immutable/nodes/30.BBuL_XNB.js.br +0 -0
- package/build/client/_app/immutable/nodes/30.BBuL_XNB.js.gz +0 -0
- package/build/client/_app/immutable/nodes/35.De6sleaH.js +5 -0
- package/build/client/_app/immutable/nodes/35.De6sleaH.js.br +0 -0
- package/build/client/_app/immutable/nodes/35.De6sleaH.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{5.Ck6I7GRI.js → 5.DmA9lTA-.js} +1 -1
- package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.br +1 -0
- package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{6.BiSiWLjz.js → 6.D6WLqCgl.js} +1 -1
- package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.br +0 -0
- package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{7.OTA16TkX.js → 7.CNuRjkv2.js} +1 -1
- package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.br +0 -0
- package/build/client/_app/immutable/nodes/7.CNuRjkv2.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 +108 -89
- package/build/server/_app/immutable/assets/_layout.2jDm0bqh.css +2 -0
- package/build/server/_app/immutable/assets/{_page.BLIssNhc.css → _page.l97MEw0G.css} +1 -1
- package/build/server/chunks/SettingsMenu.js +2 -2
- package/build/server/chunks/SettingsMenu.js.map +1 -1
- package/build/server/chunks/{abort-CNJ8Sn4g.js → abort-Bfrdupaj.js} +10 -3
- package/build/server/chunks/{abort-CNJ8Sn4g.js.map → abort-Bfrdupaj.js.map} +1 -1
- package/build/server/chunks/access.js +608 -150
- package/build/server/chunks/access.js.map +1 -1
- package/build/server/chunks/access2.server.js +2 -2
- package/build/server/chunks/api-errors.js +1 -1
- package/build/server/chunks/api.js +66 -18
- package/build/server/chunks/api.js.map +1 -1
- package/build/server/chunks/auth-bootstrap.server.js +1 -1
- package/build/server/chunks/boot.server.js +12 -701
- package/build/server/chunks/boot.server.js.map +1 -1
- package/build/server/chunks/bootHealth.server.js.map +1 -1
- package/build/server/chunks/compute.js +1 -1
- package/build/server/chunks/computeLimits.js +1 -1
- package/build/server/chunks/computeRateLimit.server.js +1 -1
- package/build/server/chunks/context.js +9 -43
- package/build/server/chunks/context.js.map +1 -1
- package/build/server/chunks/create-project.js +2 -2
- package/build/server/chunks/delete-with-blobs.js +1 -1
- package/build/server/chunks/engine.server.js +2 -16
- package/build/server/chunks/engine.server.js.map +1 -1
- package/build/server/chunks/grasshopper.js +2 -1
- package/build/server/chunks/grasshopper.js.map +1 -1
- package/build/server/chunks/handlers.js +13 -29
- package/build/server/chunks/handlers.js.map +1 -1
- package/build/server/chunks/http.js +93 -6
- package/build/server/chunks/http.js.map +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/instanceAdmins.server.js +1 -1
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/limits.js +71 -0
- package/build/server/chunks/limits.js.map +1 -0
- 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/permissions.server.js +1 -1
- package/build/server/chunks/presets.server.js +1 -1
- package/build/server/chunks/previous-key.js +18 -2
- package/build/server/chunks/previous-key.js.map +1 -1
- package/build/server/chunks/providers.server.js +808 -444
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/registry.js +4 -1
- package/build/server/chunks/registry.js.map +1 -1
- package/build/server/chunks/remote-definition.js +1 -1
- package/build/server/chunks/safe-url.js +1 -1
- package/build/server/chunks/schema.js.map +1 -1
- package/build/server/chunks/schemas.js +12 -61
- package/build/server/chunks/schemas.js.map +1 -1
- package/build/server/chunks/schemas2.js +80 -0
- package/build/server/chunks/schemas2.js.map +1 -0
- package/build/server/chunks/server-config-write.js +3 -8
- package/build/server/chunks/server-config-write.js.map +1 -1
- package/build/server/chunks/signInMaxAge.server.js +1 -1
- package/build/server/chunks/solve.server.js +4 -2
- package/build/server/chunks/solve.server.js.map +1 -1
- package/build/server/chunks/sveltekit.js +4 -4
- package/build/server/chunks/token2.server.js +1 -1
- package/build/server/chunks/tokens.js +2 -2
- package/build/server/chunks/types.js +9 -4
- package/build/server/chunks/types.js.map +1 -1
- package/build/server/chunks/types2.js +1 -2
- package/build/server/chunks/types2.js.map +1 -1
- package/build/server/chunks/visibility.js +1 -1
- package/build/server/chunks/visibility.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/orgs/_id_/_server.ts.js +3 -3
- package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js +6 -5
- package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_grantId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/admin/users/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +2 -1
- package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/v1/compute/schema/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/image/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/publish/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/schema/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_linkId_/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/schema/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/me/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/me/starred/_guid_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/me/token/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/assets/_kind_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/compute/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/invites/_id_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/invites/_id_/resend/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/invites/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/members/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/members/_userId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_tokenId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/projects/_id_/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/projects/_id_/members/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/projects/_id_/members/_userId_/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/projects/_id_/reclaim/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/projects/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/solve/_solveId_/cancel/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/solve-events/_server.ts.js +1 -1
- package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
- package/build/server/entries/endpoints/mcp/_server.ts.js +5 -4
- package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
- package/build/server/entries/hooks.server.js +3 -92
- package/build/server/entries/hooks.server.js.map +1 -1
- package/build/server/entries/pages/accept-invite/_page.server.ts.js +9 -6
- package/build/server/entries/pages/accept-invite/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/admin/_page.server.ts.js +1 -1
- package/build/server/entries/pages/admin/organizations/_page.server.ts.js +1 -1
- package/build/server/entries/pages/admin/projects/_id_/_page.server.ts.js +1 -1
- package/build/server/entries/pages/admin/projects/_page.server.ts.js +1 -1
- package/build/server/entries/pages/admin/system/_page.server.ts.js +2 -2
- package/build/server/entries/pages/admin/users/_page.server.ts.js +1 -1
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +114 -43
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/oauth/authorize/_page.server.ts.js +1 -1
- package/build/server/entries/pages/projects/_layout.server.ts.js +1 -1
- package/build/server/entries/pages/projects/_page.server.ts.js +2 -2
- package/build/server/entries/pages/setup/_page.server.ts.js +1 -1
- package/build/server/entries/pages/team/compute/_page.server.ts.js +1 -1
- package/build/server/entries/pages/team/members/_page.server.ts.js +1 -1
- package/build/server/entries/pages/team/members/_page.svelte.js +2 -2
- package/build/server/entries/pages/team/members/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/team/projects/_page.server.ts.js +1 -1
- package/build/server/entries/pages/team/settings/_page.server.ts.js +1 -1
- package/build/server/entries/pages/team/shares/_page.server.ts.js +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/2.js +1 -1
- package/build/server/nodes/20.js +1 -1
- package/build/server/nodes/21.js +2 -2
- package/build/server/nodes/30.js +1 -1
- package/build/server/nodes/35.js +1 -1
- package/build/server/nodes/5.js +1 -1
- package/build/server/nodes/6.js +1 -1
- package/build/server/nodes/7.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +12 -12
- package/build/client/_app/immutable/assets/0.DwB0QWdx.css +0 -2
- package/build/client/_app/immutable/assets/0.DwB0QWdx.css.br +0 -0
- package/build/client/_app/immutable/assets/0.DwB0QWdx.css.gz +0 -0
- package/build/client/_app/immutable/assets/21.CZQvs3vE.css.br +0 -0
- package/build/client/_app/immutable/assets/21.CZQvs3vE.css.gz +0 -0
- package/build/client/_app/immutable/chunks/6oDkMEbX.js.br +0 -0
- package/build/client/_app/immutable/chunks/6oDkMEbX.js.gz +0 -0
- package/build/client/_app/immutable/chunks/B9IvNrzX.js +0 -1
- package/build/client/_app/immutable/chunks/B9IvNrzX.js.br +0 -1
- package/build/client/_app/immutable/chunks/B9IvNrzX.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DVcao28H.js.br +0 -0
- package/build/client/_app/immutable/chunks/DVcao28H.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DbTdXFSI.js.br +0 -0
- package/build/client/_app/immutable/chunks/DbTdXFSI.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DyqtDkQe.js.br +0 -0
- package/build/client/_app/immutable/chunks/DyqtDkQe.js.gz +0 -0
- package/build/client/_app/immutable/chunks/I4bYfY0F.js +0 -1
- package/build/client/_app/immutable/chunks/I4bYfY0F.js.br +0 -0
- package/build/client/_app/immutable/chunks/I4bYfY0F.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.CN37JsEV.js.br +0 -0
- package/build/client/_app/immutable/entry/app.CN37JsEV.js.gz +0 -0
- package/build/client/_app/immutable/nodes/2.c6X0ddnS.js.br +0 -0
- package/build/client/_app/immutable/nodes/2.c6X0ddnS.js.gz +0 -0
- package/build/client/_app/immutable/nodes/20.CyrNl6i7.js.br +0 -0
- package/build/client/_app/immutable/nodes/20.CyrNl6i7.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21._AcAMXtP.js +0 -1
- package/build/client/_app/immutable/nodes/21._AcAMXtP.js.br +0 -0
- package/build/client/_app/immutable/nodes/21._AcAMXtP.js.gz +0 -0
- package/build/client/_app/immutable/nodes/30.Bz0cB9UL.js.br +0 -0
- package/build/client/_app/immutable/nodes/30.Bz0cB9UL.js.gz +0 -0
- package/build/client/_app/immutable/nodes/35.DFkalFgm.js +0 -5
- package/build/client/_app/immutable/nodes/35.DFkalFgm.js.br +0 -0
- package/build/client/_app/immutable/nodes/35.DFkalFgm.js.gz +0 -0
- package/build/client/_app/immutable/nodes/5.Ck6I7GRI.js.br +0 -0
- package/build/client/_app/immutable/nodes/5.Ck6I7GRI.js.gz +0 -0
- package/build/client/_app/immutable/nodes/6.BiSiWLjz.js.br +0 -0
- package/build/client/_app/immutable/nodes/6.BiSiWLjz.js.gz +0 -0
- package/build/client/_app/immutable/nodes/7.OTA16TkX.js.br +0 -0
- package/build/client/_app/immutable/nodes/7.OTA16TkX.js.gz +0 -0
- package/build/server/_app/immutable/assets/_layout.DwB0QWdx.css +0 -2
- /package/build/client/_app/immutable/nodes/{0.CC0wt5QB.js → 0.CYdyv5To.js} +0 -0
- /package/build/client/_app/immutable/nodes/{0.CC0wt5QB.js.br → 0.CYdyv5To.js.br} +0 -0
- /package/build/client/_app/immutable/nodes/{0.CC0wt5QB.js.gz → 0.CYdyv5To.js.gz} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"access.js","names":[],"sources":["../../../../platform/src/access/rules.ts","../../../../platform/src/apiTokens/scope.ts","../../../../platform/src/logging/interface.ts","../../../../platform/src/config.ts","../../../../server/src/compute/limits.ts","../../../../server/src/api/errors.ts","../../../../server/src/access/project-access-input.ts","../../../../server/src/access/guards.ts","../../../../server/src/access/permissions-scope.ts"],"sourcesContent":["import type { PlatformPermission } from '../permissions/types.js';\nimport type { OrgPermission, OrgRole } from '../organizations/schemas.js';\nimport type { Project, ProjectMember } from '../projects/types.js';\nimport type { OrgMember } from '../organizations/types.js';\nimport type { DefinitionRecord } from '../definitions/types.js';\nimport type { PlatformProjectGrant } from '../platformProjects/types.js';\n\n/**\n * Pure access-control rules — single source of truth for UI gating across\n * adapters. Mutating store methods MUST re-enforce the same predicate\n * independently (RLS in SQL, code in local/JSON).\n *\n * `instance_admin` bypass is not baked into rule bodies — wrap calls with\n * `withAdminBypass` at the call site.\n */\n\nfunction isInstanceAdmin(platformPermissions: readonly PlatformPermission[]): boolean {\n\treturn platformPermissions.includes('instance_admin');\n}\n\nexport function withAdminBypass(\n\tplatformPermissions: readonly PlatformPermission[],\n\trule: () => boolean\n): boolean {\n\tif (isInstanceAdmin(platformPermissions)) return true;\n\treturn rule();\n}\n\nexport interface ProjectAccessInput {\n\torgPermissions: readonly OrgPermission[];\n\tplatformPermissions: readonly PlatformPermission[];\n\tproject: Project | null;\n\tmember: ProjectMember | null;\n\torgMember: OrgMember | null;\n\t/**\n\t * `ALLOW_CROSS_ORG_PUBLIC` flag. When false, `public` visibility means\n\t * \"everyone in the parent org\" rather than \"everyone on the instance\".\n\t */\n\tallowCrossOrgPublic: boolean;\n\t/**\n\t * `ENABLE_PLATFORM_PROJECTS` flag. When false, every rule treats a\n\t * `platform`-visibility project as inaccessible — even for instance\n\t * admins — so the feature can be hidden silently without deleting data.\n\t */\n\tenablePlatformProjects: boolean;\n\t/** Grants for `platform`-visibility projects; empty for non-platform ones. */\n\tplatformGrants: readonly PlatformProjectGrant[];\n\t/** `ctx.actingOrgId` — matches org grants on platform projects. */\n\tactingOrgId: string | null;\n\t/** `ctx.userId` — matches user grants on platform projects. */\n\tuserId: string;\n}\n\n/**\n * Authenticated-user view rule. Anonymous access goes through share-link\n * tokens instead — the route resolves a valid token before this runs.\n *\n * Platform projects: `instance_admin` always passes; otherwise any grant\n * (view-only or canSolve) satisfies view access.\n */\nexport function canView(input: ProjectAccessInput): boolean {\n\tconst {\n\t\tproject,\n\t\tmember,\n\t\torgMember,\n\t\tallowCrossOrgPublic,\n\t\tenablePlatformProjects,\n\t\tplatformPermissions,\n\t\tplatformGrants,\n\t\tactingOrgId,\n\t\tuserId\n\t} = input;\n\tif (!project) return false;\n\n\tif (project.visibility === 'platform') {\n\t\tif (!enablePlatformProjects) return false;\n\t\tif (isInstanceAdmin(platformPermissions)) return true;\n\t\treturn platformGrants.some(\n\t\t\t(g) =>\n\t\t\t\t(g.granteeType === 'user' && g.granteeId === userId) ||\n\t\t\t\t(g.granteeType === 'org' && g.granteeId === actingOrgId)\n\t\t);\n\t}\n\n\t// A project member sees the project at any visibility. Leaving the org ends the\n\t// membership, so this only widens access for someone who reclaimed from outside.\n\tif (member !== null) return true;\n\tif (project.visibility === 'org') return orgMember !== null && actingOrgId === project.orgId;\n\tif (project.visibility === 'public') return allowCrossOrgPublic ? true : orgMember !== null;\n\treturn false;\n}\n\n/**\n * Non-platform projects: same as `canView` — kept as a separate function so\n * cost gating can diverge from view access later.\n *\n * Platform projects: `instance_admin` always passes; a view-only grant\n * satisfies `canView` but not `canSolve` — the grant needs `canSolve: true`.\n */\nexport function canSolve(input: ProjectAccessInput): boolean {\n\tconst {\n\t\tproject,\n\t\tenablePlatformProjects,\n\t\tplatformPermissions,\n\t\tplatformGrants,\n\t\tactingOrgId,\n\t\tuserId\n\t} = input;\n\tif (!project) return false;\n\n\tif (project.visibility === 'platform') {\n\t\tif (!enablePlatformProjects) return false;\n\t\tif (isInstanceAdmin(platformPermissions)) return true;\n\t\treturn platformGrants.some(\n\t\t\t(g) =>\n\t\t\t\tg.canSolve &&\n\t\t\t\t((g.granteeType === 'user' && g.granteeId === userId) ||\n\t\t\t\t\t(g.granteeType === 'org' && g.granteeId === actingOrgId))\n\t\t);\n\t}\n\n\treturn canView(input);\n}\n\n/**\n * Platform projects: `instance_admin` only (they have no member rows).\n * All other visibilities: project owner/editor.\n */\nexport function canEdit(input: ProjectAccessInput): boolean {\n\tconst { member, project, enablePlatformProjects, platformPermissions } = input;\n\tif (!project) return false;\n\tif (project.visibility === 'platform') {\n\t\tif (!enablePlatformProjects) return false;\n\t\treturn isInstanceAdmin(platformPermissions);\n\t}\n\treturn member?.role === 'owner' || member?.role === 'editor';\n}\n\n/**\n * Adding a new definition. Commons projects (`autoJoinOnUpload`) take uploads\n * from anyone who can {@link canView} them, and the uploader owns what they\n * upload; everywhere else it needs {@link canEdit}.\n */\nexport function canCreateDefinition(input: ProjectAccessInput): boolean {\n\treturn (input.project?.autoJoinOnUpload === true && canView(input)) || canEdit(input);\n}\n\n/** Platform projects: `instance_admin` only. All other visibilities: project owner. */\nexport function canManage(input: ProjectAccessInput): boolean {\n\tif (!input.project) return false;\n\tif (input.project.visibility === 'platform') {\n\t\tif (!input.enablePlatformProjects) return false;\n\t\treturn isInstanceAdmin(input.platformPermissions);\n\t}\n\treturn input.member?.role === 'owner';\n}\n\n/** Platform projects: `instance_admin` only. All other visibilities: project owner. */\nexport function canEditProjectSettings(input: ProjectAccessInput): boolean {\n\treturn canManage(input);\n}\n\nexport interface VisibilityChangeInput {\n\torgMember: OrgMember | null;\n}\n\n/**\n * Authorization to flip a project to `public`. The `ALLOW_CROSS_ORG_PUBLIC`\n * flag only changes what `public` means post-flip; the flip itself is gated\n * by org owner/admin role.\n */\nexport function canChangeVisibilityToPublic(input: VisibilityChangeInput): boolean {\n\tconst role = input.orgMember?.role;\n\treturn role === 'owner' || role === 'admin';\n}\n\nexport interface DefinitionAccessInput {\n\tproject: Project | null;\n\tdefinition: DefinitionRecord | null;\n\tmember: ProjectMember | null;\n\t/**\n\t * The actor's membership in the project's parent org, used only by the\n\t * commons branch below. `null` means \"not a member of this org\" — which on a\n\t * commons project is what separates a current contributor from a departed\n\t * one.\n\t */\n\torgMember: OrgMember | null;\n\tuserId: string;\n\tplatformPermissions: readonly PlatformPermission[];\n\t/**\n\t * `ENABLE_PLATFORM_PROJECTS` flag. When false, definitions in\n\t * platform-visibility projects are not editable by anyone, matching the\n\t * other project rules.\n\t */\n\tenablePlatformProjects: boolean;\n}\n\n/**\n * For platform projects: `instance_admin` only.\n * For all other projects: project editor/owner can always edit (moderation).\n * On commons projects (`autoJoinOnUpload=true`) the definition owner can edit\n * their own, as long as they still belong to the project's org.\n */\nexport function canEditDefinition(input: DefinitionAccessInput): boolean {\n\tconst {\n\t\tproject,\n\t\tdefinition,\n\t\tmember,\n\t\torgMember,\n\t\tuserId,\n\t\tplatformPermissions,\n\t\tenablePlatformProjects\n\t} = input;\n\tif (!project || !definition) return false;\n\tif (definition.projectId !== project.id) return false;\n\n\tif (project.visibility === 'platform') {\n\t\tif (!enablePlatformProjects) return false;\n\t\treturn isInstanceAdmin(platformPermissions);\n\t}\n\n\tif (member?.role === 'owner' || member?.role === 'editor') return true;\n\n\t// Commons grants edit on top of belonging, not instead of it. `ownerId` is\n\t// stamped at upload and never revisited, so without the org-membership test\n\t// a departed uploader keeps edit/delete/share-link authority on everything\n\t// they ever uploaded — and flipping `autoJoinOnUpload` on hands it back to\n\t// them retroactively, with no action taken against them.\n\tif (project.autoJoinOnUpload && userId === definition.ownerId && orgMember) return true;\n\n\treturn false;\n}\n\nexport interface ReclaimAccessInput {\n\tproject: Project | null;\n\torgMember: OrgMember | null;\n\t/** `ctx.actingOrgId` — must match `project.orgId`. */\n\tactingOrgId: string | null;\n}\n\n/**\n * Org leadership escape hatch: adds the actor as co-owner without demoting\n * the existing owner. Tenancy must match.\n *\n * Platform projects can't be reclaimed — `instance_admin` already has\n * management access to them.\n */\nexport function canReclaim(input: ReclaimAccessInput): boolean {\n\tconst { project, orgMember, actingOrgId } = input;\n\tif (!project || !actingOrgId) return false;\n\tif (project.visibility === 'platform') return false;\n\tif (actingOrgId !== project.orgId) return false;\n\tconst role = orgMember?.role;\n\treturn role === 'owner' || role === 'admin';\n}\n\nexport interface CreateProjectAccessInput {\n\torgPermissions: readonly OrgPermission[];\n\torgMember: OrgMember | null;\n\tactingOrgId: string | null;\n\ttargetOrgId: string;\n}\n\n/**\n * Owner/admin can always create; a `member` needs `manage_projects` org\n * permission. Tenancy is enforced.\n *\n * Platform projects (`visibility: 'platform'`) go through the admin API,\n * gated on `instance_admin` — this rule isn't consulted for them.\n */\nexport function canCreateProject(input: CreateProjectAccessInput): boolean {\n\tconst { orgMember, orgPermissions, actingOrgId, targetOrgId } = input;\n\tif (actingOrgId !== targetOrgId) return false;\n\tconst role = orgMember?.role;\n\tif (role === 'owner' || role === 'admin') return true;\n\tif (role === 'member' && orgPermissions.includes('manage_projects')) return true;\n\treturn false;\n}\n\nexport interface OrgOwnerAuthorityInput {\n\t/** The acting user's own membership row, not the org's `ownerId` column. */\n\tactorMember: OrgMember | null;\n\t/** The role being granted, or the role the target already holds. */\n\trole: OrgRole;\n}\n\n/**\n * Whether the actor may hand out or take away org `owner`/`admin` standing.\n * Inviting someone as owner/admin, changing a member's role and removing an owner\n * are one rule, so all three read it here.\n *\n * Reads the actor's **membership row**. `Organization.ownerId` is a separate field\n * that can disagree with it and is not authority for this decision.\n */\nexport function canChangeOrgRole(input: OrgOwnerAuthorityInput): boolean {\n\tif (input.role === 'member') return true;\n\treturn input.actorMember?.role === 'owner';\n}\n\n/**\n * Pre-flight check for project-owner removal, run after `canManage`.\n *\n * - `ok` — proceed\n * - `sole_owner` — last owner; route surfaces 409 and suggests reclaim\n * - `needs_confirm` — owner-on-owner removal without `?confirm=true`\n */\nexport type OwnerRemovalCheck = 'ok' | 'sole_owner' | 'needs_confirm';\n\nexport interface OwnerRemovalInput {\n\ttarget: { role: 'owner' | 'editor' | 'viewer' };\n\tallMembers: readonly { role: 'owner' | 'editor' | 'viewer' }[];\n\tconfirmed: boolean;\n}\n\nexport function checkOwnerRemoval(input: OwnerRemovalInput): OwnerRemovalCheck {\n\tif (input.target.role !== 'owner') return 'ok';\n\tconst ownerCount = input.allMembers.filter((m) => m.role === 'owner').length;\n\tif (ownerCount <= 1) return 'sole_owner';\n\tif (!input.confirmed) return 'needs_confirm';\n\treturn 'ok';\n}\n","import type { RequestContext } from '../context.js';\nimport { ProviderError } from '../errors.js';\nimport { parseApiScope, type ApiScope, type ApiScopeAction, type ApiToken } from './types.js';\n\n/** The rows a request touches, when the route knows them. */\nexport interface ScopeTarget {\n\tprojectId?: string;\n\tdefinitionId?: string;\n}\n\n/**\n * May this request perform `action` on `target`?\n *\n * Without a target this is an org-level check, which only `all` and org scopes\n * pass: a project key must never reach a route that can't say which project it\n * touches. Requests without an API token always pass; their permissions are\n * checked elsewhere.\n */\nexport function scopeAllows(\n\tctx: RequestContext,\n\taction: ApiScopeAction,\n\ttarget?: ScopeTarget\n): boolean {\n\tconst api = ctx.apiScope;\n\tif (!api) return true;\n\treturn api.scopes.some(\n\t\t(s) => apiScopeActionCovers(s.action, action) && resourceCovers(s, ctx, target)\n\t);\n}\n\n/** Does a scope granting `granted` allow `wanted`? */\nexport function apiScopeActionCovers(granted: ApiScopeAction, wanted: ApiScopeAction): boolean {\n\tif (granted === wanted || wanted === 'read') return true;\n\treturn granted === 'write' && (wanted === 'upload' || wanted === 'create_projects');\n}\n\nfunction resourceCovers(scope: ApiScope, ctx: RequestContext, target?: ScopeTarget): boolean {\n\tconst { resource } = scope;\n\tswitch (resource.kind) {\n\t\tcase 'all':\n\t\t\treturn true;\n\t\tcase 'org':\n\t\t\treturn resource.id === ctx.actingOrgId;\n\t\tcase 'project':\n\t\t\treturn target?.projectId === resource.id;\n\t\tcase 'definition':\n\t\t\treturn target?.definitionId === resource.id;\n\t}\n}\n\n/**\n * Narrow the owner's live context to what the token grants. Only removes\n * rights:\n *\n * - Platform permissions are dropped. Instance authority never rides on a\n * bearer key, so an operator's leaked key can't reach other tenants.\n * - `apiScope` is attached, which `scopeAllows` reads.\n *\n * Scopes this version can't parse are dropped, so they grant nothing.\n */\nexport function narrowApiTokenContext(\n\tctx: RequestContext,\n\ttoken: Pick<ApiToken, 'id' | 'orgId' | 'scopes' | 'expiresAt'>\n): RequestContext {\n\tif (ctx.actingOrgId !== token.orgId) {\n\t\tthrow new ProviderError('API token context must act in the token’s org', 500);\n\t}\n\tconst scopes = token.scopes.map(parseApiScope).filter((s): s is ApiScope => s !== null);\n\treturn {\n\t\t...ctx,\n\t\tplatformPermissions: [],\n\t\tapiScope: { tokenId: token.id, scopes, expiresAt: token.expiresAt }\n\t};\n}\n\n/**\n * True when an API-token request reaches for something owned by an org other\n * than the token's. A token is bound to one org, so that resource doesn't\n * exist for it, even when the owner belongs to the other org too. Treat it as\n * not found. Session requests are never outside.\n */\nexport function outsideTokenOrg(ctx: RequestContext, orgId: string): boolean {\n\treturn ctx.apiScope !== undefined && orgId !== ctx.actingOrgId;\n}\n","/**\n * Structured logging seam: the interface + a safe default live here, the real\n * backend (pino) ships from `@selvajs/server` so `@selvajs/platform` never\n * gains a logging dependency and browser-side consumers never pull a Node\n * logger into a bundle. A hard pino import would also impose a transport\n * config on every embedder, including ones that already own a logging stack.\n * Call sites describe WHAT happened and hand over fields; formatting,\n * redaction and routing are the backend's business.\n */\n\n/**\n * Fields attached to one log record. Values are `unknown`, not `string`, so a\n * field survives as typed JSON (numbers stay numbers, queryable by range)\n * instead of being flattened into a message string.\n *\n * Never put secrets here — session tokens, API keys, refresh tokens, raw share\n * tokens. Log records leave the box (stdout to collector to third-party index)\n * and outlive the credential.\n */\nexport type LogFields = Record<string, unknown>;\n\n/**\n * Severity levels, ordered to match pino's set so the backend is a thin\n * pass-through and operators get the level names they expect.\n *\n * - `debug` — detail only useful when actively diagnosing; off in production.\n * - `info` — a thing happened that an operator would want in the record\n * (boot, config resolved, request completed).\n * - `warn` — degraded or suspicious, but handled; the system continues.\n * - `error` — an operation failed. Pair with `IErrorReporter` when it's\n * genuinely unexpected: logs are for the operator reading stdout,\n * the reporter is for off-box triage.\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * A structured logger.\n *\n * MUST NOT throw — logging sits on every path including the error path, where a\n * failing logger would mask the original fault. Implementations swallow their\n * own failures.\n */\nexport interface ILogger {\n\tdebug(message: string, fields?: LogFields): void;\n\tinfo(message: string, fields?: LogFields): void;\n\twarn(message: string, fields?: LogFields): void;\n\terror(message: string, fields?: LogFields): void;\n\t/**\n\t * Derive a logger that stamps `fields` onto every record it writes. The\n\t * request hook binds `requestId` (plus method/route) once via `child`, so\n\t * every downstream call site logs without knowing a request id exists.\n\t *\n\t * Children compose; a child of a child carries both parents' fields. A\n\t * child's field overwrites a parent's on key collision.\n\t */\n\tchild(fields: LogFields): ILogger;\n}\n\n/**\n * Default `ILogger` — discards everything. Lets library code log\n * unconditionally without a configured backend, and keeps test output clean.\n * The app wires a real logger at its composition root; a consumer that wires\n * nothing gets silence rather than unsolicited stdout writes.\n */\nexport class NoopLogger implements ILogger {\n\tdebug(_message: string, _fields?: LogFields): void {}\n\tinfo(_message: string, _fields?: LogFields): void {}\n\twarn(_message: string, _fields?: LogFields): void {}\n\terror(_message: string, _fields?: LogFields): void {}\n\tchild(_fields: LogFields): ILogger {\n\t\treturn this;\n\t}\n}\n","import type { IAuthProvider } from './auth/interface.js';\nimport type { IDataProvider } from './data/interface.js';\nimport type { IStorageProvider } from './storage/interface.js';\nimport type { IEventSink } from './events/interface.js';\nimport type { ISolveMetricSink } from './metrics/interface.js';\nimport type { IBindingResolver } from './bindings/interface.js';\n\n/**\n * `single`: one org per deployment, created at setup; `ctx.actingOrgId` resolves to it for\n * every user. `multi`: orgs are first-class, created by users; `ctx.actingOrgId` resolves\n * per-request.\n */\nexport type TenancyMode = 'single' | 'multi';\n\n/** White-label branding. Omitted fields fall back to \"Selva\" defaults in the selva app. */\nexport interface SelvaBranding {\n\tname?: string;\n\tcopyrightName?: string;\n\ttagline?: string;\n\tdescription?: string;\n}\n\n/** Opt-in platform features. All default false when absent. */\nexport interface SelvaFlags {\n\t/** Projects with `visibility='public'` visible across orgs on the instance. */\n\tALLOW_CROSS_ORG_PUBLIC?: boolean;\n\t/** Orgs may override the instance compute pool with their own server. */\n\tALLOW_ORG_COMPUTE_OVERRIDE?: boolean;\n\t/** Authenticated users may create new orgs. */\n\tALLOW_ORG_CREATION?: boolean;\n\t/**\n\t * Anonymous external access via tokenized URLs. When off, share-link admin\n\t * routes reject mint/list/revoke and existing tokens stop resolving.\n\t */\n\tENABLE_SHARING?: boolean;\n\t/**\n\t * Projects owned by instance admins, granted to orgs or users without normal\n\t * membership. When off, `/admin/projects` 404s and platform-visibility\n\t * projects are hidden and inaccessible; data survives the toggle either way.\n\t */\n\tENABLE_PLATFORM_PROJECTS?: boolean;\n}\n\nexport interface SelvaConfig {\n\ttenancy?: TenancyMode;\n\tflags?: SelvaFlags;\n\tbranding?: SelvaBranding;\n\tauth: IAuthProvider;\n\t/** Orgs, projects, members, definitions, compute config, user profiles, platform permissions. */\n\tdata: IDataProvider;\n\t/** Blob storage — .gh/.ghx files, archived versions, images. */\n\tstorage: IStorageProvider;\n\t/** Defaults to `NoopEventSink`. */\n\tevents?: IEventSink;\n\t/** Records per-solve wall time. Defaults to `NoopSolveMetricSink`, which discards every metric. */\n\tsolveMetrics?: ISolveMetricSink;\n\t/**\n\t * Resolves values for inputs marked `source.kind === 'server'`. Defaults to\n\t * `NoopBindingResolver`, which resolves nothing — hosts that use server-resolved\n\t * inputs must supply a real resolver.\n\t */\n\tbindingResolver?: IBindingResolver;\n}\n\nexport type SelvaConfigFactory = (env: Record<string, string | undefined>) => SelvaConfig;\n\nexport function isFlagEnabled(config: SelvaConfig, flag: keyof SelvaFlags): boolean {\n\treturn Boolean(config.flags?.[flag]);\n}\n\n/** Identity function for type inference and IDE autocomplete. */\nexport function defineConfig<T extends SelvaConfig | SelvaConfigFactory>(config: T): T {\n\treturn config;\n}\n","/**\n * Compute/solve server limits, resolved from an injected env map.\n *\n * Env comes in as a parameter — nothing ambient is read — so this is importable\n * from any runtime and testable without env plumbing. Defaults are sized for\n * typical interactive use (sliders + small uploads).\n *\n * Client-side counterparts (the in-flight compute throttle and slider debounce)\n * are bundled into the client in `@selvajs/ui` and can't read env — they carry\n * their own defaults.\n */\n\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\n\nconst MB = 1024 * 1024;\n\n/**\n * Cap on a solve request body. A `file` input embeds geometry as base64, so the\n * client's 150 MB raw file is ~200 MB on the wire, plus JSON envelope slack.\n * adapter-node's `BODY_SIZE_LIMIT` must be at least this, or it rejects first.\n */\nexport const COMPUTE_REQUEST_MAX_BYTES = 256 * MB;\n\n/** Env source: any string→string map. `$env/dynamic/private` satisfies this. */\nexport type EnvRecord = Record<string, string | undefined>;\n\n/**\n * Default logger for the env-parsing warnings below. This is library code, so an\n * embedder that wires nothing gets silence rather than unsolicited stdout writes.\n */\nconst noop = new NoopLogger();\n\n/** Parse a positive integer env value; absent, or present but not finite and positive, falls back. */\nexport function readPositiveInt(\n\tenv: EnvRecord,\n\tname: string,\n\tfallback: number,\n\tlogger: ILogger = noop\n): number {\n\tconst raw = env[name];\n\tif (!raw) return fallback;\n\tconst parsed = Number(raw);\n\tif (!Number.isFinite(parsed) || parsed <= 0) {\n\t\tlogger.warn('Invalid env value, falling back to default', {\n\t\t\tcomponent: 'selva',\n\t\t\tenvVar: name,\n\t\t\tvalue: raw,\n\t\t\tfallback\n\t\t});\n\t\treturn fallback;\n\t}\n\treturn Math.floor(parsed);\n}\n\n/** Like {@link readPositiveInt}, but `0` is valid — knobs where it means \"disable\". */\nexport function readNonNegativeInt(\n\tenv: EnvRecord,\n\tname: string,\n\tfallback: number,\n\tlogger: ILogger = noop\n): number {\n\tconst raw = env[name];\n\tif (!raw) return fallback;\n\tconst parsed = Number(raw);\n\tif (!Number.isFinite(parsed) || parsed < 0) {\n\t\tlogger.warn('Invalid env value, falling back to default', {\n\t\t\tcomponent: 'selva',\n\t\t\tenvVar: name,\n\t\t\tvalue: raw,\n\t\t\tfallback\n\t\t});\n\t\treturn fallback;\n\t}\n\treturn Math.floor(parsed);\n}\n\n/**\n * Fall back to a variable's previous name, warning when the old one is used.\n * Setting both is not an error: the new name wins silently, which is what an\n * operator mid-migration expects.\n *\n * A var that quietly stops being read looks exactly like one that is working —\n * the failure only surfaces as a memory number nobody is watching.\n */\nfunction readRenamed(env: EnvRecord, name: string, oldName: string, logger: ILogger): EnvRecord {\n\tif (env[name] !== undefined || env[oldName] === undefined) return env;\n\tlogger.warn('Deprecated env var: rename it', {\n\t\tcomponent: 'selva',\n\t\tenvVar: oldName,\n\t\trenamedTo: name\n\t});\n\treturn { ...env, [name]: env[oldName] };\n}\n\n/**\n * Parse a boolean env flag. Accepts `true/1/yes/on` and `false/0/no/off`\n * (case-insensitive); any other spelling warns and falls back.\n */\nexport function readBool(\n\tenv: EnvRecord,\n\tname: string,\n\tfallback: boolean,\n\tlogger: ILogger = noop\n): boolean {\n\tconst raw = env[name];\n\tif (raw == null || raw === '') return fallback;\n\tconst v = raw.trim().toLowerCase();\n\tif (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;\n\tif (v === 'false' || v === '0' || v === 'no' || v === 'off') return false;\n\tlogger.warn('Invalid env value, falling back to default', {\n\t\tcomponent: 'selva',\n\t\tenvVar: name,\n\t\tvalue: raw,\n\t\tfallback\n\t});\n\treturn fallback;\n}\n\n/** Fully-resolved server-side compute limits. */\nexport interface ComputeLimits {\n\t/** Fixed-window cap on /api/v1/compute: window length + max requests per window. */\n\trateLimitWindowMs: number;\n\trateLimitMaxRequests: number;\n\t/**\n\t * Largest .gh definition accepted on upload. 50 MB matches Rhino.Compute's own\n\t * `RHINO_COMPUTE_MAX_REQUEST_SIZE` default — a larger file 413s at compute\n\t * regardless, so accepting it here only defers the failure.\n\t */\n\tmaxDefinitionFileSize: number;\n\t/** Largest cover image accepted on upload. */\n\tmaxImageFileSize: number;\n\t/** /api/v1/compute JSON *request* body cap: {@link COMPUTE_REQUEST_MAX_BYTES}. */\n\tcomputeRequestMaxBytes: number;\n\t/**\n\t * /api/v1/compute JSON *response* cap. A `file`-typed output is base64-embedded\n\t * in the response; this guards V8's ~512 MB single-string wall (a\n\t * `JSON.stringify` `RangeError`) and browser-tab OOM, turning an opaque crash\n\t * into a clear 413. The real fix is out-of-band streaming.\n\t *\n\t * 300 MB is deliberate, not a dev leftover — above any legitimate inline\n\t * payload, below the V8 string wall. Unlike the request cap it is not bounded\n\t * by `BODY_SIZE_LIMIT`, which only covers inbound bodies.\n\t */\n\tcomputeResponseMaxBytes: number;\n\t/**\n\t * Hard cap on fetching a remote definition. Tracks `maxDefinitionFileSize` so a\n\t * remote URL can't smuggle a file past the upload cap.\n\t */\n\tremoteDefinitionMaxBytes: number;\n\t/** Deadline on fetching a remote definition (slow-loris protection). */\n\tremoteDefinitionFetchTimeoutMs: number;\n\t/**\n\t * TTL for the in-process cache of .gh bytes fetched from a REMOTE URL.\n\t *\n\t * Only the remote path is TTL'd, and the name says so deliberately: the other\n\t * definition cache is keyed on an immutable version id, where expiry could only\n\t * ever throw away valid work. A URL's owner can swap the file underneath us, so\n\t * that path needs a freshness bound and this is it.\n\t */\n\tremoteDefinitionCacheTtlMs: number;\n\t/**\n\t * Ask Rhino.Compute to cache solve RESULTS keyed on the full request and\n\t * return a cached result on an identical repeat. Server-wide (survives Selva\n\t * restarts, spans instances). Only helps IDENTICAL re-solves.\n\t */\n\tcomputeServerCachesolve: boolean;\n\t/**\n\t * Backpressure — max solves allowed to WAIT in the per-server FIFO queue. This\n\t * excludes in-flight solves, which the scheduler caps at `maxConcurrent`,\n\t * auto-detected from the compute server's active child count. A solve arriving\n\t * at a full queue is rejected on the spot (scheduler `QUEUE_FULL` → HTTP 503 +\n\t * `Retry-After`) instead of piling up. `0` = unbounded, the default.\n\t *\n\t * Size it to roughly 2–3× the compute server's child count once you know the\n\t * Rhino pool's real capacity — rejecting fast beats a hung request.\n\t */\n\tcomputeMaxQueueDepth: number;\n\t/**\n\t * Backpressure — longest (ms) a solve may sit QUEUED before it starts\n\t * executing. Still waiting past this, it's rejected (scheduler `QUEUE_TIMEOUT`\n\t * → HTTP 503 + `Retry-After`) rather than burning compute on a stale request.\n\t * `0` = no queue deadline, the default.\n\t *\n\t * Bounds tail latency: the scheduler's `timeoutMs` clock starts at execution,\n\t * so without this a solve's total wait is unbounded and invisible. Tune it to\n\t * about the compute server's own timeout.\n\t */\n\tcomputeQueueWaitMs: number;\n\t/**\n\t * **Definition cache** — total-byte budget for the in-process cache of .gh bytes\n\t * keyed on immutable version id. A warm entry lets a solve skip `storage.get`;\n\t * `0` disables it, so every solve re-reads storage. A byte LRU rather than an\n\t * entry count because definitions span KB→hundreds of MB. Env value is MB.\n\t */\n\tcomputeDefinitionCacheBytes: number;\n\t/**\n\t * **Solve cache** — total-byte budget for EACH warm client's in-process cache of\n\t * solve results (the `fromCache` layer in front of Rhino.Compute). `0` disables\n\t * it, so every solve goes to compute. Results span KB→100s of MB\n\t * (`computeResponseMaxBytes` allows 300 MB), so an entry count alone can't bound\n\t * heap; this adds a byte LRU on top. Env value is MB.\n\t *\n\t * **Per warm client, so the worst case multiplies.** Selva keeps up to\n\t * `maxWarmComputeServers` (default 16) compute servers warm, making the real\n\t * ceiling this × 16 — 4 GB at the default. Most deployments run 1–2 servers,\n\t * which is why the default is comfortable; a fan-out across many servers on a\n\t * small VPS is the case this knob exists for.\n\t */\n\tcomputeSolveCacheBytes: number;\n}\n\n/**\n * Resolve every server-side compute limit from an env map. The app calls this\n * once at its composition root with `$env/dynamic/private`.\n */\nexport function resolveComputeLimits(env: EnvRecord, logger: ILogger = noop): ComputeLimits {\n\t// Deprecation shims, so each var says what it HOLDS and what it bounds — one\n\t// solve — rather than a vague \"duration\". Drop one minor version on.\n\tenv = readRenamed(env, 'COMPUTE_DEFINITION_CACHE_MB', 'COMPUTE_DEFINITION_BYTE_CACHE_MB', logger);\n\tenv = readRenamed(env, 'COMPUTE_SOLVE_CACHE_MB', 'COMPUTE_RESPONSE_CACHE_MB', logger);\n\n\t// Clean-cut rename with no old-name dual-read: deliberate pre-1.0 breaking change.\n\tconst maxDefinitionFileSize = readPositiveInt(\n\t\tenv,\n\t\t'MAX_DEFINITION_FILE_SIZE_BYTES',\n\t\t50 * MB,\n\t\tlogger\n\t);\n\treturn {\n\t\trateLimitWindowMs: 100_000,\n\t\trateLimitMaxRequests: readPositiveInt(env, 'COMPUTE_RATE_LIMIT_MAX', 120, logger),\n\t\tmaxDefinitionFileSize,\n\t\tmaxImageFileSize: 10 * MB,\n\t\tcomputeRequestMaxBytes: COMPUTE_REQUEST_MAX_BYTES,\n\t\tcomputeResponseMaxBytes: 300 * MB,\n\t\tremoteDefinitionMaxBytes: maxDefinitionFileSize,\n\t\tremoteDefinitionFetchTimeoutMs: 30_000,\n\t\tremoteDefinitionCacheTtlMs: 5 * 60 * 1000,\n\t\tcomputeServerCachesolve: readBool(env, 'COMPUTE_SERVER_CACHESOLVE', true, logger),\n\t\t// Both default to off — nothing is rejected until an operator who has measured\n\t\t// their pool opts in. readNonNegativeInt throughout, so `0` reads as \"disabled\"\n\t\t// rather than as an invalid value that falls back.\n\t\tcomputeMaxQueueDepth: readNonNegativeInt(env, 'COMPUTE_MAX_QUEUE_DEPTH', 0, logger),\n\t\tcomputeQueueWaitMs: readNonNegativeInt(env, 'COMPUTE_QUEUE_WAIT_MS', 0, logger),\n\t\t// 256 MB holds a handful of typical definitions warm without pinning gigabytes.\n\t\tcomputeDefinitionCacheBytes:\n\t\t\treadNonNegativeInt(env, 'COMPUTE_DEFINITION_CACHE_MB', 256, logger) * MB,\n\t\t// 256 MB keeps a scrub session's recent solves warm; PER warm client, so see\n\t\t// the field doc for the ×16 worst case.\n\t\tcomputeSolveCacheBytes: readNonNegativeInt(env, 'COMPUTE_SOLVE_CACHE_MB', 256, logger) * MB\n\t};\n}\n","/**\n * The transport-free error type every API handler raises.\n *\n * `apiError` used to throw SvelteKit's `error()` directly, which welded all 151\n * of its call sites to one framework. `ApiError` carries the same envelope as a\n * plain exception; the host adapter converts it to whatever its framework\n * expects (see `toApiResponse`). Call sites are unchanged — only the throw\n * site and the boundary know the difference.\n */\n\n/** Stable, machine-readable error codes. Append-only — never renumber/rename. */\nexport const ApiErrorCode = {\n\tVALIDATION_FAILED: 'VALIDATION_FAILED',\n\tUNAUTHORIZED: 'UNAUTHORIZED',\n\tFORBIDDEN: 'FORBIDDEN',\n\tNOT_FOUND: 'NOT_FOUND',\n\tCONFLICT: 'CONFLICT',\n\tUNPROCESSABLE: 'UNPROCESSABLE',\n\tCOMPUTE_UNAVAILABLE: 'COMPUTE_UNAVAILABLE',\n\tSETUP_REQUIRED: 'SETUP_REQUIRED',\n\tINTERNAL: 'INTERNAL',\n\t/** API tokens are switched off or misconfigured here; browser sessions still work. */\n\tAPI_TOKENS_UNAVAILABLE: 'API_TOKENS_UNAVAILABLE',\n\t/** Too many requests, or a share link's solve cap is spent. `Retry-After`, when sent, says when to retry. */\n\tRATE_LIMITED: 'RATE_LIMITED',\n\t/** The key is valid, but the host's holder policy no longer lets its owner hold API tokens. */\n\tAPI_TOKEN_HOLDER_REFUSED: 'API_TOKEN_HOLDER_REFUSED',\n\t/** The caller's last sign-in at the identity provider is too old for this; sign in again. */\n\tSIGN_IN_REQUIRED: 'SIGN_IN_REQUIRED'\n} as const;\n\nexport type ApiErrorCode = (typeof ApiErrorCode)[keyof typeof ApiErrorCode];\n\nexport class ApiError extends Error {\n\treadonly status: number;\n\treadonly code: ApiErrorCode;\n\t/** Per-field validation messages, keyed by dotted path. Only on VALIDATION_FAILED. */\n\treadonly fields?: Record<string, string>;\n\t/** Machine-readable context, e.g. `requiredScope` on a scope refusal. */\n\treadonly details?: Record<string, string>;\n\n\tconstructor(\n\t\tstatus: number,\n\t\tcode: ApiErrorCode,\n\t\tmessage: string,\n\t\tfields?: Record<string, string>,\n\t\tdetails?: Record<string, string>\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'ApiError';\n\t\tthis.status = status;\n\t\tthis.code = code;\n\t\tthis.fields = fields;\n\t\tthis.details = details;\n\t}\n}\n\nexport interface ApiErrorBody {\n\tmessage: string;\n\tcode: ApiErrorCode;\n\tfields?: Record<string, string>;\n\tdetails?: Record<string, string>;\n}\n\nexport function toErrorBody(err: ApiError): ApiErrorBody {\n\tconst body: ApiErrorBody = { message: err.message, code: err.code };\n\tif (err.fields) body.fields = err.fields;\n\tif (err.details) body.details = err.details;\n\treturn body;\n}\n\nexport function isApiError(err: unknown): err is ApiError {\n\treturn err instanceof ApiError;\n}\n\n/** Raise a structured API error. The only way handlers should fail. */\nexport function apiError(\n\tstatus: number,\n\tcode: ApiErrorCode,\n\tmessage: string,\n\tfields?: Record<string, string>,\n\tdetails?: Record<string, string>\n): never {\n\tthrow new ApiError(status, code, message, fields, details);\n}\n\n/** Default code for a status, for mapping errors that carry no code of their own. */\nexport function codeForStatus(status: number): ApiErrorCode {\n\tswitch (status) {\n\t\tcase 400:\n\t\t\treturn ApiErrorCode.VALIDATION_FAILED;\n\t\tcase 401:\n\t\t\treturn ApiErrorCode.UNAUTHORIZED;\n\t\tcase 403:\n\t\t\treturn ApiErrorCode.FORBIDDEN;\n\t\tcase 404:\n\t\t\treturn ApiErrorCode.NOT_FOUND;\n\t\tcase 409:\n\t\t\treturn ApiErrorCode.CONFLICT;\n\t\tcase 422:\n\t\t\treturn ApiErrorCode.UNPROCESSABLE;\n\t\tcase 429:\n\t\t\treturn ApiErrorCode.RATE_LIMITED;\n\t\tcase 503:\n\t\t\treturn ApiErrorCode.COMPUTE_UNAVAILABLE;\n\t\tdefault:\n\t\t\treturn ApiErrorCode.INTERNAL;\n\t}\n}\n","import type { Project, ProjectAccessInput, RequestContext } from '@selvajs/platform';\n\n/**\n * Marshals an app's providers into the one input shape platform's pure access\n * rules (`canView`/`canEdit`/`canSolve`/`canManage`/…) read. What lives here is\n * **which rows each visibility needs**, so a consuming app doesn't reimplement\n * and mis-fetch it:\n *\n * - `platform` → grants (skipped entirely while the feature flag is off)\n * - `private` → caller's project member row\n * - `org` / `public` → caller's project member row (for canEdit/canManage) and\n * org member row (for canView). Cross-org public skips the org row.\n *\n * Row lookups are injected as functions so lazily-initialized providers work\n * unchanged, and flags are read per call so runtime flips behave like the app's\n * own `flag()` reads.\n */\n\nexport interface ProjectAccessFlags {\n\t/** `ALLOW_CROSS_ORG_PUBLIC` — public visibility spans orgs when true. */\n\tallowCrossOrgPublic: boolean;\n\t/** `ENABLE_PLATFORM_PROJECTS` — platform visibility is live when true. */\n\tenablePlatformProjects: boolean;\n}\n\nexport interface ProjectAccessInputDeps {\n\tgetProjectMember(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\tuserId: string\n\t): Promise<ProjectAccessInput['member']>;\n\tgetOrgMember(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string\n\t): Promise<ProjectAccessInput['orgMember']>;\n\tlistPlatformGrants(\n\t\tctx: RequestContext,\n\t\tprojectId: string\n\t): Promise<ProjectAccessInput['platformGrants']>;\n\t/** Read the two access-relevant feature flags. Called once per assembly. */\n\tflags(): ProjectAccessFlags;\n}\n\nexport interface ProjectAccessInputBuilder {\n\t/**\n\t * Fetches exactly the rows the rule will consult, based on\n\t * `project.visibility`. Other fields default to safe values; `overrides` is\n\t * for the rare caller that already loaded a row (tests, batched listings).\n\t */\n\tbuildProjectAccessInput(\n\t\tctx: RequestContext,\n\t\tproject: Project,\n\t\toverrides?: Partial<ProjectAccessInput>\n\t): Promise<ProjectAccessInput>;\n\t/**\n\t * Same input, from caller-provided rows and no I/O. A listing page that has\n\t * batch-loaded membership calls this per row instead of\n\t * `buildProjectAccessInput`, which would fetch N+1 times.\n\t */\n\tprojectAccessInputFromRows(\n\t\tctx: RequestContext,\n\t\tproject: Project,\n\t\trows: {\n\t\t\tmember?: ProjectAccessInput['member'];\n\t\t\torgMember?: ProjectAccessInput['orgMember'];\n\t\t\tplatformGrants?: ProjectAccessInput['platformGrants'];\n\t\t}\n\t): ProjectAccessInput;\n}\n\nexport function createProjectAccessInputBuilder(\n\tdeps: ProjectAccessInputDeps\n): ProjectAccessInputBuilder {\n\treturn {\n\t\tasync buildProjectAccessInput(\n\t\t\tctx: RequestContext,\n\t\t\tproject: Project,\n\t\t\toverrides: Partial<ProjectAccessInput> = {}\n\t\t): Promise<ProjectAccessInput> {\n\t\t\tconst { allowCrossOrgPublic, enablePlatformProjects } = deps.flags();\n\n\t\t\tlet member: ProjectAccessInput['member'] = null;\n\t\t\tlet orgMember: ProjectAccessInput['orgMember'] = null;\n\t\t\tlet platformGrants: ProjectAccessInput['platformGrants'] = [];\n\n\t\t\tif (project.visibility === 'platform') {\n\t\t\t\t// With the flag off every rule returns false before reading grants,\n\t\t\t\t// so the lookup would be wasted I/O.\n\t\t\t\tif (enablePlatformProjects) {\n\t\t\t\t\tplatformGrants = await deps.listPlatformGrants(ctx, project.id);\n\t\t\t\t}\n\t\t\t} else if (project.visibility === 'private') {\n\t\t\t\tmember = await deps.getProjectMember(ctx, project.id, ctx.userId);\n\t\t\t} else {\n\t\t\t\tconst skipOrgMember = project.visibility === 'public' && allowCrossOrgPublic;\n\t\t\t\t[member, orgMember] = await Promise.all([\n\t\t\t\t\tdeps.getProjectMember(ctx, project.id, ctx.userId),\n\t\t\t\t\tskipOrgMember ? Promise.resolve(null) : deps.getOrgMember(ctx, project.orgId, ctx.userId)\n\t\t\t\t]);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\torgPermissions: ctx.orgPermissions,\n\t\t\t\tplatformPermissions: ctx.platformPermissions,\n\t\t\t\tproject,\n\t\t\t\tmember,\n\t\t\t\torgMember,\n\t\t\t\tallowCrossOrgPublic,\n\t\t\t\tenablePlatformProjects,\n\t\t\t\tplatformGrants,\n\t\t\t\tactingOrgId: ctx.actingOrgId ?? null,\n\t\t\t\tuserId: ctx.userId,\n\t\t\t\t...overrides\n\t\t\t};\n\t\t},\n\n\t\tprojectAccessInputFromRows(\n\t\t\tctx: RequestContext,\n\t\t\tproject: Project,\n\t\t\trows: {\n\t\t\t\tmember?: ProjectAccessInput['member'];\n\t\t\t\torgMember?: ProjectAccessInput['orgMember'];\n\t\t\t\tplatformGrants?: ProjectAccessInput['platformGrants'];\n\t\t\t}\n\t\t): ProjectAccessInput {\n\t\t\tconst { allowCrossOrgPublic, enablePlatformProjects } = deps.flags();\n\t\t\treturn {\n\t\t\t\torgPermissions: ctx.orgPermissions,\n\t\t\t\tplatformPermissions: ctx.platformPermissions,\n\t\t\t\tproject,\n\t\t\t\tmember: rows.member ?? null,\n\t\t\t\torgMember: rows.orgMember ?? null,\n\t\t\t\tallowCrossOrgPublic,\n\t\t\t\tenablePlatformProjects,\n\t\t\t\tplatformGrants: rows.platformGrants ?? [],\n\t\t\t\tactingOrgId: ctx.actingOrgId ?? null,\n\t\t\t\tuserId: ctx.userId\n\t\t\t};\n\t\t}\n\t};\n}\n","/**\n * The permission guards every API handler runs before touching a store.\n *\n * These name no framework. A guard raises `ApiError`, which `runHandler` folds\n * into the response envelope — so the same guard protects a SvelteKit route, a\n * Next route handler, or a Hono route behind that host's own adapter.\n *\n * **Guards that redirect stay with the host.** A redirect is a browser-page\n * concept, not an API one, and a framework implements it by throwing a value\n * only that framework understands.\n *\n * A caller outside an API route — a page load, or a route that builds its own\n * `Response` — has to convert the `ApiError` at its boundary, since a framework\n * will not recognize it. Selva does that with `asHttpError` in\n * `access.server.ts`; SvelteKit gives anything that is not its own `HttpError` a\n * 500, so an unconverted guard denial reads as a crash.\n *\n * Providers arrive through {@link AccessDeps} rather than being resolved here.\n * That is what keeps this module importable without booting an app: a guard\n * that reached for a module global would drag the whole composition root — and\n * its top-level `await createSelvaProviders()` — into every consumer.\n */\n\nimport type {\n\tAuthUser,\n\tDefinitionRecord,\n\tOrgMember,\n\tOrgPermission,\n\tOrgRole,\n\tPlatformPermission,\n\tProject,\n\tProjectVisibility,\n\tRequestContext,\n\tSelvaConfig\n} from '@selvajs/platform';\nimport {\n\tisFlagEnabled,\n\thasPermission,\n\tcanReclaim,\n\tcanCreateProject,\n\tcanChangeOrgRole,\n\tcanView,\n\tcanSolve,\n\tcanCreateDefinition,\n\tcanManage,\n\tcanEditProjectSettings,\n\tcanEditDefinition,\n\tcanChangeVisibilityToPublic,\n\toutsideTokenOrg,\n\tscopeAllows,\n\tSYSTEM_CONTEXT\n} from '@selvajs/platform';\nimport {\n\tcreateProjectAccessInputBuilder,\n\ttype ProjectAccessInputBuilder\n} from './project-access-input.js';\nimport { apiError, ApiErrorCode } from '../api/errors.js';\nimport type { SelvaDeps } from '../api/deps.js';\n\nexport type AnyPermission = PlatformPermission | OrgPermission;\n\n/**\n * What the permission-only guards read.\n *\n * `deps` is absent here on purpose: `requirePermission` and friends check\n * `ctx.platformPermissions` and touch no store, so demanding providers from\n * their callers — the ~20 admin routes and page loads that only ever ask \"may\n * this user do X?\" — would be a cost with nothing behind it. The guards that do\n * read stores take `HasDeps` instead, which requires them.\n */\nexport interface Locals {\n\tuser?: AuthUser;\n\tctx?: RequestContext;\n}\n\n/**\n * What a store-reading guard takes: identity plus the providers to read with.\n *\n * `ApiRequest` satisfies this structurally, so a mounted handler passes itself.\n * Everyone else passes `scoped(locals)`.\n */\ntype ScopedLocals = Locals & HasDeps;\n\n/**\n * The stores a guard reads, injected rather than resolved.\n *\n * `ApiRequest` satisfies this structurally, so a mounted handler passes itself\n * and the guard runs against that request's providers.\n *\n * **Required, not optional.** These guards used to fall back to a host's module\n * globals when no `deps` arrived, which meant importing this file pulled in that\n * host's composition root — in Selva a module running a top-level\n * `await createSelvaProviders()`, so any handler importing a guard booted the\n * whole provider stack. That is what kept these guards in the app; a caller with\n * no `deps` in hand builds them with `accessDepsFromConfig`.\n */\nexport type AccessDeps = Pick<\n\tSelvaDeps,\n\t'orgs' | 'projects' | 'definitionMeta' | 'platformProjectGrants' | 'flag'\n>;\n\ninterface HasDeps {\n\tdeps: AccessDeps;\n}\n\n/**\n * Derive the stores a guard needs from a resolved config.\n *\n * Pure — it reads the config it is handed and nothing else, which is what keeps\n * this module free of any import that boots the app. Page loads pass\n * `locals.providers`; `hooks.server.ts` sets it on every request.\n */\nexport function accessDepsFromConfig(config: SelvaConfig): AccessDeps {\n\treturn {\n\t\torgs: config.data.orgs,\n\t\tprojects: config.data.projects,\n\t\tdefinitionMeta: config.data.definitions,\n\t\tplatformProjectGrants: config.data.platformProjectGrants,\n\t\tflag: (name) => isFlagEnabled(config, name)\n\t};\n}\n\n/** `locals` as a store-reading guard wants it. */\nexport function scoped<L extends Locals & { providers: SelvaConfig }>(\n\tlocals: L\n): L & { deps: AccessDeps } {\n\treturn { ...locals, deps: accessDepsFromConfig(locals.providers) };\n}\n\n// Accessors rather than `src.deps.orgs` inline: they keep the 17 call sites\n// below reading the same as before, and they are the single place that would\n// change if `AccessDeps` grew a store.\nconst orgsOf = (src: HasDeps) => src.deps.orgs;\nconst projectsOf = (src: HasDeps) => src.deps.projects;\nconst definitionMetaOf = (src: HasDeps) => src.deps.definitionMeta;\nconst flagOf = (src: HasDeps) => src.deps.flag;\n\nexport function requireAuthed(locals: Locals): { user: AuthUser; ctx: RequestContext } {\n\tconst { user, ctx } = locals;\n\tif (!user || !ctx) apiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\treturn { user, ctx };\n}\n\n/** Throws 403 — use in API routes. */\nexport function requirePermission(locals: Locals, permission: AnyPermission): AuthUser {\n\tconst { user, ctx } = requireAuthed(locals);\n\tif (!hasPermission(ctx, permission)) {\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, `You don't have permission to do this.`);\n\t}\n\treturn user;\n}\n\n// Named aliases exist only for permissions with real call sites. Routes gating\n// on anything else call `requirePermission(locals, '…')` directly rather than\n// growing an alias per permission — `manage_definitions` and `manage_projects`\n// had wrappers that nothing ever called.\nexport const requireManageInstanceUsers = (locals: Locals) =>\n\trequirePermission(locals, 'manage_instance_users');\nexport const requireManageCompute = (locals: Locals) => requirePermission(locals, 'manage_compute');\nexport const requireManageOrgMembers = (locals: Locals) =>\n\trequirePermission(locals, 'manage_org_members');\nexport const requireManageOrgCompute = (locals: Locals) =>\n\trequirePermission(locals, 'manage_org_compute');\n\nexport const requireInstanceAdmin = (locals: Locals) => requirePermission(locals, 'instance_admin');\n\n/**\n * Platform scope is not delegable: `manage_instance_users` runs the user-admin\n * surface but must not be able to mint an `instance_admin`, or an org admin\n * holding it self-elevates. Three routes write platform permissions — the two\n * `/api/admin/users` handlers and the invite mint route — and each carried its\n * own copy of this check.\n *\n * Pass `current` on an update. Revoking is a platform-scope change too, so a\n * PATCH that drops `instance_admin` is refused for the same reason granting it\n * is; without `current` the caller is creating (a user, an invite) and there is\n * nothing to compare against.\n *\n * Requesting nothing on a create is always allowed — that is a\n * `manage_instance_users` operation, not a platform-scope one.\n */\nexport function assertCanGrantPlatformPermissions(\n\tctx: RequestContext,\n\trequested: readonly PlatformPermission[],\n\tcurrent?: readonly PlatformPermission[]\n): void {\n\tconst changed = current\n\t\t? requested.length !== current.length ||\n\t\t\trequested.some((p) => !current.includes(p)) ||\n\t\t\tcurrent.some((p) => !requested.includes(p))\n\t\t: requested.length > 0;\n\tif (!changed) return;\n\tif (hasPermission(ctx, 'instance_admin')) return;\n\tapiError(\n\t\t403,\n\t\tApiErrorCode.FORBIDDEN,\n\t\tcurrent\n\t\t\t? 'Only a platform admin can change platform-scope permissions'\n\t\t\t: 'Only a platform admin can grant platform-scope permissions'\n\t);\n}\n\n/**\n * Tenancy gate for `/api/v1/orgs/{orgId}/…`. The URL id is never trusted alone\n * — the acting context decides which tenant a request applies to, so a\n * mismatch is 403 rather than a silent read of the caller's own org.\n */\nexport function requireActingOrg(\n\tlocals: Locals,\n\torgId: string | undefined\n): { ctx: RequestContext; orgId: string } {\n\tconst ctx = locals.ctx;\n\tif (!ctx) apiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\tif (!orgId) apiError(400, ApiErrorCode.VALIDATION_FAILED, 'Missing org ID');\n\tif (!ctx.actingOrgId) apiError(400, ApiErrorCode.VALIDATION_FAILED, 'No active organization');\n\tif (ctx.actingOrgId !== orgId) {\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'Acting org does not match the target org.');\n\t}\n\treturn { ctx, orgId };\n}\n\n/**\n * Gate for pages reachable by any platform-class permission holder (the\n\n/**\n * Management-scope bypass — used for org governance and project management\n * actions (Reclaim, create project, delete project, manage members, edit\n * settings). `instance_admin` bypasses these so platform staff can administer\n * the instance without being a member of every org.\n *\n * NOT used for content access (view, solve, edit definitions):\n * `instance_admin` follows the same `canView`/`canEdit` rules as any other\n * user there, keeping blast radius small and forcing content escalation\n * through Reclaim, which leaves an audit trail.\n */\nasync function managementBypassOrRun(\n\tctx: RequestContext,\n\tcheck: () => Promise<boolean>\n): Promise<boolean> {\n\tif (hasPermission(ctx, 'instance_admin')) return true;\n\treturn await check();\n}\n\n// Content-scope check — NO `instance_admin` bypass. `canView`, `canSolve`,\n// `canEdit`, and `canEditDefinition` run as-is regardless of platform role;\n// platform staff use Reclaim first if they need content access.\nasync function contentCheck(check: () => Promise<boolean>): Promise<boolean> {\n\treturn await check();\n}\n\n// With ENABLE_PLATFORM_PROJECTS off every rule denies a platform project, even for\n// `instance_admin`, so the bypass must not reopen it.\nfunction managementBypassForProject(\n\tctx: RequestContext,\n\tproject: Project,\n\tsrc: HasDeps,\n\tcheck: () => Promise<boolean>\n): Promise<boolean> {\n\tif (project.visibility === 'platform' && !flagOf(src)('ENABLE_PLATFORM_PROJECTS')) {\n\t\treturn check();\n\t}\n\treturn managementBypassOrRun(ctx, check);\n}\n\nasync function loadProjectOr404(\n\tctx: RequestContext,\n\tprojectId: string,\n\tsrc: HasDeps\n): Promise<Project> {\n\tconst project = await projectsOf(src).getProject(ctx, projectId);\n\tif (!project || outsideTokenOrg(ctx, project.orgId)) {\n\t\tapiError(404, ApiErrorCode.NOT_FOUND, 'Project not found');\n\t}\n\treturn project;\n}\n\n// Rule-input assembly (the \"which rows does each visibility need\" knowledge)\n// lives in `@selvajs/server/access`; this binding wires it to the provider set\n// the caller carries.\nfunction accessInputsFor(src: HasDeps) {\n\tconst readFlag = flagOf(src);\n\treturn createProjectAccessInputBuilder({\n\t\tgetProjectMember: (ctx, projectId, userId) =>\n\t\t\tprojectsOf(src).getProjectMember(ctx, projectId, userId),\n\t\tgetOrgMember: (ctx, orgId, userId) => orgsOf(src).getOrgMember(ctx, orgId, userId),\n\t\tlistPlatformGrants: (ctx, projectId) =>\n\t\t\tsrc.deps.platformProjectGrants.listByProject(ctx, projectId),\n\t\tflags: () => ({\n\t\t\tallowCrossOrgPublic: readFlag('ALLOW_CROSS_ORG_PUBLIC'),\n\t\t\tenablePlatformProjects: readFlag('ENABLE_PLATFORM_PROJECTS')\n\t\t})\n\t});\n}\n\nfunction buildProjectAccessInput(\n\tctx: RequestContext,\n\tproject: Project,\n\tsrc: HasDeps,\n\toverrides?: Parameters<ProjectAccessInputBuilder['buildProjectAccessInput']>[2]\n) {\n\treturn accessInputsFor(src).buildProjectAccessInput(ctx, project, overrides);\n}\n\n/**\n * Assemble a rule input from rows the caller already loaded.\n *\n * Unlike the other builders this one issues no reads — the caller batched them.\n * It still needs `deps` for the flag lookups, which decide whether a\n * cross-org-public or platform project is visible at all.\n */\nexport function projectAccessInputFromRowsWith(\n\tsrc: HasDeps,\n\t...args: Parameters<ProjectAccessInputBuilder['projectAccessInputFromRows']>\n) {\n\treturn accessInputsFor(src).projectAccessInputFromRows(...args);\n}\n\n/**\n * Gates creation of a *new* definition. Container projects require project\n * owner/editor (canEdit). Commons projects (`autoJoinOnUpload=true`) accept\n * any authenticated user — the handler stamps `ownerId = user.id` so the\n * uploader becomes the owner.\n */\nexport async function requireCanCreateDefinition(\n\tlocals: ScopedLocals,\n\tprojectId: string\n): Promise<{ user: AuthUser; ctx: RequestContext; project: Project }> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst project = await loadProjectOr404(ctx, projectId, locals);\n\tconst allowed = await contentCheck(async () =>\n\t\tcanCreateDefinition(await buildProjectAccessInput(ctx, project, locals))\n\t);\n\tif (!allowed) {\n\t\tapiError(\n\t\t\t403,\n\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\t'You do not have permission to upload definitions to this project.'\n\t\t);\n\t}\n\treturn { user, ctx, project };\n}\n\n/**\n * Project members must belong to the project's parent org. Enforced at the\n * rule layer, not as a DB constraint, to leave room for cross-org guests\n * later without a schema migration.\n */\nexport async function requireTargetIsOrgMember(\n\tlocals: ScopedLocals,\n\torgId: string,\n\ttargetUserId: string\n): Promise<void> {\n\tconst { ctx } = requireAuthed(locals);\n\tconst member = await orgsOf(locals).getOrgMember(ctx, orgId, targetUserId);\n\tif (!member) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t'User must be a member of this organization to be added to a project.'\n\t\t);\n\t}\n}\n\n/**\n * `canChangeOrgRole` with the actor's membership row loaded — whether the\n * caller may grant or revoke org `owner`/`admin` standing (§3).\n *\n * Returns rather than throws: the three callers each phrase the refusal for\n * what they were doing (\"invite someone as owner\", \"change roles\", \"remove\n * another owner\") and raise it through `apiError`. What must not diverge is the\n * decision, which is why that half lives in `rules.ts` and this loads its input.\n */\nexport async function canActorChangeOrgRole(\n\tctx: RequestContext,\n\torgId: string,\n\trole: OrgRole,\n\tsrc: HasDeps\n): Promise<boolean> {\n\tif (role === 'member') return true;\n\tconst actorMember = await orgsOf(src).getOrgMember(ctx, orgId, ctx.userId);\n\treturn canChangeOrgRole({ actorMember, role });\n}\n\n/**\n * `canReclaim` — org owner/admin escape hatch. Returns the project so the\n * handler can use its `orgId` without re-fetching.\n */\nexport async function requireCanReclaim(\n\tlocals: ScopedLocals,\n\tprojectId: string\n): Promise<{ user: AuthUser; ctx: RequestContext; project: Project }> {\n\tconst { user, ctx } = requireAuthed(locals);\n\t// Reclaim exists for projects the caller cannot see, and RLS hides those from\n\t// their own session. Only the org's leadership may learn that one exists.\n\tconst visible = await projectsOf(locals).getProject(ctx, projectId);\n\tconst project = visible ?? (await projectsOf(locals).getProject(SYSTEM_CONTEXT, projectId));\n\tif (\n\t\t!project ||\n\t\toutsideTokenOrg(ctx, project.orgId) ||\n\t\t(!visible && project.orgId !== ctx.actingOrgId)\n\t) {\n\t\tapiError(404, ApiErrorCode.NOT_FOUND, 'Project not found');\n\t}\n\n\t// Ahead of the bypass, not inside the check: `instance_admin` short-circuits\n\t// `managementBypassOrRun`, so `canReclaim`'s platform-project refusal (§4a)\n\t// never ran for the one role that could reach it. Reclaim is content\n\t// escalation wearing management clothing — the management bypass is not its\n\t// to inherit.\n\tif (project.visibility === 'platform') {\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'Platform projects cannot be reclaimed.');\n\t}\n\n\tconst allowed = await managementBypassOrRun(ctx, async () => {\n\t\tconst orgMember = await orgsOf(locals).getOrgMember(ctx, project.orgId, ctx.userId);\n\t\treturn canReclaim({\n\t\t\tproject,\n\t\t\torgMember,\n\t\t\tactingOrgId: ctx.actingOrgId ?? null\n\t\t});\n\t});\n\tif (!allowed) {\n\t\tif (!visible) apiError(404, ApiErrorCode.NOT_FOUND, 'Project not found');\n\t\tapiError(\n\t\t\t403,\n\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\t'Only org owners or admins of this project’s org can reclaim it.'\n\t\t);\n\t}\n\treturn { user, ctx, project };\n}\n\n/**\n * May the caller create a project in `targetOrgId`? Owner/admin always; a\n * member needs `manage_projects`; tenancy is enforced via `actingOrgId`. An\n * API key also needs the `create_projects` scope (or `write`) org-wide.\n */\nexport async function canCreateProjectIn(\n\tlocals: ScopedLocals,\n\tctx: RequestContext,\n\ttargetOrgId: string\n): Promise<boolean> {\n\tif (!scopeAllows(ctx, 'create_projects')) return false;\n\treturn managementBypassOrRun(ctx, async () => {\n\t\tconst orgMember = await orgsOf(locals).getOrgMember(ctx, targetOrgId, ctx.userId);\n\t\treturn canCreateProject({\n\t\t\torgPermissions: ctx.orgPermissions,\n\t\t\torgMember,\n\t\t\tactingOrgId: ctx.actingOrgId ?? null,\n\t\t\ttargetOrgId\n\t\t});\n\t});\n}\n\nexport async function requireCanCreateProject(\n\tlocals: ScopedLocals,\n\ttargetOrgId: string\n): Promise<{ user: AuthUser; ctx: RequestContext }> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tif (!(await canCreateProjectIn(locals, ctx, targetOrgId)))\n\t\tapiError(\n\t\t\t403,\n\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\t'You do not have permission to create projects in this org.'\n\t\t);\n\treturn { user, ctx };\n}\n\n/**\n * The visibility a project may be created with or changed to, for create and\n * PATCH alike. `current` is absent on create.\n *\n * - `platform` takes a project out of its org entirely (no org member sees it,\n * and with ENABLE_PLATFORM_PROJECTS off every rule denies everyone), so\n * moving into it is instance-admin only.\n * - Becoming `public` is a disclosure, so it needs an org owner or admin.\n * - A key without `write` creates private projects only, never joinable ones:\n * whoever approved it was told it can't share anything.\n */\nexport async function requireProjectVisibilityAllowed(\n\tlocals: ScopedLocals,\n\tctx: RequestContext,\n\torgId: string,\n\tnext: { visibility?: ProjectVisibility; autoJoinOnUpload?: boolean },\n\tcurrent?: Pick<Project, 'visibility'>\n): Promise<void> {\n\t// Create only: PATCH already needs `write` on the project, which the mount checks with its target.\n\tif (!current && ctx.apiScope && !scopeAllows(ctx, 'write')) {\n\t\tif (next.visibility !== 'private' || next.autoJoinOnUpload === true) {\n\t\t\tapiError(\n\t\t\t\t403,\n\t\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\t\t'This API token can only create private projects that nobody joins on upload.'\n\t\t\t);\n\t\t}\n\t}\n\tif (next.visibility === 'platform' && current?.visibility !== 'platform') {\n\t\tif (!hasPermission(ctx, 'instance_admin')) {\n\t\t\tapiError(\n\t\t\t\t403,\n\t\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\t\t'Only a platform admin can give a project platform visibility.'\n\t\t\t);\n\t\t}\n\t}\n\tif (next.visibility === 'public' && current?.visibility !== 'public') {\n\t\tconst passes = await managementBypassOrRun(ctx, async () =>\n\t\t\tcanChangeVisibilityToPublic({\n\t\t\t\torgMember: await orgsOf(locals).getOrgMember(ctx, orgId, ctx.userId)\n\t\t\t})\n\t\t);\n\t\tif (!passes) {\n\t\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'Only org owners or admins can make a project public.');\n\t\t}\n\t}\n}\n\n/**\n * Project-management gate (`canManage` — owner, or `instance_admin` via the\n * bypass). Managing members is the same authority as managing the project, so\n * both callers share this; `action` only shapes the 403 message.\n */\nexport async function requireCanManage(\n\tlocals: ScopedLocals,\n\tprojectId: string,\n\taction: 'project' | 'members' = 'project'\n): Promise<AuthUser> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst project = await loadProjectOr404(ctx, projectId, locals);\n\tconst allowed = await managementBypassForProject(ctx, project, locals, async () =>\n\t\tcanManage(await buildProjectAccessInput(ctx, project, locals))\n\t);\n\tif (!allowed) {\n\t\tapiError(\n\t\t\t403,\n\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\taction === 'members'\n\t\t\t\t? 'Only project owners can manage members.'\n\t\t\t\t: 'Only project owners can manage this project.'\n\t\t);\n\t}\n\treturn user;\n}\n\n// Owner-only gate for project settings, centralized so PATCH\n// /api/projects/[id] matches the rest of the access layer.\nexport async function requireCanEditProjectSettings(\n\tlocals: ScopedLocals,\n\tprojectId: string\n): Promise<{ user: AuthUser; ctx: RequestContext; project: Project }> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst project = await loadProjectOr404(ctx, projectId, locals);\n\tconst allowed = await managementBypassForProject(ctx, project, locals, async () =>\n\t\tcanEditProjectSettings(await buildProjectAccessInput(ctx, project, locals))\n\t);\n\tif (!allowed)\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'Only project owners can edit project settings.');\n\treturn { user, ctx, project };\n}\n\nexport async function requireCanViewProject(\n\tlocals: ScopedLocals,\n\tprojectId: string\n): Promise<AuthUser> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst allowed = await contentCheck(async () => {\n\t\tconst project = await loadProjectOr404(ctx, projectId, locals);\n\t\treturn canView(await buildProjectAccessInput(ctx, project, locals));\n\t});\n\tif (!allowed) apiError(403, ApiErrorCode.FORBIDDEN, 'You do not have access to this project.');\n\treturn user;\n}\n\n/**\n * Solve gating. Today `canSolve === canView` for non-platform projects, but\n * the rule lives in its own function so future cost-gating (quotas, rate\n * limits) lands without touching view semantics. `viewer` project role\n * passes; platform projects narrow to grants with `canSolve=true`.\n */\nexport async function requireCanSolve(\n\tlocals: ScopedLocals,\n\tprojectId: string,\n\t// Callers that already loaded the project (e.g. the solve endpoint, which\n\t// reads orgId/pin off it) pass it to skip a redundant `getProject` here.\n\tpreloadedProject?: Project\n): Promise<{ user: AuthUser; ctx: RequestContext; project: Project }> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst project = preloadedProject ?? (await loadProjectOr404(ctx, projectId, locals));\n\tif (outsideTokenOrg(ctx, project.orgId))\n\t\tapiError(404, ApiErrorCode.NOT_FOUND, 'Project not found');\n\tconst allowed = await contentCheck(async () =>\n\t\tcanSolve(await buildProjectAccessInput(ctx, project, locals))\n\t);\n\tif (!allowed) apiError(403, ApiErrorCode.FORBIDDEN, 'You do not have access to this project.');\n\treturn { user, ctx, project };\n}\n\n/**\n * Org membership for the commons branch of `canEditDefinition`, or `null` when\n * that branch cannot fire. Skipping the round-trip on container projects keeps\n * the common edit path at the same two reads it had before commons gained the\n * membership test.\n */\nasync function loadCommonsOrgMember(\n\tctx: RequestContext,\n\tproject: Project | null,\n\tsrc: HasDeps\n): Promise<OrgMember | null> {\n\tif (!project?.autoJoinOnUpload) return null;\n\treturn await orgsOf(src).getOrgMember(ctx, project.orgId, ctx.userId);\n}\n\n/**\n * Loads the record and gates editing. Returns the record AND the project it\n * loads for the gate, so callers skip a re-fetch of either.\n */\nexport async function requireEditableDefinition(locals: ScopedLocals, guid: string) {\n\tconst { ctx } = requireAuthed(locals);\n\tconst record = await definitionMetaOf(locals).get(ctx, guid);\n\tif (!record) apiError(404, ApiErrorCode.NOT_FOUND, 'Definition not found');\n\t// Load project + member once up front; `project` is returned for reuse.\n\tconst [project, member] = await Promise.all([\n\t\tprojectsOf(locals).getProject(ctx, record.projectId),\n\t\tprojectsOf(locals).getProjectMember(ctx, record.projectId, ctx.userId)\n\t]);\n\tif (project && outsideTokenOrg(ctx, project.orgId)) {\n\t\tapiError(404, ApiErrorCode.NOT_FOUND, 'Definition not found');\n\t}\n\tconst allowed = await contentCheck(async () =>\n\t\tcanEditDefinition({\n\t\t\tproject,\n\t\t\tdefinition: record,\n\t\t\tmember,\n\t\t\torgMember: await loadCommonsOrgMember(ctx, project, locals),\n\t\t\tuserId: ctx.userId,\n\t\t\tplatformPermissions: ctx.platformPermissions,\n\t\t\tenablePlatformProjects: flagOf(locals)('ENABLE_PLATFORM_PROJECTS')\n\t\t})\n\t);\n\tif (!allowed)\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'You do not have permission to edit this definition.');\n\treturn { record, ctx, project };\n}\n\nexport async function requireCanEditDefinition(\n\tlocals: ScopedLocals,\n\tprojectId: string,\n\tdefinitionGuid: string,\n\t// Callers that already loaded the project and/or definition (e.g. the solve\n\t// endpoint) pass them to skip the redundant fetches inside the gate. The\n\t// member row still loads here (the caller doesn't have it).\n\tpreloaded?: { project?: Project | null; definition?: DefinitionRecord | null }\n): Promise<AuthUser> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst allowed = await contentCheck(async () => {\n\t\tconst [project, definition, member] = await Promise.all([\n\t\t\tpreloaded?.project !== undefined\n\t\t\t\t? Promise.resolve(preloaded.project)\n\t\t\t\t: projectsOf(locals).getProject(ctx, projectId),\n\t\t\tpreloaded?.definition !== undefined\n\t\t\t\t? Promise.resolve(preloaded.definition)\n\t\t\t\t: definitionMetaOf(locals).get(ctx, definitionGuid),\n\t\t\tprojectsOf(locals).getProjectMember(ctx, projectId, ctx.userId)\n\t\t]);\n\t\tif (project && outsideTokenOrg(ctx, project.orgId)) return false;\n\t\treturn canEditDefinition({\n\t\t\tproject,\n\t\t\tdefinition,\n\t\t\tmember,\n\t\t\torgMember: await loadCommonsOrgMember(ctx, project, locals),\n\t\t\tuserId: ctx.userId,\n\t\t\tplatformPermissions: ctx.platformPermissions,\n\t\t\tenablePlatformProjects: flagOf(locals)('ENABLE_PLATFORM_PROJECTS')\n\t\t});\n\t});\n\tif (!allowed)\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'You do not have permission to edit this definition.');\n\treturn user;\n}\n","/**\n * Bridges the flat `permissions` array the v1 invite body accepts to the\n * two-scope model adapters expect. One invite legitimately carries both scopes,\n * so this is a wire-format adapter, not a migration shim — retire it only when\n * the invite body grows separate `platformPermissions` + `orgPermissions`\n * fields.\n */\n\nimport type { OrgPermission, PlatformPermission } from '@selvajs/platform';\nimport { ALL_ORG_PERMISSIONS, ALL_PLATFORM_PERMISSIONS } from '@selvajs/platform';\n\nconst PLATFORM_SET: ReadonlySet<string> = new Set(ALL_PLATFORM_PERMISSIONS);\nconst ORG_SET: ReadonlySet<string> = new Set(ALL_ORG_PERMISSIONS);\n\nexport interface SplitPermissions {\n\tplatform: PlatformPermission[];\n\torg: OrgPermission[];\n}\n\n/** Split a flat array into platform + org scope buckets, dropping unknowns. */\nexport function splitFlatPermissions(flat: readonly string[]): SplitPermissions {\n\tconst platform: PlatformPermission[] = [];\n\tconst org: OrgPermission[] = [];\n\tfor (const p of flat) {\n\t\tif (PLATFORM_SET.has(p)) platform.push(p as PlatformPermission);\n\t\telse if (ORG_SET.has(p)) org.push(p as OrgPermission);\n\t}\n\treturn { platform, org };\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAAS,gBAAgB,qBAA6D;CACrF,OAAO,oBAAoB,SAAS,gBAAgB;AACrD;;;;;;;;AA0CA,SAAgB,QAAQ,OAAoC;CAC3D,MAAM,EACL,SACA,QACA,WACA,qBACA,wBACA,qBACA,gBACA,aACA,WACG;CACJ,IAAI,CAAC,SAAS,OAAO;CAErB,IAAI,QAAQ,eAAe,YAAY;EACtC,IAAI,CAAC,wBAAwB,OAAO;EACpC,IAAI,gBAAgB,mBAAmB,GAAG,OAAO;EACjD,OAAO,eAAe,MACpB,MACC,EAAE,gBAAgB,UAAU,EAAE,cAAc,UAC5C,EAAE,gBAAgB,SAAS,EAAE,cAAc,WAC9C;CACD;CAIA,IAAI,WAAW,MAAM,OAAO;CAC5B,IAAI,QAAQ,eAAe,OAAO,OAAO,cAAc,QAAQ,gBAAgB,QAAQ;CACvF,IAAI,QAAQ,eAAe,UAAU,OAAO,sBAAsB,OAAO,cAAc;CACvF,OAAO;AACR;;;;;;;;AASA,SAAgB,SAAS,OAAoC;CAC5D,MAAM,EACL,SACA,wBACA,qBACA,gBACA,aACA,WACG;CACJ,IAAI,CAAC,SAAS,OAAO;CAErB,IAAI,QAAQ,eAAe,YAA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GACZ,qBAAqB,IAAI;GACzB,wBAAwB,OAAO,MAAM,CAAC,CAAC,0BAA0B;EAClE,CAAC;CACF,CAAC,GAEA,SAAS,KAAK,aAAa,WAAW,qDAAqD;CAC5F,OAAO;AACR;;AC3pBA,IAAM,eAAoC,IAAI,IAAI,wBAAwB;AAC1E,IAAM,UAA+B,IAAI,IAAI,mBAAmB;;AAQhE,SAAgB,qBAAqB,MAA2C;CAC/E,MAAM,WAAiC,CAAC;CACxC,MAAM,MAAuB,CAAC;CAC9B,KAAK,MAAM,KAAK,MACf,IAAI,aAAa,IAAI,CAAC,GAAG,SAAS,KAAK,CAAuB;MACzD,IAAI,QAAQ,IAAI,CAAC,GAAG,IAAI,KAAK,CAAkB;CAErD,OAAO;EAAE;EAAU;CAAI;AACxB"}
|
|
1
|
+
{"version":3,"file":"access.js","names":[],"sources":["../../../../platform/src/config/manifest.ts","../../../../platform/src/utils/trim.ts","../../../../platform/src/computeServer/key32.ts","../../../../platform/src/config/raw-value.ts","../../../../platform/src/config/resolve.ts","../../../../platform/src/access/rules.ts","../../../../platform/src/apiTokens/scope.ts","../../../../platform/src/logging/interface.ts","../../../../platform/src/selva-config.ts","../../../../server/src/config/read-settings.ts","../../../../server/src/config/settings.ts","../../../../server/src/api/errors.ts","../../../../server/src/access/project-access-input.ts","../../../../server/src/access/guards.ts","../../../../server/src/access/permissions-scope.ts"],"sourcesContent":["/**\n * One declaration per environment variable: its type, default, what changing it\n * breaks, and whether a bad value stops boot. Each package declares the keys it\n * reads; a host composes the slices it ships with {@link composeManifest}.\n */\n\n/**\n * What happens to a value that fails its rule. `fail` for anything\n * security-relevant, so a typo can't switch a control off; `default` for\n * tunables, where a typo in a cache size shouldn't take the site down on the\n * next unrelated restart.\n */\nexport type OnInvalid = 'fail' | 'default';\n\n/**\n * `bootstrap`: needed before the data provider exists. `secret`: a key or\n * credential. `setting`: product behaviour an admin decides. `tunable`: a\n * limit almost nobody should touch.\n */\nexport type SettingClass = 'bootstrap' | 'secret' | 'setting' | 'tunable';\n\ninterface SettingBase<T> {\n\tkey: string;\n\tclass: SettingClass;\n\tonInvalid: OnInvalid;\n\t/** A few plain words naming the setting for someone who has never seen the key. */\n\tlabel?: string;\n\t/** One line, shown by `selva config show` and the admin page. */\n\tdescription: string;\n\t/** What changing it breaks or affects. Shown before `selva config set` writes. */\n\timpact?: string;\n\t/** Absent means the key is optional with no value. */\n\tdefault?: T;\n\trequired?: boolean;\n\t/** Never shown in clear: secrets and personal data. */\n\tsensitive?: boolean;\n\t/** 256-bit random key: safe to fingerprint, unlike a low-entropy secret. */\n\tgenerated?: boolean;\n\t/** Shown at the top of the admin Configuration section. */\n\tsummary?: boolean;\n\t/** Previous names. Read when the key is unset; `selva migrate` renames them. */\n\taliases?: readonly string[];\n\t/**\n\t * How the reader parsed this key before it parsed strictly. `selva migrate`\n\t * rewrites a value to what it meant then, so a stricter parser can't change\n\t * a deployment's behaviour behind its back. Data, not a function: the CLI\n\t * reads the manifest as JSON.\n\t */\n\tlegacy?: LegacyParse;\n}\n\n/**\n * `exact-true`: only the string `true` was on. `not-false`: anything but the\n * string `false` was on. `enumFallback`: an unrecognised value meant this one.\n */\nexport type LegacyParse = { bool: 'exact-true' | 'not-false' } | { enumFallback: string };\n\nexport interface StringSetting extends SettingBase<string> {\n\ttype: 'string';\n\tminLength?: number;\n}\n/** 32 bytes, as 64 hex characters or base64: what `decodeSecretKey` accepts. */\nexport interface KeySetting extends SettingBase<string> {\n\ttype: 'key';\n}\nexport interface UrlSetting extends SettingBase<string> {\n\ttype: 'url';\n\t/**\n\t * Scheme, host and port only. A path, query or credentials is refused: an\n\t * origin comparison, such as the CSRF check, drops or fails on them.\n\t */\n\torigin?: boolean;\n}\nexport interface IntSetting extends SettingBase<number> {\n\ttype: 'int';\n\tmin?: number;\n\tmax?: number;\n\t/** What 0 means, when it is a sentinel rather than a quantity: \"Off\", \"No limit\". */\n\tzero?: string;\n\t/** Lets a reader print 100000 as \"100 s\". */\n\tunit?: IntUnit;\n}\nexport type IntUnit = 'ms' | 'bytes' | 'mb' | 'days';\nexport interface BoolSetting extends SettingBase<boolean> {\n\ttype: 'bool';\n}\nexport interface EnumSetting extends SettingBase<string> {\n\ttype: 'enum';\n\tvalues: readonly string[];\n}\nexport interface ListSetting extends SettingBase<readonly string[]> {\n\ttype: 'list';\n}\n\nexport type SettingSpec =\n\tStringSetting | KeySetting | UrlSetting | IntSetting | BoolSetting | EnumSetting | ListSetting;\n\nexport type Manifest = readonly SettingSpec[];\n\nexport function defineSetting<S extends SettingSpec>(spec: S): S {\n\treturn spec;\n}\n\n/** Flattens slices and rejects a key declared twice: two readers, two defaults. */\nexport function composeManifest(parts: ReadonlyArray<SettingSpec | Manifest>): Manifest {\n\tconst out: SettingSpec[] = [];\n\tconst seen = new Set<string>();\n\tfor (const part of parts) {\n\t\tfor (const spec of Array.isArray(part) ? part : [part as SettingSpec]) {\n\t\t\tfor (const name of [spec.key, ...(spec.aliases ?? [])]) {\n\t\t\t\tif (seen.has(name)) throw new Error(`Config key ${name} is declared twice`);\n\t\t\t\tseen.add(name);\n\t\t\t}\n\t\t\tout.push(spec);\n\t\t}\n\t}\n\treturn out;\n}\n","// Not `s.replace(/x+$/, '')`: that regex backtracks quadratically on a long\n// run of `x` that isn't at the end, and these strings come from config.\nexport function trimTrailing(s: string, ch: string): string {\n\tlet end = s.length;\n\twhile (end > 0 && s[end - 1] === ch) end--;\n\treturn s.slice(0, end);\n}\n","import { trimTrailing } from '../utils/trim.js';\n\n/**\n * A 32-byte key written as 64 hex characters or base64 (padding optional), or\n * null. No `node:crypto` here: the config boot check imports this too.\n */\nexport function parseKey32(raw: string): Buffer | null {\n\tconst key = raw.trim();\n\tif (/^[0-9a-fA-F]{64}$/.test(key)) return Buffer.from(key, 'hex');\n\t// `Buffer.from` skips what it can't decode, so only a round trip proves the\n\t// whole string was base64 rather than 32 bytes of it.\n\tconst buf = Buffer.from(key, 'base64');\n\treturn buf.length === 32 && trimTrailing(buf.toString('base64'), '=') === trimTrailing(key, '=')\n\t\t? buf\n\t\t: null;\n}\n","import type { SettingSpec } from './manifest.js';\nimport type { EnvRecord } from './resolve.js';\n\n/**\n * The text a setting reads and the name it came from: its own key, else the\n * first alias that is set. Blank counts as unset, so a `KEY=` line with stray\n * spaces can't hide an alias or pass a required key as an empty string.\n */\nexport function rawValue(\n\tspec: SettingSpec,\n\tenv: EnvRecord\n): { name: string; raw: string } | undefined {\n\tfor (const name of [spec.key, ...(spec.aliases ?? [])]) {\n\t\tconst raw = env[name];\n\t\tif (raw !== undefined && raw.trim() !== '') return { name, raw };\n\t}\n\treturn undefined;\n}\n","import type { Manifest, SettingSpec } from './manifest.js';\nimport { trimTrailing } from '../utils/trim.js';\nimport { parseKey32 } from '../computeServer/key32.js';\nimport { rawValue } from './raw-value.js';\n\nexport type EnvRecord = Record<string, string | undefined>;\n\n/** `alias` means the value arrived under a previous name. */\nexport type ValueSource = 'env' | 'alias' | 'default' | 'unset';\n\n/** `invalid`: set, failed its rule, fell back. `error`: failed a fail-closed rule. */\nexport type KeyStatus = 'ok' | 'invalid' | 'error';\n\nexport interface KeyReport {\n\tkey: string;\n\tspec: SettingSpec;\n\tsource: ValueSource;\n\tstatus: KeyStatus;\n\tvalue: unknown;\n\t/** The previous name the value was read from, when `source` is `alias`. */\n\talias?: string;\n\t/** Why the value was rejected. Never echoes the value: it may be a secret. */\n\tproblem?: string;\n}\n\nexport interface UnknownKey {\n\tkey: string;\n\t/** Nearest declared name, when one is close enough to be a typo. */\n\tsuggestion?: string;\n}\n\nexport interface ResolvedConfig {\n\tvalues: Record<string, unknown>;\n\tkeys: Record<string, KeyReport>;\n\t/** Keys that failed a fail-closed rule. A host refuses to boot on any. */\n\terrors: KeyReport[];\n\tunknown: UnknownKey[];\n}\n\nexport interface ResolveOptions {\n\t/** Env keys under these prefixes that no setting declares are reported as unknown. */\n\tprefixes?: readonly string[];\n\t/** Keys a host knows about but doesn't resolve here (another tool reads them). */\n\texternal?: readonly string[];\n}\n\nconst TRUE = new Set(['true', '1', 'yes', 'on']);\nconst FALSE = new Set(['false', '0', 'no', 'off']);\n\ntype Parsed = { ok: true; value: unknown } | { ok: false; problem: string };\n\nfunction parse(spec: SettingSpec, raw: string): Parsed {\n\tconst v = raw.trim();\n\tswitch (spec.type) {\n\t\tcase 'string':\n\t\t\tif (spec.minLength !== undefined && v.length < spec.minLength) {\n\t\t\t\treturn { ok: false, problem: `must be at least ${spec.minLength} characters` };\n\t\t\t}\n\t\t\treturn { ok: true, value: v };\n\t\tcase 'key':\n\t\t\treturn parseKey32(v)\n\t\t\t\t? { ok: true, value: v }\n\t\t\t\t: { ok: false, problem: 'must be 32 bytes as 64 hex characters or base64' };\n\t\tcase 'url': {\n\t\t\tconst value = trimTrailing(v, '/');\n\t\t\tlet url: URL;\n\t\t\ttry {\n\t\t\t\turl = new URL(value);\n\t\t\t} catch {\n\t\t\t\treturn { ok: false, problem: 'must be an absolute URL' };\n\t\t\t}\n\t\t\tif (url.protocol !== 'http:' && url.protocol !== 'https:') {\n\t\t\t\treturn { ok: false, problem: 'must start with http:// or https://' };\n\t\t\t}\n\t\t\tif (spec.origin && (url.username || url.password || url.pathname !== '/' || /[?#]/.test(v))) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tproblem:\n\t\t\t\t\t\t'must be an origin such as https://selva.example.com: no path, query or credentials'\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, value };\n\t\t}\n\t\tcase 'int': {\n\t\t\t// Not `Number(v)` alone: it reads `0x10`, `1e3` and blank as numbers.\n\t\t\tif (!/^[+-]?\\d+$/.test(v)) return { ok: false, problem: 'must be a whole number' };\n\t\t\tconst n = Number(v);\n\t\t\tif (!Number.isSafeInteger(n)) return { ok: false, problem: 'is too large' };\n\t\t\tif (spec.min !== undefined && n < spec.min)\n\t\t\t\treturn { ok: false, problem: `must be ≥ ${spec.min}` };\n\t\t\tif (spec.max !== undefined && n > spec.max)\n\t\t\t\treturn { ok: false, problem: `must be ≤ ${spec.max}` };\n\t\t\t// `-0` is a different value to `Object.is` and to `1 / n`.\n\t\t\treturn { ok: true, value: n === 0 ? 0 : n };\n\t\t}\n\t\tcase 'bool': {\n\t\t\tconst lower = v.toLowerCase();\n\t\t\tif (TRUE.has(lower)) return { ok: true, value: true };\n\t\t\tif (FALSE.has(lower)) return { ok: true, value: false };\n\t\t\treturn { ok: false, problem: 'must be true or false' };\n\t\t}\n\t\tcase 'enum': {\n\t\t\tconst lower = v.toLowerCase();\n\t\t\tconst match = spec.values.find((m) => m.toLowerCase() === lower);\n\t\t\treturn match !== undefined\n\t\t\t\t? { ok: true, value: match }\n\t\t\t\t: { ok: false, problem: `must be one of ${spec.values.join(' | ')}` };\n\t\t}\n\t\tcase 'list':\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tvalue: v\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((s) => s.trim())\n\t\t\t\t\t.filter(Boolean)\n\t\t\t};\n\t}\n}\n\n/** What `raw` meant to the reader before it parsed strictly. */\nexport function legacyValue(spec: SettingSpec, raw: string): unknown {\n\tconst legacy = spec.legacy;\n\tif (legacy && 'bool' in legacy) {\n\t\treturn legacy.bool === 'exact-true' ? raw === 'true' : raw !== 'false';\n\t}\n\tif (legacy && 'enumFallback' in legacy && spec.type === 'enum') {\n\t\treturn spec.values.includes(raw) ? raw : legacy.enumFallback;\n\t}\n\tconst parsed = parse(spec, raw);\n\treturn parsed.ok ? parsed.value : undefined;\n}\n\nfunction resolveKey(spec: SettingSpec, env: EnvRecord): KeyReport {\n\tconst found = rawValue(spec, env);\n\tif (!found) {\n\t\tconst source: ValueSource = spec.default !== undefined ? 'default' : 'unset';\n\t\tconst base = { key: spec.key, spec, source };\n\t\tif (spec.required) {\n\t\t\treturn { ...base, status: 'error', value: undefined, problem: 'is required' };\n\t\t}\n\t\treturn { ...base, status: 'ok', value: spec.default };\n\t}\n\n\tconst alias = found.name === spec.key ? undefined : found.name;\n\tconst source: ValueSource = alias ? 'alias' : 'env';\n\tconst base = { key: spec.key, spec, source, ...(alias ? { alias } : {}) };\n\tconst parsed = parse(spec, found.raw);\n\tif (parsed.ok) return { ...base, status: 'ok', value: parsed.value };\n\tif (spec.onInvalid === 'fail') {\n\t\treturn { ...base, status: 'error', value: undefined, problem: parsed.problem };\n\t}\n\treturn { ...base, status: 'invalid', value: spec.default, problem: parsed.problem };\n}\n\n/** One setting's value by the manifest's rules: its default when unset or invalid. */\nexport function readSetting(spec: SettingSpec, env: EnvRecord): unknown {\n\treturn resolveKey(spec, env).value;\n}\n\n/** Resolve every declared key from an env map. Pure: reads nothing ambient. */\nexport function resolveConfig(\n\tmanifest: Manifest,\n\tenv: EnvRecord,\n\toptions: ResolveOptions = {}\n): ResolvedConfig {\n\tconst values: Record<string, unknown> = {};\n\tconst keys: Record<string, KeyReport> = {};\n\tconst errors: KeyReport[] = [];\n\tconst known = new Set<string>(options.external ?? []);\n\n\tfor (const spec of manifest) {\n\t\tknown.add(spec.key);\n\t\tfor (const a of spec.aliases ?? []) known.add(a);\n\t\tconst report = resolveKey(spec, env);\n\t\tkeys[spec.key] = report;\n\t\tvalues[spec.key] = report.value;\n\t\tif (report.status === 'error') errors.push(report);\n\t}\n\n\tconst declared = manifest.map((s) => s.key);\n\tconst prefixes = options.prefixes ?? [];\n\tconst unknown: UnknownKey[] = [];\n\tfor (const key of Object.keys(env)) {\n\t\tif (known.has(key) || !prefixes.some((p) => key.startsWith(p))) continue;\n\t\tconst suggestion = nearest(key, declared);\n\t\tunknown.push(suggestion ? { key, suggestion } : { key });\n\t}\n\n\treturn { values, keys, errors, unknown };\n}\n\n/** A declared name within a typo's reach: a prefix of it, or a few edits away. */\nfunction nearest(key: string, declared: readonly string[]): string | undefined {\n\tlet best: string | undefined;\n\tlet bestDistance = Infinity;\n\tfor (const candidate of declared) {\n\t\tconst d =\n\t\t\tcandidate.startsWith(key) || key.startsWith(candidate) ? 0 : editDistance(key, candidate);\n\t\tif (d < bestDistance) {\n\t\t\tbest = candidate;\n\t\t\tbestDistance = d;\n\t\t}\n\t}\n\treturn bestDistance <= 3 ? best : undefined;\n}\n\nfunction editDistance(a: string, b: string): number {\n\tlet prev = Array.from({ length: b.length + 1 }, (_, i) => i);\n\tfor (let i = 1; i <= a.length; i++) {\n\t\tconst row = [i];\n\t\tfor (let j = 1; j <= b.length; j++) {\n\t\t\trow[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));\n\t\t}\n\t\tprev = row;\n\t}\n\treturn prev[b.length];\n}\n","import type { PlatformPermission } from '../permissions/types.js';\nimport type { OrgPermission, OrgRole } from '../organizations/schemas.js';\nimport type { Project, ProjectMember } from '../projects/types.js';\nimport type { OrgMember } from '../organizations/types.js';\nimport type { DefinitionRecord } from '../definitions/types.js';\nimport type { PlatformProjectGrant } from '../platformProjects/types.js';\n\n/**\n * Pure access rules: already-loaded rows in, boolean out. Callers load the rows and the rules\n * hold the logic, so UI gating and server guards agree.\n *\n * Each rule decides `instance_admin` itself. An admin sees no private project without a\n * member row, and no rule opens a `platform` project while `enablePlatformProjects` is off.\n */\n\nfunction isInstanceAdmin(platformPermissions: readonly PlatformPermission[]): boolean {\n\treturn platformPermissions.includes('instance_admin');\n}\n\n/**\n * @deprecated Unsafe on a content rule: wrapping `canView` opens `platform` projects with the\n * feature off, and private projects to an admin with no member row. Call the rule alone.\n */\nexport function withAdminBypass(\n\tplatformPermissions: readonly PlatformPermission[],\n\trule: () => boolean\n): boolean {\n\tif (isInstanceAdmin(platformPermissions)) return true;\n\treturn rule();\n}\n\nexport interface ProjectAccessInput {\n\t/** @deprecated No rule reads it. */\n\torgPermissions?: readonly OrgPermission[];\n\tplatformPermissions: readonly PlatformPermission[];\n\tproject: Project | null;\n\tmember: ProjectMember | null;\n\torgMember: OrgMember | null;\n\t/**\n\t * `ALLOW_CROSS_ORG_PUBLIC` flag. When false, `public` visibility means\n\t * \"everyone in the parent org\" rather than \"everyone on the instance\".\n\t */\n\tallowCrossOrgPublic: boolean;\n\t/**\n\t * `ENABLE_PLATFORM_PROJECTS` flag. When false, every rule treats a\n\t * `platform`-visibility project as inaccessible — even for instance\n\t * admins — so the feature can be hidden silently without deleting data.\n\t */\n\tenablePlatformProjects: boolean;\n\t/** Grants for `platform`-visibility projects; empty for non-platform ones. */\n\tplatformGrants: readonly PlatformProjectGrant[];\n\t/** `ctx.actingOrgId` — matches org grants on platform projects. */\n\tactingOrgId: string | null;\n\t/** `ctx.userId` — matches user grants on platform projects. */\n\tuserId: string;\n}\n\nfunction grantMatches(\n\tgrant: PlatformProjectGrant,\n\twho: { userId?: string; actingOrgId?: string | null }\n): boolean {\n\treturn (\n\t\t(grant.granteeType === 'user' && grant.granteeId === who.userId) ||\n\t\t(grant.granteeType === 'org' && grant.granteeId === who.actingOrgId)\n\t);\n}\n\n/**\n * The verdict on a `platform`-visibility project, or `undefined` for any other, which the\n * calling rule decides. The flag is read before `instance_admin`, so switching the feature\n * off hides these projects from admins too. Without `grantAllows`, no grant is enough.\n */\nfunction platformGate(\n\tinput: Pick<ProjectAccessInput, 'project' | 'enablePlatformProjects' | 'platformPermissions'> &\n\t\tPartial<Pick<ProjectAccessInput, 'platformGrants' | 'actingOrgId' | 'userId'>>,\n\tgrantAllows?: (grant: PlatformProjectGrant) => boolean\n): boolean | undefined {\n\tif (input.project?.visibility !== 'platform') return undefined;\n\tif (!input.enablePlatformProjects) return false;\n\tif (isInstanceAdmin(input.platformPermissions)) return true;\n\tif (!grantAllows) return false;\n\treturn (input.platformGrants ?? []).some((g) => grantAllows(g) && grantMatches(g, input));\n}\n\n/**\n * Authenticated-user view rule. Anonymous access goes through share-link\n * tokens instead — the route resolves a valid token before this runs.\n *\n * Platform projects: `instance_admin` always passes; otherwise any grant\n * (view-only or canSolve) satisfies view access.\n */\nexport function canView(input: ProjectAccessInput): boolean {\n\tconst { project, member, orgMember, allowCrossOrgPublic, actingOrgId } = input;\n\tif (!project) return false;\n\n\tconst platform = platformGate(input, () => true);\n\tif (platform !== undefined) return platform;\n\n\t// A project member sees the project at any visibility. Leaving the org ends the\n\t// membership, so this only widens access for someone who reclaimed from outside.\n\tif (member !== null) return true;\n\tif (project.visibility === 'org') return orgMember !== null && actingOrgId === project.orgId;\n\tif (project.visibility === 'public') return allowCrossOrgPublic ? true : orgMember !== null;\n\treturn false;\n}\n\n/**\n * Non-platform projects: same as `canView` — kept as a separate function so\n * cost gating can diverge from view access later.\n *\n * Platform projects: `instance_admin` always passes; a view-only grant\n * satisfies `canView` but not `canSolve` — the grant needs `canSolve: true`.\n */\nexport function canSolve(input: ProjectAccessInput): boolean {\n\treturn platformGate(input, (g) => g.canSolve) ?? canView(input);\n}\n\n/**\n * Platform projects: `instance_admin` only (they have no member rows).\n * All other visibilities: project owner/editor.\n */\nexport function canEdit(input: ProjectAccessInput): boolean {\n\tconst { member, project } = input;\n\tif (!project) return false;\n\treturn platformGate(input) ?? (member?.role === 'owner' || member?.role === 'editor');\n}\n\n/**\n * Adding a new definition. Commons projects (`autoJoinOnUpload`) take uploads\n * from anyone who can {@link canView} them, and the uploader owns what they\n * upload; everywhere else it needs {@link canEdit}.\n */\nexport function canCreateDefinition(input: ProjectAccessInput): boolean {\n\treturn (input.project?.autoJoinOnUpload === true && canView(input)) || canEdit(input);\n}\n\n/** Platform projects: `instance_admin` only. All other visibilities: project owner. */\nexport function canManage(input: ProjectAccessInput): boolean {\n\tif (!input.project) return false;\n\treturn platformGate(input) ?? input.member?.role === 'owner';\n}\n\n/** Platform projects: `instance_admin` only. All other visibilities: project owner. */\nexport function canEditProjectSettings(input: ProjectAccessInput): boolean {\n\treturn canManage(input);\n}\n\nexport interface VisibilityChangeInput {\n\torgMember: OrgMember | null;\n}\n\n/**\n * Authorization to flip a project to `public`. The `ALLOW_CROSS_ORG_PUBLIC`\n * flag only changes what `public` means post-flip; the flip itself is gated\n * by org owner/admin role.\n */\nexport function canChangeVisibilityToPublic(input: VisibilityChangeInput): boolean {\n\tconst role = input.orgMember?.role;\n\treturn role === 'owner' || role === 'admin';\n}\n\nexport interface DefinitionAccessInput {\n\tproject: Project | null;\n\tdefinition: DefinitionRecord | null;\n\tmember: ProjectMember | null;\n\t/**\n\t * The actor's membership in the project's parent org, used only by the\n\t * commons branch below. `null` means \"not a member of this org\" — which on a\n\t * commons project is what separates a current contributor from a departed\n\t * one.\n\t */\n\torgMember: OrgMember | null;\n\tuserId: string;\n\tplatformPermissions: readonly PlatformPermission[];\n\t/**\n\t * `ENABLE_PLATFORM_PROJECTS` flag. When false, definitions in\n\t * platform-visibility projects are not editable by anyone, matching the\n\t * other project rules.\n\t */\n\tenablePlatformProjects: boolean;\n}\n\n/**\n * For platform projects: `instance_admin` only.\n * For all other projects: project editor/owner can always edit (moderation).\n * On commons projects (`autoJoinOnUpload=true`) the definition owner can edit\n * their own, as long as they still belong to the project's org.\n */\nexport function canEditDefinition(input: DefinitionAccessInput): boolean {\n\tconst { project, definition, member, orgMember, userId } = input;\n\tif (!project || !definition) return false;\n\tif (definition.projectId !== project.id) return false;\n\n\tconst platform = platformGate(input);\n\tif (platform !== undefined) return platform;\n\n\tif (member?.role === 'owner' || member?.role === 'editor') return true;\n\n\t// Commons grants edit on top of belonging, not instead of it. `ownerId` is\n\t// stamped at upload and never revisited, so without the org-membership test\n\t// a departed uploader keeps edit/delete/share-link authority on everything\n\t// they ever uploaded — and flipping `autoJoinOnUpload` on hands it back to\n\t// them retroactively, with no action taken against them.\n\tif (project.autoJoinOnUpload && userId === definition.ownerId && orgMember) return true;\n\n\treturn false;\n}\n\nexport interface ReclaimAccessInput {\n\tproject: Project | null;\n\torgMember: OrgMember | null;\n\t/** `ctx.actingOrgId` — must match `project.orgId`. */\n\tactingOrgId: string | null;\n}\n\n/**\n * Org leadership escape hatch: adds the actor as co-owner without demoting\n * the existing owner. Tenancy must match.\n *\n * Platform projects can't be reclaimed — `instance_admin` already has\n * management access to them.\n */\nexport function canReclaim(input: ReclaimAccessInput): boolean {\n\tconst { project, orgMember, actingOrgId } = input;\n\tif (!project || !actingOrgId) return false;\n\tif (project.visibility === 'platform') return false;\n\tif (actingOrgId !== project.orgId) return false;\n\tconst role = orgMember?.role;\n\treturn role === 'owner' || role === 'admin';\n}\n\nexport interface CreateProjectAccessInput {\n\torgPermissions: readonly OrgPermission[];\n\torgMember: OrgMember | null;\n\tactingOrgId: string | null;\n\ttargetOrgId: string;\n}\n\n/**\n * Owner/admin can always create; a `member` needs `manage_projects` org\n * permission. Tenancy is enforced.\n *\n * Platform projects (`visibility: 'platform'`) go through the admin API,\n * gated on `instance_admin` — this rule isn't consulted for them.\n */\nexport function canCreateProject(input: CreateProjectAccessInput): boolean {\n\tconst { orgMember, orgPermissions, actingOrgId, targetOrgId } = input;\n\tif (actingOrgId !== targetOrgId) return false;\n\tconst role = orgMember?.role;\n\tif (role === 'owner' || role === 'admin') return true;\n\tif (role === 'member' && orgPermissions.includes('manage_projects')) return true;\n\treturn false;\n}\n\nexport interface OrgOwnerAuthorityInput {\n\t/** The acting user's own membership row, not the org's `ownerId` column. */\n\tactorMember: OrgMember | null;\n\t/** The role being granted, or the role the target already holds. */\n\trole: OrgRole;\n}\n\n/**\n * Whether the actor may hand out or take away org `owner`/`admin` standing.\n * Inviting someone as owner/admin, changing a member's role and removing an owner\n * are one rule, so all three read it here.\n *\n * Reads the actor's **membership row**. `Organization.ownerId` is a separate field\n * that can disagree with it and is not authority for this decision.\n */\nexport function canChangeOrgRole(input: OrgOwnerAuthorityInput): boolean {\n\tif (input.role === 'member') return true;\n\treturn input.actorMember?.role === 'owner';\n}\n\n/**\n * Pre-flight check for project-owner removal, run after `canManage`.\n *\n * - `ok` — proceed\n * - `sole_owner` — last owner; route surfaces 409 and suggests reclaim\n * - `needs_confirm` — owner-on-owner removal without `?confirm=true`\n */\nexport type OwnerRemovalCheck = 'ok' | 'sole_owner' | 'needs_confirm';\n\nexport interface OwnerRemovalInput {\n\ttarget: { role: 'owner' | 'editor' | 'viewer' };\n\tallMembers: readonly { role: 'owner' | 'editor' | 'viewer' }[];\n\tconfirmed: boolean;\n}\n\nexport function checkOwnerRemoval(input: OwnerRemovalInput): OwnerRemovalCheck {\n\tif (input.target.role !== 'owner') return 'ok';\n\tconst ownerCount = input.allMembers.filter((m) => m.role === 'owner').length;\n\tif (ownerCount <= 1) return 'sole_owner';\n\tif (!input.confirmed) return 'needs_confirm';\n\treturn 'ok';\n}\n","import type { RequestContext } from '../context.js';\nimport { ProviderError } from '../errors/index.js';\nimport { parseApiScope, type ApiScope, type ApiScopeAction, type ApiToken } from './types.js';\n\n/** The rows a request touches, when the route knows them. */\nexport interface ScopeTarget {\n\tprojectId?: string;\n\tdefinitionId?: string;\n}\n\n/**\n * May this request perform `action` on `target`?\n *\n * Without a target this is an org-level check, which only `all` and org scopes\n * pass: a project key must never reach a route that can't say which project it\n * touches. Requests without an API token always pass; their permissions are\n * checked elsewhere.\n */\nexport function scopeAllows(\n\tctx: RequestContext,\n\taction: ApiScopeAction,\n\ttarget?: ScopeTarget\n): boolean {\n\tconst api = ctx.apiScope;\n\tif (!api) return true;\n\treturn api.scopes.some(\n\t\t(s) => apiScopeActionCovers(s.action, action) && resourceCovers(s, ctx, target)\n\t);\n}\n\n/** Does a scope granting `granted` allow `wanted`? */\nexport function apiScopeActionCovers(granted: ApiScopeAction, wanted: ApiScopeAction): boolean {\n\tif (granted === wanted || wanted === 'read') return true;\n\treturn granted === 'write' && (wanted === 'upload' || wanted === 'create_projects');\n}\n\nfunction resourceCovers(scope: ApiScope, ctx: RequestContext, target?: ScopeTarget): boolean {\n\tconst { resource } = scope;\n\tswitch (resource.kind) {\n\t\tcase 'all':\n\t\t\treturn true;\n\t\tcase 'org':\n\t\t\treturn resource.id === ctx.actingOrgId;\n\t\tcase 'project':\n\t\t\treturn target?.projectId === resource.id;\n\t\tcase 'definition':\n\t\t\treturn target?.definitionId === resource.id;\n\t}\n}\n\n/**\n * Narrow the owner's live context to what the token grants. Only removes\n * rights:\n *\n * - Platform permissions are dropped. Instance authority never rides on a\n * bearer key, so an operator's leaked key can't reach other tenants.\n * - `apiScope` is attached, which `scopeAllows` reads.\n *\n * Scopes this version can't parse are dropped, so they grant nothing.\n */\nexport function narrowApiTokenContext(\n\tctx: RequestContext,\n\ttoken: Pick<ApiToken, 'id' | 'orgId' | 'scopes' | 'expiresAt'>\n): RequestContext {\n\tif (ctx.actingOrgId !== token.orgId) {\n\t\tthrow new ProviderError('API token context must act in the token’s org', 500);\n\t}\n\tconst scopes = token.scopes.map(parseApiScope).filter((s): s is ApiScope => s !== null);\n\treturn {\n\t\t...ctx,\n\t\tplatformPermissions: [],\n\t\tapiScope: { tokenId: token.id, scopes, expiresAt: token.expiresAt }\n\t};\n}\n\n/**\n * True when an API-token request reaches for something owned by an org other\n * than the token's. A token is bound to one org, so that resource doesn't\n * exist for it, even when the owner belongs to the other org too. Treat it as\n * not found. Session requests are never outside.\n */\nexport function outsideTokenOrg(ctx: RequestContext, orgId: string): boolean {\n\treturn ctx.apiScope !== undefined && orgId !== ctx.actingOrgId;\n}\n","/**\n * Structured logging seam with a silent default. The host supplies the backend, so this\n * package takes no logging dependency and a browser bundle never pulls in a Node logger.\n * Call sites describe WHAT happened and hand over fields; formatting, redaction and\n * routing are the backend's business.\n */\n\n/**\n * Fields attached to one log record. Values are `unknown`, not `string`, so a\n * field survives as typed JSON (numbers stay numbers, queryable by range)\n * instead of being flattened into a message string.\n *\n * Never put secrets here — session tokens, API keys, refresh tokens, raw share\n * tokens. Log records leave the box (stdout to collector to third-party index)\n * and outlive the credential.\n */\nexport type LogFields = Record<string, unknown>;\n\n/**\n * Severity levels, ordered to match pino's set so the backend is a thin\n * pass-through and operators get the level names they expect.\n *\n * - `debug` — detail only useful when actively diagnosing; off in production.\n * - `info` — a thing happened that an operator would want in the record\n * (boot, config resolved, request completed).\n * - `warn` — degraded or suspicious, but handled; the system continues.\n * - `error` — an operation failed. Pair with `IErrorReporter` when it's\n * genuinely unexpected: logs are for the operator reading stdout,\n * the reporter is for off-box triage.\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * A structured logger.\n *\n * MUST NOT throw — logging sits on every path including the error path, where a\n * failing logger would mask the original fault. Implementations swallow their\n * own failures.\n */\nexport interface ILogger {\n\tdebug(message: string, fields?: LogFields): void;\n\tinfo(message: string, fields?: LogFields): void;\n\twarn(message: string, fields?: LogFields): void;\n\terror(message: string, fields?: LogFields): void;\n\t/**\n\t * Derive a logger that stamps `fields` onto every record it writes. The\n\t * request hook binds `requestId` (plus method/route) once via `child`, so\n\t * every downstream call site logs without knowing a request id exists.\n\t *\n\t * Children compose; a child of a child carries both parents' fields. A\n\t * child's field overwrites a parent's on key collision.\n\t */\n\tchild(fields: LogFields): ILogger;\n}\n\n/**\n * Default `ILogger` — discards everything. Lets library code log\n * unconditionally without a configured backend, and keeps test output clean.\n * The app wires a real logger at its composition root; a consumer that wires\n * nothing gets silence rather than unsolicited stdout writes.\n */\nexport class NoopLogger implements ILogger {\n\tdebug(_message: string, _fields?: LogFields): void {}\n\tinfo(_message: string, _fields?: LogFields): void {}\n\twarn(_message: string, _fields?: LogFields): void {}\n\terror(_message: string, _fields?: LogFields): void {}\n\tchild(_fields: LogFields): ILogger {\n\t\treturn this;\n\t}\n}\n","import type { IAuthProvider } from './auth/interface.js';\nimport type { IDataProvider } from './data/interface.js';\nimport type { IStorageProvider } from './storage/interface.js';\nimport type { IEventSink } from './events/interface.js';\nimport type { ISolveMetricSink } from './metrics/interface.js';\nimport type { IBindingResolver } from './bindings/interface.js';\n\n/**\n * `single`: one org per deployment, created at setup; `ctx.actingOrgId` resolves to it for\n * every user. `multi`: orgs are first-class, created by users; `ctx.actingOrgId` resolves\n * per-request.\n */\nexport type TenancyMode = 'single' | 'multi';\n\n/** White-label branding. Omitted fields fall back to \"Selva\" defaults in the selva app. */\nexport interface SelvaBranding {\n\tname?: string;\n\tcopyrightName?: string;\n\ttagline?: string;\n\tdescription?: string;\n}\n\n/** Opt-in platform features. All default false when absent. */\nexport interface SelvaFlags {\n\t/** Projects with `visibility='public'` visible across orgs on the instance. */\n\tALLOW_CROSS_ORG_PUBLIC?: boolean;\n\t/** Orgs may override the instance compute pool with their own server. */\n\tALLOW_ORG_COMPUTE_OVERRIDE?: boolean;\n\t/** Authenticated users may create new orgs. */\n\tALLOW_ORG_CREATION?: boolean;\n\t/**\n\t * Anonymous external access via tokenized URLs. When off, share-link admin\n\t * routes reject mint/list/revoke and existing tokens stop resolving.\n\t */\n\tENABLE_SHARING?: boolean;\n\t/**\n\t * Projects owned by instance admins, granted to orgs or users without normal\n\t * membership. When off, `/admin/projects` 404s and platform-visibility\n\t * projects are hidden and inaccessible; data survives the toggle either way.\n\t */\n\tENABLE_PLATFORM_PROJECTS?: boolean;\n}\n\nexport interface SelvaConfig {\n\ttenancy?: TenancyMode;\n\tflags?: SelvaFlags;\n\tbranding?: SelvaBranding;\n\tauth: IAuthProvider;\n\t/** Orgs, projects, members, definitions, compute config, user profiles, platform permissions. */\n\tdata: IDataProvider;\n\t/** Blob storage — .gh/.ghx files, archived versions, images. */\n\tstorage: IStorageProvider;\n\t/** Defaults to `NoopEventSink`. */\n\tevents?: IEventSink;\n\t/** Records per-solve wall time. Defaults to `NoopSolveMetricSink`, which discards every metric. */\n\tsolveMetrics?: ISolveMetricSink;\n\t/** Nothing reads this: see `IBindingResolver`. */\n\tbindingResolver?: IBindingResolver;\n}\n\nexport type SelvaConfigFactory = (env: Record<string, string | undefined>) => SelvaConfig;\n\nexport function isFlagEnabled(config: SelvaConfig, flag: keyof SelvaFlags): boolean {\n\treturn Boolean(config.flags?.[flag]);\n}\n\n/** Identity function for type inference and IDE autocomplete. */\nexport function defineConfig<T extends SelvaConfig | SelvaConfigFactory>(config: T): T {\n\treturn config;\n}\n","import type { ILogger } from '@selvajs/platform';\nimport { resolveConfig, type EnvRecord, type Manifest } from '@selvajs/platform/config';\n\n/**\n * A manifest slice's values by its own rules, so a reader runs on what the config report shows.\n * Warns on a value read from an old name, and on one that failed its rule and fell back.\n */\nexport function readSettings(\n\tmanifest: Manifest,\n\tenv: EnvRecord,\n\tlogger: ILogger\n): Record<string, unknown> {\n\tconst { values, keys } = resolveConfig(manifest, env);\n\tfor (const key of Object.values(keys)) {\n\t\tif (key.source === 'alias') {\n\t\t\tlogger.warn('Deprecated env var: rename it', {\n\t\t\t\tcomponent: 'selva',\n\t\t\t\tenvVar: key.alias,\n\t\t\t\trenamedTo: key.key\n\t\t\t});\n\t\t}\n\t\tif (key.status !== 'ok') {\n\t\t\tlogger.warn('Invalid env value, falling back to default', {\n\t\t\t\tcomponent: 'selva',\n\t\t\t\tenvVar: key.key,\n\t\t\t\tproblem: key.problem,\n\t\t\t\tfallback: key.value\n\t\t\t});\n\t\t}\n\t}\n\treturn values;\n}\n","import { composeManifest, defineSetting, type IntSetting } from '@selvajs/platform/config';\n\n// Keys the engine reads, wherever the host app runs it. Providers declare their\n// own (`@selvajs/*-provider/config`); the host app declares what only it reads.\n\nconst flag = (key: string, label: string, description: string, impact?: string) =>\n\tdefineSetting({\n\t\tkey: `SELVA_FLAG_${key}`,\n\t\tlabel,\n\t\ttype: 'bool',\n\t\tdefault: false,\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription,\n\t\t...(impact ? { impact } : {})\n\t});\n\nconst tunableInt = (\n\tkey: string,\n\tfallback: number,\n\tlabel: string,\n\tdescription: string,\n\textra: Partial<Pick<IntSetting, 'min' | 'aliases' | 'impact' | 'zero' | 'unit'>> = {}\n) =>\n\tdefineSetting({\n\t\tkey,\n\t\tlabel,\n\t\ttype: 'int',\n\t\tmin: 1,\n\t\tdefault: fallback,\n\t\tonInvalid: 'default',\n\t\tclass: 'tunable',\n\t\tdescription,\n\t\t...extra\n\t});\n\nconst MB = 1024 * 1024;\n\nexport const SIGN_IN_MAX_AGE_SETTING = defineSetting({\n\tkey: 'SIGN_IN_MAX_AGE_DAYS',\n\tlabel: 'Force sign-in again after',\n\ttype: 'int',\n\tmin: 0,\n\tdefault: 0,\n\tonInvalid: 'fail',\n\tclass: 'setting',\n\tsummary: true,\n\tzero: 'Never',\n\tunit: 'days',\n\tdescription: 'Days before users must sign in at the identity provider again. 0 is never.',\n\timpact: 'API tokens of anyone who has not signed in within this many days are revoked.'\n});\n\nexport const COMPUTE_LIMIT_SETTINGS = composeManifest([\n\ttunableInt(\n\t\t'COMPUTE_RATE_LIMIT_MAX',\n\t\t120,\n\t\t'Solves per window',\n\t\t'Solves per user or share link per 100-second window.'\n\t),\n\ttunableInt('MAX_DEFINITION_FILE_SIZE_BYTES', 50 * MB, 'Max .gh upload', 'Largest .gh upload.', {\n\t\tunit: 'bytes'\n\t}),\n\t// Off by default: nothing is refused until an operator who has measured their pool opts in.\n\ttunableInt(\n\t\t'COMPUTE_MAX_QUEUE_DEPTH',\n\t\t0,\n\t\t'Solve queue length',\n\t\t'Solves allowed to wait per compute server. 0 is unbounded.',\n\t\t{ min: 0, zero: 'No limit' }\n\t),\n\ttunableInt(\n\t\t'COMPUTE_QUEUE_WAIT_MS',\n\t\t0,\n\t\t'Max queue wait',\n\t\t'Longest a solve may wait queued. 0 is no deadline.',\n\t\t{ min: 0, unit: 'ms', zero: 'No limit' }\n\t),\n\t// 256 MB keeps a handful of typical definitions warm without pinning gigabytes.\n\ttunableInt(\n\t\t'COMPUTE_DEFINITION_CACHE_MB',\n\t\t256,\n\t\t'Definition cache size',\n\t\t'Definition cache budget. 0 turns it off.',\n\t\t{ min: 0, unit: 'mb', zero: 'Off', aliases: ['COMPUTE_DEFINITION_BYTE_CACHE_MB'] }\n\t),\n\t// Per warm client: see `ComputeLimits.computeSolveCacheBytes` for the worst case.\n\ttunableInt(\n\t\t'COMPUTE_SOLVE_CACHE_MB',\n\t\t256,\n\t\t'Solve cache size',\n\t\t'Solve cache budget per warm compute server. 0 turns it off.',\n\t\t{ min: 0, unit: 'mb', zero: 'Off', aliases: ['COMPUTE_RESPONSE_CACHE_MB'] }\n\t),\n\tdefineSetting({\n\t\tkey: 'COMPUTE_SERVER_CACHESOLVE',\n\t\tlabel: 'Compute server solve cache',\n\t\ttype: 'bool',\n\t\tdefault: true,\n\t\tonInvalid: 'default',\n\t\tclass: 'tunable',\n\t\tdescription: 'Ask Rhino.Compute to cache solve results server-side.'\n\t})\n]);\n\nexport const API_TOKEN_RATE_LIMIT_SETTING = tunableInt(\n\t'API_TOKEN_RATE_LIMIT_MAX',\n\t600,\n\t'API requests per minute',\n\t'Requests per API token per minute. 0 is off.',\n\t{ min: 0, zero: 'Off' }\n);\n\nexport const ENGINE_SETTINGS = composeManifest([\n\t// ── Wiring ───────────────────────────────────────────────────────────────\n\t...(\n\t\t[\n\t\t\t[\n\t\t\t\t'AUTH',\n\t\t\t\t'Sign-in',\n\t\t\t\t'Who checks passwords: local (this server), supabase, or header (your SSO proxy).'\n\t\t\t],\n\t\t\t[\n\t\t\t\t'DATA',\n\t\t\t\t'Database',\n\t\t\t\t'Where users, orgs and projects live: local (files on this server) or supabase.'\n\t\t\t],\n\t\t\t[\n\t\t\t\t'STORAGE',\n\t\t\t\t'File storage',\n\t\t\t\t'Where uploaded .gh files and images live: local (this server) or supabase.'\n\t\t\t]\n\t\t] as const\n\t).map(([slot, label, description]) =>\n\t\tdefineSetting({\n\t\t\tkey: `SELVA_${slot}_PROVIDER`,\n\t\t\tlabel,\n\t\t\ttype: 'string',\n\t\t\tdefault: 'local',\n\t\t\tonInvalid: 'fail',\n\t\t\tclass: 'bootstrap',\n\t\t\tsummary: true,\n\t\t\tdescription,\n\t\t\timpact:\n\t\t\t\t'Switching it does not move any data: the instance starts on what the new provider holds.'\n\t\t})\n\t),\n\tdefineSetting({\n\t\tkey: 'SELVA_TENANCY',\n\t\tlabel: 'Organizations',\n\t\ttype: 'enum',\n\t\tvalues: ['single', 'multi'],\n\t\tdefault: 'single',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsummary: true,\n\t\tdescription: 'single: everyone shares one organization. multi: users can create their own.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SELVA_CONFIG_PATH',\n\t\tlabel: 'Custom config file',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tdescription: 'A selva.config.js that replaces env-driven provider wiring.'\n\t}),\n\n\t// ── Keys ─────────────────────────────────────────────────────────────────\n\tdefineSetting({\n\t\tkey: 'SELVA_HMAC_KEY',\n\t\tlabel: 'Signing key',\n\t\ttype: 'string',\n\t\tminLength: 32,\n\t\trequired: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tgenerated: true,\n\t\tsummary: true,\n\t\tdescription:\n\t\t\t'Stops sign-ins, links and tokens from being forged. Generated at install; never share it.',\n\t\timpact:\n\t\t\t'Changing it without SELVA_HMAC_KEY_PREVIOUS breaks what it signed: run `selva keys rotate hmac`.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SELVA_AT_REST_KEY',\n\t\tlabel: 'Encryption key',\n\t\ttype: 'key',\n\t\trequired: true,\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tgenerated: true,\n\t\tsummary: true,\n\t\tdescription: 'Encrypts the Rhino.Compute API keys stored here. Generated at install.',\n\t\timpact:\n\t\t\t'Changing it without SELVA_AT_REST_KEY_PREVIOUS makes stored API keys unreadable: run `selva keys rotate at-rest`.'\n\t}),\n\n\tdefineSetting({\n\t\tkey: 'SELVA_HMAC_KEY_PREVIOUS',\n\t\tlabel: 'Previous signing key',\n\t\ttype: 'string',\n\t\tminLength: 32,\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tgenerated: true,\n\t\tsummary: true,\n\t\tdescription: 'Kept after a rotation so what the old signing key signed works until it expires.',\n\t\timpact: 'Removing it ends sessions, MCP clients and links signed before the rotation.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SELVA_AT_REST_KEY_PREVIOUS',\n\t\tlabel: 'Previous encryption key',\n\t\ttype: 'key',\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tgenerated: true,\n\t\tsummary: true,\n\t\tdescription:\n\t\t\t'Kept after a rotation until stored API keys are re-encrypted, which happens at the next start.',\n\t\timpact: 'Remove it only once /admin/system shows no API key on the previous key.'\n\t}),\n\n\tdefineSetting({\n\t\tkey: 'SELVA_HMAC_KEY_PREVIOUS_EXPIRES',\n\t\tlabel: 'Previous signing key expiry',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tdescription:\n\t\t\t'When SELVA_HMAC_KEY_PREVIOUS stops being accepted (ISO date). Set by `selva keys rotate`.',\n\t\timpact:\n\t\t\t'After it, anything only the previous key opens is refused. An unreadable date counts as passed.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SELVA_AT_REST_KEY_PREVIOUS_EXPIRES',\n\t\tlabel: 'Previous encryption key expiry',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tdescription:\n\t\t\t'When SELVA_AT_REST_KEY_PREVIOUS stops being accepted (ISO date). Set by `selva keys rotate`.',\n\t\timpact:\n\t\t\t'After it, anything only the previous key opens is refused. An unreadable date counts as passed.'\n\t}),\n\n\t// ── Access ───────────────────────────────────────────────────────────────\n\tdefineSetting({\n\t\tkey: 'BOOTSTRAP_INSTANCE_ADMIN_EMAIL',\n\t\tlabel: 'Recovery admin email',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'bootstrap',\n\t\tsensitive: true,\n\t\tsummary: true,\n\t\tdescription:\n\t\t\t'While no instance admin exists, only this address may become one. For first setup and lockouts.'\n\t}),\n\tSIGN_IN_MAX_AGE_SETTING,\n\tflag('ALLOW_ORG_CREATION', 'Users create orgs', 'Self-service org creation (read by host apps).'),\n\tflag(\n\t\t'ALLOW_CROSS_ORG_PUBLIC',\n\t\t'Public across orgs',\n\t\t'Public projects are visible to every signed-in user, not just the publishing org.',\n\t\t'Turning it on widens who sees existing public projects.'\n\t),\n\tflag(\n\t\t'ALLOW_ORG_COMPUTE_OVERRIDE',\n\t\t'Orgs bring their own compute',\n\t\t'Orgs may configure their own Rhino.Compute server.'\n\t),\n\tflag(\n\t\t'ENABLE_SHARING',\n\t\t'Share links',\n\t\t'Per-definition share links for anonymous access.',\n\t\t'Turning it off stops every existing share link from resolving.'\n\t),\n\tflag(\n\t\t'ENABLE_PLATFORM_PROJECTS',\n\t\t'Platform projects',\n\t\t'Projects owned by instance admins and granted to orgs or users.'\n\t),\n\n\t// ── Branding ─────────────────────────────────────────────────────────────\n\t...(\n\t\t[\n\t\t\t['NAME', 'Product name', 'Product name in the header and titles.'],\n\t\t\t['COPYRIGHT_NAME', 'Copyright holder', 'Footer copyright owner. Defaults to the brand name.'],\n\t\t\t['TAGLINE', 'Tagline', 'Subtitle on the landing page.'],\n\t\t\t['DESCRIPTION', 'Site description', 'Meta description for search and link previews.']\n\t\t] as const\n\t).map(([key, label, description]) =>\n\t\tdefineSetting({\n\t\t\tkey: `SELVA_BRAND_${key}`,\n\t\t\tlabel,\n\t\t\ttype: 'string',\n\t\t\tonInvalid: 'fail',\n\t\t\tclass: 'setting',\n\t\t\tdescription\n\t\t})\n\t),\n\n\t// ── Mail ─────────────────────────────────────────────────────────────────\n\tdefineSetting({\n\t\tkey: 'SMTP_HOST',\n\t\tlabel: 'Mail server',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription: 'SMTP server. Unset: invites return a link to send by hand.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SMTP_PORT',\n\t\tlabel: 'Mail server port',\n\t\ttype: 'int',\n\t\tmin: 1,\n\t\tmax: 65535,\n\t\tdefault: 587,\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tdescription: '587 for STARTTLS, 465 for implicit TLS.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SMTP_USER',\n\t\tlabel: 'Mail username',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tsensitive: true,\n\t\tdescription: 'SMTP login.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SMTP_PASS',\n\t\tlabel: 'Mail password',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'secret',\n\t\tsensitive: true,\n\t\tdescription: 'SMTP password.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SMTP_FROM',\n\t\tlabel: 'Sender address',\n\t\ttype: 'string',\n\t\tonInvalid: 'fail',\n\t\tclass: 'setting',\n\t\tsensitive: true,\n\t\tdescription: 'Sender address. Required once SMTP_HOST is set.'\n\t}),\n\tdefineSetting({\n\t\tkey: 'SMTP_SECURE',\n\t\tlabel: 'Mail TLS mode',\n\t\ttype: 'bool',\n\t\tonInvalid: 'fail',\n\t\tclass: 'tunable',\n\t\tdescription: 'Override the TLS mode inferred from the port.',\n\t\tlegacy: { bool: 'exact-true' }\n\t}),\n\n\t// ── Compute limits ───────────────────────────────────────────────────────\n\tCOMPUTE_LIMIT_SETTINGS,\n\tAPI_TOKEN_RATE_LIMIT_SETTING\n]);\n","/**\n * The transport-free error type every API handler raises.\n *\n * `apiError` used to throw SvelteKit's `error()` directly, which welded all 151\n * of its call sites to one framework. `ApiError` carries the same envelope as a\n * plain exception; the host adapter converts it to whatever its framework\n * expects (see `toApiResponse`). Call sites are unchanged — only the throw\n * site and the boundary know the difference.\n */\n\n/** Stable, machine-readable error codes. Append-only — never renumber/rename. */\nexport const ApiErrorCode = {\n\tVALIDATION_FAILED: 'VALIDATION_FAILED',\n\tUNAUTHORIZED: 'UNAUTHORIZED',\n\tFORBIDDEN: 'FORBIDDEN',\n\tNOT_FOUND: 'NOT_FOUND',\n\tCONFLICT: 'CONFLICT',\n\tUNPROCESSABLE: 'UNPROCESSABLE',\n\tCOMPUTE_UNAVAILABLE: 'COMPUTE_UNAVAILABLE',\n\tSETUP_REQUIRED: 'SETUP_REQUIRED',\n\tINTERNAL: 'INTERNAL',\n\t/** API tokens are switched off or misconfigured here; browser sessions still work. */\n\tAPI_TOKENS_UNAVAILABLE: 'API_TOKENS_UNAVAILABLE',\n\t/** Too many requests, or a share link's solve cap is spent. `Retry-After`, when sent, says when to retry. */\n\tRATE_LIMITED: 'RATE_LIMITED',\n\t/** The key is valid, but the host's holder policy no longer lets its owner hold API tokens. */\n\tAPI_TOKEN_HOLDER_REFUSED: 'API_TOKEN_HOLDER_REFUSED',\n\t/** The caller's last sign-in at the identity provider is too old for this; sign in again. */\n\tSIGN_IN_REQUIRED: 'SIGN_IN_REQUIRED'\n} as const;\n\nexport type ApiErrorCode = (typeof ApiErrorCode)[keyof typeof ApiErrorCode];\n\nexport class ApiError extends Error {\n\treadonly status: number;\n\treadonly code: ApiErrorCode;\n\t/** Per-field validation messages, keyed by dotted path. Only on VALIDATION_FAILED. */\n\treadonly fields?: Record<string, string>;\n\t/** Machine-readable context, e.g. `requiredScope` on a scope refusal. */\n\treadonly details?: Record<string, string>;\n\n\tconstructor(\n\t\tstatus: number,\n\t\tcode: ApiErrorCode,\n\t\tmessage: string,\n\t\tfields?: Record<string, string>,\n\t\tdetails?: Record<string, string>\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'ApiError';\n\t\tthis.status = status;\n\t\tthis.code = code;\n\t\tthis.fields = fields;\n\t\tthis.details = details;\n\t}\n}\n\nexport interface ApiErrorBody {\n\tmessage: string;\n\tcode: ApiErrorCode;\n\tfields?: Record<string, string>;\n\tdetails?: Record<string, string>;\n}\n\nexport function toErrorBody(err: ApiError): ApiErrorBody {\n\tconst body: ApiErrorBody = { message: err.message, code: err.code };\n\tif (err.fields) body.fields = err.fields;\n\tif (err.details) body.details = err.details;\n\treturn body;\n}\n\nexport function isApiError(err: unknown): err is ApiError {\n\treturn err instanceof ApiError;\n}\n\n/** Raise a structured API error. The only way handlers should fail. */\nexport function apiError(\n\tstatus: number,\n\tcode: ApiErrorCode,\n\tmessage: string,\n\tfields?: Record<string, string>,\n\tdetails?: Record<string, string>\n): never {\n\tthrow new ApiError(status, code, message, fields, details);\n}\n\n/** Default code for a status, for mapping errors that carry no code of their own. */\nexport function codeForStatus(status: number): ApiErrorCode {\n\tswitch (status) {\n\t\tcase 400:\n\t\t\treturn ApiErrorCode.VALIDATION_FAILED;\n\t\tcase 401:\n\t\t\treturn ApiErrorCode.UNAUTHORIZED;\n\t\tcase 403:\n\t\t\treturn ApiErrorCode.FORBIDDEN;\n\t\tcase 404:\n\t\t\treturn ApiErrorCode.NOT_FOUND;\n\t\tcase 409:\n\t\t\treturn ApiErrorCode.CONFLICT;\n\t\tcase 422:\n\t\t\treturn ApiErrorCode.UNPROCESSABLE;\n\t\tcase 429:\n\t\t\treturn ApiErrorCode.RATE_LIMITED;\n\t\tcase 503:\n\t\t\treturn ApiErrorCode.COMPUTE_UNAVAILABLE;\n\t\tdefault:\n\t\t\treturn ApiErrorCode.INTERNAL;\n\t}\n}\n","import type { Project, ProjectAccessInput, RequestContext } from '@selvajs/platform';\n\n/**\n * Marshals an app's providers into the one input shape platform's pure access\n * rules (`canView`/`canEdit`/`canSolve`/`canManage`/…) read. What lives here is\n * **which rows each visibility needs**, so a consuming app doesn't reimplement\n * and mis-fetch it:\n *\n * - `platform` → grants (skipped entirely while the feature flag is off)\n * - `private` → caller's project member row\n * - `org` / `public` → caller's project member row (for canEdit/canManage) and\n * org member row (for canView). Cross-org public skips the org row.\n *\n * Row lookups are injected as functions so lazily-initialized providers work\n * unchanged, and flags are read per call so runtime flips behave like the app's\n * own `flag()` reads.\n */\n\nexport interface ProjectAccessFlags {\n\t/** `ALLOW_CROSS_ORG_PUBLIC` — public visibility spans orgs when true. */\n\tallowCrossOrgPublic: boolean;\n\t/** `ENABLE_PLATFORM_PROJECTS` — platform visibility is live when true. */\n\tenablePlatformProjects: boolean;\n}\n\nexport interface ProjectAccessInputDeps {\n\tgetProjectMember(\n\t\tctx: RequestContext,\n\t\tprojectId: string,\n\t\tuserId: string\n\t): Promise<ProjectAccessInput['member']>;\n\tgetOrgMember(\n\t\tctx: RequestContext,\n\t\torgId: string,\n\t\tuserId: string\n\t): Promise<ProjectAccessInput['orgMember']>;\n\tlistPlatformGrants(\n\t\tctx: RequestContext,\n\t\tprojectId: string\n\t): Promise<ProjectAccessInput['platformGrants']>;\n\t/** Read the two access-relevant feature flags. Called once per assembly. */\n\tflags(): ProjectAccessFlags;\n}\n\nexport interface ProjectAccessInputBuilder {\n\t/**\n\t * Fetches exactly the rows the rule will consult, based on\n\t * `project.visibility`. Other fields default to safe values; `overrides` is\n\t * for the rare caller that already loaded a row (tests, batched listings).\n\t */\n\tbuildProjectAccessInput(\n\t\tctx: RequestContext,\n\t\tproject: Project,\n\t\toverrides?: Partial<ProjectAccessInput>\n\t): Promise<ProjectAccessInput>;\n\t/**\n\t * Same input, from caller-provided rows and no I/O. A listing page that has\n\t * batch-loaded membership calls this per row instead of\n\t * `buildProjectAccessInput`, which would fetch N+1 times.\n\t */\n\tprojectAccessInputFromRows(\n\t\tctx: RequestContext,\n\t\tproject: Project,\n\t\trows: {\n\t\t\tmember?: ProjectAccessInput['member'];\n\t\t\torgMember?: ProjectAccessInput['orgMember'];\n\t\t\tplatformGrants?: ProjectAccessInput['platformGrants'];\n\t\t}\n\t): ProjectAccessInput;\n}\n\nexport function createProjectAccessInputBuilder(\n\tdeps: ProjectAccessInputDeps\n): ProjectAccessInputBuilder {\n\treturn {\n\t\tasync buildProjectAccessInput(\n\t\t\tctx: RequestContext,\n\t\t\tproject: Project,\n\t\t\toverrides: Partial<ProjectAccessInput> = {}\n\t\t): Promise<ProjectAccessInput> {\n\t\t\tconst { allowCrossOrgPublic, enablePlatformProjects } = deps.flags();\n\n\t\t\tlet member: ProjectAccessInput['member'] = null;\n\t\t\tlet orgMember: ProjectAccessInput['orgMember'] = null;\n\t\t\tlet platformGrants: ProjectAccessInput['platformGrants'] = [];\n\n\t\t\tif (project.visibility === 'platform') {\n\t\t\t\t// With the flag off every rule returns false before reading grants,\n\t\t\t\t// so the lookup would be wasted I/O.\n\t\t\t\tif (enablePlatformProjects) {\n\t\t\t\t\tplatformGrants = await deps.listPlatformGrants(ctx, project.id);\n\t\t\t\t}\n\t\t\t} else if (project.visibility === 'private') {\n\t\t\t\tmember = await deps.getProjectMember(ctx, project.id, ctx.userId);\n\t\t\t} else {\n\t\t\t\tconst skipOrgMember = project.visibility === 'public' && allowCrossOrgPublic;\n\t\t\t\t[member, orgMember] = await Promise.all([\n\t\t\t\t\tdeps.getProjectMember(ctx, project.id, ctx.userId),\n\t\t\t\t\tskipOrgMember ? Promise.resolve(null) : deps.getOrgMember(ctx, project.orgId, ctx.userId)\n\t\t\t\t]);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\torgPermissions: ctx.orgPermissions,\n\t\t\t\tplatformPermissions: ctx.platformPermissions,\n\t\t\t\tproject,\n\t\t\t\tmember,\n\t\t\t\torgMember,\n\t\t\t\tallowCrossOrgPublic,\n\t\t\t\tenablePlatformProjects,\n\t\t\t\tplatformGrants,\n\t\t\t\tactingOrgId: ctx.actingOrgId ?? null,\n\t\t\t\tuserId: ctx.userId,\n\t\t\t\t...overrides\n\t\t\t};\n\t\t},\n\n\t\tprojectAccessInputFromRows(\n\t\t\tctx: RequestContext,\n\t\t\tproject: Project,\n\t\t\trows: {\n\t\t\t\tmember?: ProjectAccessInput['member'];\n\t\t\t\torgMember?: ProjectAccessInput['orgMember'];\n\t\t\t\tplatformGrants?: ProjectAccessInput['platformGrants'];\n\t\t\t}\n\t\t): ProjectAccessInput {\n\t\t\tconst { allowCrossOrgPublic, enablePlatformProjects } = deps.flags();\n\t\t\treturn {\n\t\t\t\torgPermissions: ctx.orgPermissions,\n\t\t\t\tplatformPermissions: ctx.platformPermissions,\n\t\t\t\tproject,\n\t\t\t\tmember: rows.member ?? null,\n\t\t\t\torgMember: rows.orgMember ?? null,\n\t\t\t\tallowCrossOrgPublic,\n\t\t\t\tenablePlatformProjects,\n\t\t\t\tplatformGrants: rows.platformGrants ?? [],\n\t\t\t\tactingOrgId: ctx.actingOrgId ?? null,\n\t\t\t\tuserId: ctx.userId\n\t\t\t};\n\t\t}\n\t};\n}\n","/**\n * The permission guards every API handler runs before touching a store.\n *\n * These name no framework. A guard raises `ApiError`, which `runHandler` folds\n * into the response envelope — so the same guard protects a SvelteKit route, a\n * Next route handler, or a Hono route behind that host's own adapter.\n *\n * **Guards that redirect stay with the host.** A redirect is a browser-page\n * concept, not an API one, and a framework implements it by throwing a value\n * only that framework understands.\n *\n * A caller outside an API route — a page load, or a route that builds its own\n * `Response` — has to convert the `ApiError` at its boundary, since a framework\n * will not recognize it. Selva does that with `asHttpError` in\n * `access.server.ts`; SvelteKit gives anything that is not its own `HttpError` a\n * 500, so an unconverted guard denial reads as a crash.\n *\n * Providers arrive through {@link AccessDeps} rather than being resolved here.\n * That is what keeps this module importable without booting an app: a guard\n * that reached for a module global would drag the whole composition root — and\n * its top-level `await createSelvaProviders()` — into every consumer.\n */\n\nimport type {\n\tAuthUser,\n\tDefinitionRecord,\n\tOrgMember,\n\tOrgPermission,\n\tOrgRole,\n\tPlatformPermission,\n\tProject,\n\tProjectVisibility,\n\tRequestContext,\n\tSelvaConfig\n} from '@selvajs/platform';\nimport {\n\tisFlagEnabled,\n\thasPermission,\n\tcanReclaim,\n\tcanCreateProject,\n\tcanChangeOrgRole,\n\tcanView,\n\tcanSolve,\n\tcanCreateDefinition,\n\tcanManage,\n\tcanEditProjectSettings,\n\tcanEditDefinition,\n\tcanChangeVisibilityToPublic,\n\toutsideTokenOrg,\n\tscopeAllows,\n\tSYSTEM_CONTEXT\n} from '@selvajs/platform';\nimport {\n\tcreateProjectAccessInputBuilder,\n\ttype ProjectAccessInputBuilder\n} from './project-access-input.js';\nimport { apiError, ApiErrorCode } from '../api/errors.js';\nimport type { SelvaDeps } from '../api/deps.js';\n\nexport type AnyPermission = PlatformPermission | OrgPermission;\n\n/**\n * What the permission-only guards read.\n *\n * `deps` is absent here on purpose: `requirePermission` and friends check\n * `ctx.platformPermissions` and touch no store, so demanding providers from\n * their callers — the ~20 admin routes and page loads that only ever ask \"may\n * this user do X?\" — would be a cost with nothing behind it. The guards that do\n * read stores take `HasDeps` instead, which requires them.\n */\nexport interface Locals {\n\tuser?: AuthUser;\n\tctx?: RequestContext;\n}\n\n/**\n * What a store-reading guard takes: identity plus the providers to read with.\n *\n * `ApiRequest` satisfies this structurally, so a mounted handler passes itself.\n * Everyone else passes `scoped(locals)`.\n */\ntype ScopedLocals = Locals & HasDeps;\n\n/**\n * The stores a guard reads, injected rather than resolved.\n *\n * `ApiRequest` satisfies this structurally, so a mounted handler passes itself\n * and the guard runs against that request's providers.\n *\n * **Required, not optional.** These guards used to fall back to a host's module\n * globals when no `deps` arrived, which meant importing this file pulled in that\n * host's composition root — in Selva a module running a top-level\n * `await createSelvaProviders()`, so any handler importing a guard booted the\n * whole provider stack. That is what kept these guards in the app; a caller with\n * no `deps` in hand builds them with `accessDepsFromConfig`.\n */\nexport type AccessDeps = Pick<\n\tSelvaDeps,\n\t'orgs' | 'projects' | 'definitionMeta' | 'platformProjectGrants' | 'flag'\n>;\n\ninterface HasDeps {\n\tdeps: AccessDeps;\n}\n\n/**\n * Derive the stores a guard needs from a resolved config.\n *\n * Pure — it reads the config it is handed and nothing else, which is what keeps\n * this module free of any import that boots the app. Page loads pass\n * `locals.providers`; `hooks.server.ts` sets it on every request.\n */\nexport function accessDepsFromConfig(config: SelvaConfig): AccessDeps {\n\treturn {\n\t\torgs: config.data.orgs,\n\t\tprojects: config.data.projects,\n\t\tdefinitionMeta: config.data.definitions,\n\t\tplatformProjectGrants: config.data.platformProjectGrants,\n\t\tflag: (name) => isFlagEnabled(config, name)\n\t};\n}\n\n/** `locals` as a store-reading guard wants it. */\nexport function scoped<L extends Locals & { providers: SelvaConfig }>(\n\tlocals: L\n): L & { deps: AccessDeps } {\n\treturn { ...locals, deps: accessDepsFromConfig(locals.providers) };\n}\n\n// Accessors rather than `src.deps.orgs` inline: they keep the 17 call sites\n// below reading the same as before, and they are the single place that would\n// change if `AccessDeps` grew a store.\nconst orgsOf = (src: HasDeps) => src.deps.orgs;\nconst projectsOf = (src: HasDeps) => src.deps.projects;\nconst definitionMetaOf = (src: HasDeps) => src.deps.definitionMeta;\nconst flagOf = (src: HasDeps) => src.deps.flag;\n\nexport function requireAuthed(locals: Locals): { user: AuthUser; ctx: RequestContext } {\n\tconst { user, ctx } = locals;\n\tif (!user || !ctx) apiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\treturn { user, ctx };\n}\n\n/** Throws 403 — use in API routes. */\nexport function requirePermission(locals: Locals, permission: AnyPermission): AuthUser {\n\tconst { user, ctx } = requireAuthed(locals);\n\tif (!hasPermission(ctx, permission)) {\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, `You don't have permission to do this.`);\n\t}\n\treturn user;\n}\n\n// Named aliases exist only for permissions with real call sites. Routes gating\n// on anything else call `requirePermission(locals, '…')` directly rather than\n// growing an alias per permission — `manage_definitions` and `manage_projects`\n// had wrappers that nothing ever called.\nexport const requireManageInstanceUsers = (locals: Locals) =>\n\trequirePermission(locals, 'manage_instance_users');\nexport const requireManageCompute = (locals: Locals) => requirePermission(locals, 'manage_compute');\nexport const requireManageOrgMembers = (locals: Locals) =>\n\trequirePermission(locals, 'manage_org_members');\nexport const requireManageOrgCompute = (locals: Locals) =>\n\trequirePermission(locals, 'manage_org_compute');\n\nexport const requireInstanceAdmin = (locals: Locals) => requirePermission(locals, 'instance_admin');\n\n/**\n * Platform scope is not delegable: `manage_instance_users` runs the user-admin\n * surface but must not be able to mint an `instance_admin`, or an org admin\n * holding it self-elevates. Three routes write platform permissions — the two\n * `/api/admin/users` handlers and the invite mint route — and each carried its\n * own copy of this check.\n *\n * Pass `current` on an update. Revoking is a platform-scope change too, so a\n * PATCH that drops `instance_admin` is refused for the same reason granting it\n * is; without `current` the caller is creating (a user, an invite) and there is\n * nothing to compare against.\n *\n * Requesting nothing on a create is always allowed — that is a\n * `manage_instance_users` operation, not a platform-scope one.\n */\nexport function assertCanGrantPlatformPermissions(\n\tctx: RequestContext,\n\trequested: readonly PlatformPermission[],\n\tcurrent?: readonly PlatformPermission[]\n): void {\n\tconst changed = current\n\t\t? requested.length !== current.length ||\n\t\t\trequested.some((p) => !current.includes(p)) ||\n\t\t\tcurrent.some((p) => !requested.includes(p))\n\t\t: requested.length > 0;\n\tif (!changed) return;\n\tif (hasPermission(ctx, 'instance_admin')) return;\n\tapiError(\n\t\t403,\n\t\tApiErrorCode.FORBIDDEN,\n\t\tcurrent\n\t\t\t? 'Only a platform admin can change platform-scope permissions'\n\t\t\t: 'Only a platform admin can grant platform-scope permissions'\n\t);\n}\n\n/**\n * Tenancy gate for `/api/v1/orgs/{orgId}/…`. The URL id is never trusted alone\n * — the acting context decides which tenant a request applies to, so a\n * mismatch is 403 rather than a silent read of the caller's own org.\n */\nexport function requireActingOrg(\n\tlocals: Locals,\n\torgId: string | undefined\n): { ctx: RequestContext; orgId: string } {\n\tconst ctx = locals.ctx;\n\tif (!ctx) apiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\tif (!orgId) apiError(400, ApiErrorCode.VALIDATION_FAILED, 'Missing org ID');\n\tif (!ctx.actingOrgId) apiError(400, ApiErrorCode.VALIDATION_FAILED, 'No active organization');\n\tif (ctx.actingOrgId !== orgId) {\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'Acting org does not match the target org.');\n\t}\n\treturn { ctx, orgId };\n}\n\n/**\n * Gate for pages reachable by any platform-class permission holder (the\n\n/**\n * Management-scope bypass — used for org governance and project management\n * actions (Reclaim, create project, delete project, manage members, edit\n * settings). `instance_admin` bypasses these so platform staff can administer\n * the instance without being a member of every org.\n *\n * NOT used for content access (view, solve, edit definitions):\n * `instance_admin` follows the same `canView`/`canEdit` rules as any other\n * user there, keeping blast radius small and forcing content escalation\n * through Reclaim, which leaves an audit trail.\n */\nasync function managementBypassOrRun(\n\tctx: RequestContext,\n\tcheck: () => Promise<boolean>\n): Promise<boolean> {\n\tif (hasPermission(ctx, 'instance_admin')) return true;\n\treturn await check();\n}\n\n// Content-scope check — NO `instance_admin` bypass. `canView`, `canSolve`,\n// `canEdit`, and `canEditDefinition` run as-is regardless of platform role;\n// platform staff use Reclaim first if they need content access.\nasync function contentCheck(check: () => Promise<boolean>): Promise<boolean> {\n\treturn await check();\n}\n\n// With ENABLE_PLATFORM_PROJECTS off every rule denies a platform project, even for\n// `instance_admin`, so the bypass must not reopen it.\nfunction managementBypassForProject(\n\tctx: RequestContext,\n\tproject: Project,\n\tsrc: HasDeps,\n\tcheck: () => Promise<boolean>\n): Promise<boolean> {\n\tif (project.visibility === 'platform' && !flagOf(src)('ENABLE_PLATFORM_PROJECTS')) {\n\t\treturn check();\n\t}\n\treturn managementBypassOrRun(ctx, check);\n}\n\nasync function loadProjectOr404(\n\tctx: RequestContext,\n\tprojectId: string,\n\tsrc: HasDeps\n): Promise<Project> {\n\tconst project = await projectsOf(src).getProject(ctx, projectId);\n\tif (!project || outsideTokenOrg(ctx, project.orgId)) {\n\t\tapiError(404, ApiErrorCode.NOT_FOUND, 'Project not found');\n\t}\n\treturn project;\n}\n\n// Rule-input assembly (the \"which rows does each visibility need\" knowledge)\n// lives in `@selvajs/server/access`; this binding wires it to the provider set\n// the caller carries.\nfunction accessInputsFor(src: HasDeps) {\n\tconst readFlag = flagOf(src);\n\treturn createProjectAccessInputBuilder({\n\t\tgetProjectMember: (ctx, projectId, userId) =>\n\t\t\tprojectsOf(src).getProjectMember(ctx, projectId, userId),\n\t\tgetOrgMember: (ctx, orgId, userId) => orgsOf(src).getOrgMember(ctx, orgId, userId),\n\t\tlistPlatformGrants: (ctx, projectId) =>\n\t\t\tsrc.deps.platformProjectGrants.listByProject(ctx, projectId),\n\t\tflags: () => ({\n\t\t\tallowCrossOrgPublic: readFlag('ALLOW_CROSS_ORG_PUBLIC'),\n\t\t\tenablePlatformProjects: readFlag('ENABLE_PLATFORM_PROJECTS')\n\t\t})\n\t});\n}\n\nfunction buildProjectAccessInput(\n\tctx: RequestContext,\n\tproject: Project,\n\tsrc: HasDeps,\n\toverrides?: Parameters<ProjectAccessInputBuilder['buildProjectAccessInput']>[2]\n) {\n\treturn accessInputsFor(src).buildProjectAccessInput(ctx, project, overrides);\n}\n\n/**\n * Assemble a rule input from rows the caller already loaded.\n *\n * Unlike the other builders this one issues no reads — the caller batched them.\n * It still needs `deps` for the flag lookups, which decide whether a\n * cross-org-public or platform project is visible at all.\n */\nexport function projectAccessInputFromRowsWith(\n\tsrc: HasDeps,\n\t...args: Parameters<ProjectAccessInputBuilder['projectAccessInputFromRows']>\n) {\n\treturn accessInputsFor(src).projectAccessInputFromRows(...args);\n}\n\n/**\n * Gates creation of a *new* definition. Container projects require project\n * owner/editor (canEdit). Commons projects (`autoJoinOnUpload=true`) accept\n * any authenticated user — the handler stamps `ownerId = user.id` so the\n * uploader becomes the owner.\n */\nexport async function requireCanCreateDefinition(\n\tlocals: ScopedLocals,\n\tprojectId: string\n): Promise<{ user: AuthUser; ctx: RequestContext; project: Project }> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst project = await loadProjectOr404(ctx, projectId, locals);\n\tconst allowed = await contentCheck(async () =>\n\t\tcanCreateDefinition(await buildProjectAccessInput(ctx, project, locals))\n\t);\n\tif (!allowed) {\n\t\tapiError(\n\t\t\t403,\n\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\t'You do not have permission to upload definitions to this project.'\n\t\t);\n\t}\n\treturn { user, ctx, project };\n}\n\n/**\n * Project members must belong to the project's parent org. Enforced at the\n * rule layer, not as a DB constraint, to leave room for cross-org guests\n * later without a schema migration.\n */\nexport async function requireTargetIsOrgMember(\n\tlocals: ScopedLocals,\n\torgId: string,\n\ttargetUserId: string\n): Promise<void> {\n\tconst { ctx } = requireAuthed(locals);\n\tconst member = await orgsOf(locals).getOrgMember(ctx, orgId, targetUserId);\n\tif (!member) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t'User must be a member of this organization to be added to a project.'\n\t\t);\n\t}\n}\n\n/**\n * `canChangeOrgRole` with the actor's membership row loaded — whether the\n * caller may grant or revoke org `owner`/`admin` standing (§3).\n *\n * Returns rather than throws: the three callers each phrase the refusal for\n * what they were doing (\"invite someone as owner\", \"change roles\", \"remove\n * another owner\") and raise it through `apiError`. What must not diverge is the\n * decision, which is why that half lives in `rules.ts` and this loads its input.\n */\nexport async function canActorChangeOrgRole(\n\tctx: RequestContext,\n\torgId: string,\n\trole: OrgRole,\n\tsrc: HasDeps\n): Promise<boolean> {\n\tif (role === 'member') return true;\n\tconst actorMember = await orgsOf(src).getOrgMember(ctx, orgId, ctx.userId);\n\treturn canChangeOrgRole({ actorMember, role });\n}\n\n/**\n * `canReclaim` — org owner/admin escape hatch. Returns the project so the\n * handler can use its `orgId` without re-fetching.\n */\nexport async function requireCanReclaim(\n\tlocals: ScopedLocals,\n\tprojectId: string\n): Promise<{ user: AuthUser; ctx: RequestContext; project: Project }> {\n\tconst { user, ctx } = requireAuthed(locals);\n\t// Reclaim exists for projects the caller cannot see, and RLS hides those from\n\t// their own session. Only the org's leadership may learn that one exists.\n\tconst visible = await projectsOf(locals).getProject(ctx, projectId);\n\tconst project = visible ?? (await projectsOf(locals).getProject(SYSTEM_CONTEXT, projectId));\n\tif (\n\t\t!project ||\n\t\toutsideTokenOrg(ctx, project.orgId) ||\n\t\t(!visible && project.orgId !== ctx.actingOrgId)\n\t) {\n\t\tapiError(404, ApiErrorCode.NOT_FOUND, 'Project not found');\n\t}\n\n\t// Ahead of the bypass, not inside the check: `instance_admin` short-circuits\n\t// `managementBypassOrRun`, so `canReclaim`'s platform-project refusal (§4a)\n\t// never ran for the one role that could reach it. Reclaim is content\n\t// escalation wearing management clothing — the management bypass is not its\n\t// to inherit.\n\tif (project.visibility === 'platform') {\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'Platform projects cannot be reclaimed.');\n\t}\n\n\tconst allowed = await managementBypassOrRun(ctx, async () => {\n\t\tconst orgMember = await orgsOf(locals).getOrgMember(ctx, project.orgId, ctx.userId);\n\t\treturn canReclaim({\n\t\t\tproject,\n\t\t\torgMember,\n\t\t\tactingOrgId: ctx.actingOrgId ?? null\n\t\t});\n\t});\n\tif (!allowed) {\n\t\tif (!visible) apiError(404, ApiErrorCode.NOT_FOUND, 'Project not found');\n\t\tapiError(\n\t\t\t403,\n\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\t'Only org owners or admins of this project’s org can reclaim it.'\n\t\t);\n\t}\n\treturn { user, ctx, project };\n}\n\n/**\n * May the caller create a project in `targetOrgId`? Owner/admin always; a\n * member needs `manage_projects`; tenancy is enforced via `actingOrgId`. An\n * API key also needs the `create_projects` scope (or `write`) org-wide.\n */\nexport async function canCreateProjectIn(\n\tlocals: ScopedLocals,\n\tctx: RequestContext,\n\ttargetOrgId: string\n): Promise<boolean> {\n\tif (!scopeAllows(ctx, 'create_projects')) return false;\n\treturn managementBypassOrRun(ctx, async () => {\n\t\tconst orgMember = await orgsOf(locals).getOrgMember(ctx, targetOrgId, ctx.userId);\n\t\treturn canCreateProject({\n\t\t\torgPermissions: ctx.orgPermissions,\n\t\t\torgMember,\n\t\t\tactingOrgId: ctx.actingOrgId ?? null,\n\t\t\ttargetOrgId\n\t\t});\n\t});\n}\n\nexport async function requireCanCreateProject(\n\tlocals: ScopedLocals,\n\ttargetOrgId: string\n): Promise<{ user: AuthUser; ctx: RequestContext }> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tif (!(await canCreateProjectIn(locals, ctx, targetOrgId)))\n\t\tapiError(\n\t\t\t403,\n\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\t'You do not have permission to create projects in this org.'\n\t\t);\n\treturn { user, ctx };\n}\n\n/**\n * The visibility a project may be created with or changed to, for create and\n * PATCH alike. `current` is absent on create.\n *\n * - `platform` takes a project out of its org entirely (no org member sees it,\n * and with ENABLE_PLATFORM_PROJECTS off every rule denies everyone), so\n * moving into it is instance-admin only.\n * - Becoming `public` is a disclosure, so it needs an org owner or admin.\n * - A key without `write` creates private projects only, never joinable ones:\n * whoever approved it was told it can't share anything.\n */\nexport async function requireProjectVisibilityAllowed(\n\tlocals: ScopedLocals,\n\tctx: RequestContext,\n\torgId: string,\n\tnext: { visibility?: ProjectVisibility; autoJoinOnUpload?: boolean },\n\tcurrent?: Pick<Project, 'visibility'>\n): Promise<void> {\n\t// Create only: PATCH already needs `write` on the project, which the mount checks with its target.\n\tif (!current && ctx.apiScope && !scopeAllows(ctx, 'write')) {\n\t\tif (next.visibility !== 'private' || next.autoJoinOnUpload === true) {\n\t\t\tapiError(\n\t\t\t\t403,\n\t\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\t\t'This API token can only create private projects that nobody joins on upload.'\n\t\t\t);\n\t\t}\n\t}\n\tif (next.visibility === 'platform' && current?.visibility !== 'platform') {\n\t\tif (!hasPermission(ctx, 'instance_admin')) {\n\t\t\tapiError(\n\t\t\t\t403,\n\t\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\t\t'Only a platform admin can give a project platform visibility.'\n\t\t\t);\n\t\t}\n\t}\n\tif (next.visibility === 'public' && current?.visibility !== 'public') {\n\t\tconst passes = await managementBypassOrRun(ctx, async () =>\n\t\t\tcanChangeVisibilityToPublic({\n\t\t\t\torgMember: await orgsOf(locals).getOrgMember(ctx, orgId, ctx.userId)\n\t\t\t})\n\t\t);\n\t\tif (!passes) {\n\t\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'Only org owners or admins can make a project public.');\n\t\t}\n\t}\n}\n\n/**\n * Project-management gate (`canManage` — owner, or `instance_admin` via the\n * bypass). Managing members is the same authority as managing the project, so\n * both callers share this; `action` only shapes the 403 message.\n */\nexport async function requireCanManage(\n\tlocals: ScopedLocals,\n\tprojectId: string,\n\taction: 'project' | 'members' = 'project'\n): Promise<AuthUser> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst project = await loadProjectOr404(ctx, projectId, locals);\n\tconst allowed = await managementBypassForProject(ctx, project, locals, async () =>\n\t\tcanManage(await buildProjectAccessInput(ctx, project, locals))\n\t);\n\tif (!allowed) {\n\t\tapiError(\n\t\t\t403,\n\t\t\tApiErrorCode.FORBIDDEN,\n\t\t\taction === 'members'\n\t\t\t\t? 'Only project owners can manage members.'\n\t\t\t\t: 'Only project owners can manage this project.'\n\t\t);\n\t}\n\treturn user;\n}\n\n// Owner-only gate for project settings, centralized so PATCH\n// /api/projects/[id] matches the rest of the access layer.\nexport async function requireCanEditProjectSettings(\n\tlocals: ScopedLocals,\n\tprojectId: string\n): Promise<{ user: AuthUser; ctx: RequestContext; project: Project }> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst project = await loadProjectOr404(ctx, projectId, locals);\n\tconst allowed = await managementBypassForProject(ctx, project, locals, async () =>\n\t\tcanEditProjectSettings(await buildProjectAccessInput(ctx, project, locals))\n\t);\n\tif (!allowed)\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'Only project owners can edit project settings.');\n\treturn { user, ctx, project };\n}\n\nexport async function requireCanViewProject(\n\tlocals: ScopedLocals,\n\tprojectId: string\n): Promise<AuthUser> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst allowed = await contentCheck(async () => {\n\t\tconst project = await loadProjectOr404(ctx, projectId, locals);\n\t\treturn canView(await buildProjectAccessInput(ctx, project, locals));\n\t});\n\tif (!allowed) apiError(403, ApiErrorCode.FORBIDDEN, 'You do not have access to this project.');\n\treturn user;\n}\n\n/**\n * Solve gating. Today `canSolve === canView` for non-platform projects, but\n * the rule lives in its own function so future cost-gating (quotas, rate\n * limits) lands without touching view semantics. `viewer` project role\n * passes; platform projects narrow to grants with `canSolve=true`.\n */\nexport async function requireCanSolve(\n\tlocals: ScopedLocals,\n\tprojectId: string,\n\t// Callers that already loaded the project (e.g. the solve endpoint, which\n\t// reads orgId/pin off it) pass it to skip a redundant `getProject` here.\n\tpreloadedProject?: Project\n): Promise<{ user: AuthUser; ctx: RequestContext; project: Project }> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst project = preloadedProject ?? (await loadProjectOr404(ctx, projectId, locals));\n\tif (outsideTokenOrg(ctx, project.orgId))\n\t\tapiError(404, ApiErrorCode.NOT_FOUND, 'Project not found');\n\tconst allowed = await contentCheck(async () =>\n\t\tcanSolve(await buildProjectAccessInput(ctx, project, locals))\n\t);\n\tif (!allowed) apiError(403, ApiErrorCode.FORBIDDEN, 'You do not have access to this project.');\n\treturn { user, ctx, project };\n}\n\n/**\n * Org membership for the commons branch of `canEditDefinition`, or `null` when\n * that branch cannot fire. Skipping the round-trip on container projects keeps\n * the common edit path at the same two reads it had before commons gained the\n * membership test.\n */\nasync function loadCommonsOrgMember(\n\tctx: RequestContext,\n\tproject: Project | null,\n\tsrc: HasDeps\n): Promise<OrgMember | null> {\n\tif (!project?.autoJoinOnUpload) return null;\n\treturn await orgsOf(src).getOrgMember(ctx, project.orgId, ctx.userId);\n}\n\n/**\n * Loads the record and gates editing. Returns the record AND the project it\n * loads for the gate, so callers skip a re-fetch of either.\n */\nexport async function requireEditableDefinition(locals: ScopedLocals, guid: string) {\n\tconst { ctx } = requireAuthed(locals);\n\tconst record = await definitionMetaOf(locals).get(ctx, guid);\n\tif (!record) apiError(404, ApiErrorCode.NOT_FOUND, 'Definition not found');\n\t// Load project + member once up front; `project` is returned for reuse.\n\tconst [project, member] = await Promise.all([\n\t\tprojectsOf(locals).getProject(ctx, record.projectId),\n\t\tprojectsOf(locals).getProjectMember(ctx, record.projectId, ctx.userId)\n\t]);\n\tif (project && outsideTokenOrg(ctx, project.orgId)) {\n\t\tapiError(404, ApiErrorCode.NOT_FOUND, 'Definition not found');\n\t}\n\tconst allowed = await contentCheck(async () =>\n\t\tcanEditDefinition({\n\t\t\tproject,\n\t\t\tdefinition: record,\n\t\t\tmember,\n\t\t\torgMember: await loadCommonsOrgMember(ctx, project, locals),\n\t\t\tuserId: ctx.userId,\n\t\t\tplatformPermissions: ctx.platformPermissions,\n\t\t\tenablePlatformProjects: flagOf(locals)('ENABLE_PLATFORM_PROJECTS')\n\t\t})\n\t);\n\tif (!allowed)\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'You do not have permission to edit this definition.');\n\treturn { record, ctx, project };\n}\n\nexport async function requireCanEditDefinition(\n\tlocals: ScopedLocals,\n\tprojectId: string,\n\tdefinitionGuid: string,\n\t// Callers that already loaded the project and/or definition (e.g. the solve\n\t// endpoint) pass them to skip the redundant fetches inside the gate. The\n\t// member row still loads here (the caller doesn't have it).\n\tpreloaded?: { project?: Project | null; definition?: DefinitionRecord | null }\n): Promise<AuthUser> {\n\tconst { user, ctx } = requireAuthed(locals);\n\tconst allowed = await contentCheck(async () => {\n\t\tconst [project, definition, member] = await Promise.all([\n\t\t\tpreloaded?.project !== undefined\n\t\t\t\t? Promise.resolve(preloaded.project)\n\t\t\t\t: projectsOf(locals).getProject(ctx, projectId),\n\t\t\tpreloaded?.definition !== undefined\n\t\t\t\t? Promise.resolve(preloaded.definition)\n\t\t\t\t: definitionMetaOf(locals).get(ctx, definitionGuid),\n\t\t\tprojectsOf(locals).getProjectMember(ctx, projectId, ctx.userId)\n\t\t]);\n\t\tif (project && outsideTokenOrg(ctx, project.orgId)) return false;\n\t\treturn canEditDefinition({\n\t\t\tproject,\n\t\t\tdefinition,\n\t\t\tmember,\n\t\t\torgMember: await loadCommonsOrgMember(ctx, project, locals),\n\t\t\tuserId: ctx.userId,\n\t\t\tplatformPermissions: ctx.platformPermissions,\n\t\t\tenablePlatformProjects: flagOf(locals)('ENABLE_PLATFORM_PROJECTS')\n\t\t});\n\t});\n\tif (!allowed)\n\t\tapiError(403, ApiErrorCode.FORBIDDEN, 'You do not have permission to edit this definition.');\n\treturn user;\n}\n","/**\n * Bridges the flat `permissions` array the v1 invite body accepts to the\n * two-scope model adapters expect. One invite legitimately carries both scopes,\n * so this is a wire-format adapter, not a migration shim — retire it only when\n * the invite body grows separate `platformPermissions` + `orgPermissions`\n * fields.\n */\n\nimport type { OrgPermission, PlatformPermission } from '@selvajs/platform';\nimport { ALL_ORG_PERMISSIONS, ALL_PLATFORM_PERMISSIONS } from '@selvajs/platform';\n\nconst PLATFORM_SET: ReadonlySet<string> = new Set(ALL_PLATFORM_PERMISSIONS);\nconst ORG_SET: ReadonlySet<string> = new Set(ALL_ORG_PERMISSIONS);\n\nexport interface SplitPermissions {\n\tplatform: PlatformPermission[];\n\torg: OrgPermission[];\n}\n\n/** Split a flat array into platform + org scope buckets, dropping unknowns. */\nexport function splitFlatPermissions(flat: readonly string[]): SplitPermissions {\n\tconst platform: PlatformPermission[] = [];\n\tconst org: OrgPermission[] = [];\n\tfor (const p of flat) {\n\t\tif (PLATFORM_SET.has(p)) platform.push(p as PlatformPermission);\n\t\telse if (ORG_SET.has(p)) org.push(p as OrgPermission);\n\t}\n\treturn { platform, org };\n}\n"],"mappings":";;;;;AAmGA,SAAgB,cAAqC,MAAY;CAChE,OAAO;AACR;;AAGA,SAAgB,gBAAgB,OAAwD;CACvF,MAAM,MAAqB,CAAC;CAC5B,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,QAAQ,OAClB,KAAK,MAAM,QAAQ,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAmB,GAAG;EACtE,KAAK,MAAM,QAAQ,CAAC,KAAK,KAAK,GAAI,KAAK,WAAW,CAAC,CAAE,GAAG;GACvD,IAAI,KAAK,IAAI,IAAI,GAAG,MAAM,IAAI,MAAM,cAAc,KAAK,mBAAmB;GAC1E,KAAK,IAAI,IAAI;EACd;EACA,IAAI,KAAK,IAAI;CACd;CAED,OAAO;AACR;;ACnHA,SAAgB,aAAa,GAAW,IAAoB;CAC3D,IAAI,MAAM,EAAE;CACZ,OAAO,MAAM,KAAK,EAAE,MAAM,OAAO,IAAI;CACrC,OAAO,EAAE,MAAM,GAAG,GAAG;AACtB;;;;;;ACAA,SAAgB,WAAW,KAA4B;CACtD,MAAM,MAAM,IAAI,KAAK;CACrB,IAAI,oBAAoB,KAAK,GAA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,SAAS;EACT,aAAa;CACd,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aAAa;CACd,CAAC;CAGD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,UAAU;EACV,WAAW;EACX,OAAO;EACP,WAAW;EACX,WAAW;EACX,SAAS;EACT,aACC;EACD,QACC;CACF,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,UAAU;EACV,WAAW;EACX,OAAO;EACP,WAAW;EACX,WAAW;EACX,SAAS;EACT,aAAa;EACb,QACC;CACF,CAAC;CAED,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,WAAW;EACX,OAAO;EACP,WAAW;EACX,WAAW;EACX,SAAS;EACT,aAAa;EACb,QAAQ;CACT,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,WAAW;EACX,WAAW;EACX,SAAS;EACT,aACC;EACD,QAAQ;CACT,CAAC;CAED,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aACC;EACD,QACC;CACF,CAAC;CACD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,aACC;EACD,QACC;CACF,CAAC;CAGD,cAAc;EACb,KAAK;EACL,OAAO;EACP,MAAM;EACN,WAAW;EACX,OAAO;EACP,WAAW;EACX,SAAS;EACT,aACC;CACF,CAAC;CACD;CACA,KAAK,sBAAsB,qBAAqB,gDAAgD;CAChG,KACC,0BACA,sBACA,qFACA,yDACD;CACA,KACC,8BACA,gCACA,oDACD;CACA,KACC,kBACA,eACA,oDACA,gEACD;CACA,KACC,4BACA,qBACA,iEACD;CAGA,GACC;EACC;GAAC;GAAQ;GAAgB;EAAwC;EACjE;GAAC;GAAkB;GAAoB;EAAqD;EAC5F;GAAC;GA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K,WAAW,IAAI,MAAM;EAC/D,CAAC;EACD,IAAI,WAAW,gBAAgB,KAAK,QAAQ,KAAK,GAAG,OAAO;EAC3D,OAAO,kBAAkB;GACxB;GACA;GACA;GACA,WAAW,MAAM,qBAAqB,KAAK,SAAS,MAAM;GAC1D,QAAQ,IAAI;GACZ,qBAAqB,IAAI;GACzB,wBAAwB,OAAO,MAAM,CAAC,CAAC,0BAA0B;EAClE,CAAC;CACF,CAAC,GAEA,SAAS,KAAK,aAAa,WAAW,qDAAqD;CAC5F,OAAO;AACR;;AC3pBA,IAAM,eAAoC,IAAI,IAAI,wBAAwB;AAC1E,IAAM,UAA+B,IAAI,IAAI,mBAAmB;;AAQhE,SAAgB,qBAAqB,MAA2C;CAC/E,MAAM,WAAiC,CAAC;CACxC,MAAM,MAAuB,CAAC;CAC9B,KAAK,MAAM,KAAK,MACf,IAAI,aAAa,IAAI,CAAC,GAAG,SAAS,KAAK,CAAuB;MACzD,IAAI,QAAQ,IAAI,CAAC,GAAG,IAAI,KAAK,CAAkB;CAErD,OAAO;EAAE;EAAU;CAAI;AACxB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { M as isApiError, c as requireAuthed } from "./access.js";
|
|
2
|
-
import {
|
|
3
|
-
import { n as OPERATOR_PLATFORM_PERMISSIONS } from "./types3.js";
|
|
2
|
+
import { r as hasPermission } from "./context.js";
|
|
4
3
|
import "./api.js";
|
|
4
|
+
import { n as OPERATOR_PLATFORM_PERMISSIONS } from "./types3.js";
|
|
5
5
|
import { error, redirect } from "@sveltejs/kit";
|
|
6
6
|
// src/lib/server/access.server.ts
|
|
7
7
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { M as isApiError, j as codeForStatus, k as ApiErrorCode } from "./access.js";
|
|
2
|
-
import {
|
|
2
|
+
import { i as ProviderError } from "./context.js";
|
|
3
3
|
import "./api.js";
|
|
4
4
|
import { a as ComputeServerUnconfiguredError, t as SchemaExtractionError } from "./schema-extraction.js";
|
|
5
5
|
import "./compute.js";
|