@sssb/kit 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/dist/core/webhook-hmac.d.ts +69 -0
- package/dist/release.json +1 -0
- package/dist/testing/e2e.d.ts +15 -0
- package/dist/testing/e2e.js +195 -0
- package/package.json +209 -3
- package/src/adapters/README.md +6 -0
- package/src/adapters/dev-server.ts +21 -0
- package/src/adapters/fake/agreements.ts +81 -0
- package/src/adapters/fake/analytics.ts +93 -0
- package/src/adapters/fake/atomic-write.ts +161 -0
- package/src/adapters/fake/audit.ts +58 -0
- package/src/adapters/fake/auth.ts +312 -0
- package/src/adapters/fake/clock.ts +54 -0
- package/src/adapters/fake/data-dir.ts +27 -0
- package/src/adapters/fake/db.ts +88 -0
- package/src/adapters/fake/email.ts +46 -0
- package/src/adapters/fake/jobs.ts +270 -0
- package/src/adapters/fake/llm.ts +230 -0
- package/src/adapters/fake/pglite-dialect.ts +124 -0
- package/src/adapters/fake/service-auth.ts +145 -0
- package/src/adapters/fake/simulator-admin.ts +203 -0
- package/src/adapters/fake/simulator.ts +94 -0
- package/src/adapters/fake/sms.ts +43 -0
- package/src/adapters/fake/storage.ts +288 -0
- package/src/adapters/fake/webhooks.ts +98 -0
- package/src/adapters/index.ts +115 -0
- package/src/adapters/real/accept-invite-form.tsx +77 -0
- package/src/adapters/real/analytics.ts +28 -0
- package/src/adapters/real/auth.ts +216 -0
- package/src/adapters/real/contract-data-api.ts +104 -0
- package/src/adapters/real/contract-postgres.ts +167 -0
- package/src/adapters/real/database-transport.ts +34 -0
- package/src/adapters/real/db-data-api.ts +61 -0
- package/src/adapters/real/db.ts +88 -0
- package/src/adapters/real/email.ts +22 -0
- package/src/adapters/real/index.ts +89 -0
- package/src/adapters/real/jobs.ts +32 -0
- package/src/adapters/real/llm.ts +108 -0
- package/src/adapters/real/migrate-handler.ts +66 -0
- package/src/adapters/real/providers.tsx +12 -0
- package/src/adapters/real/rds-data-codec.ts +508 -0
- package/src/adapters/real/rds-data-dialect.ts +470 -0
- package/src/adapters/real/rds-data-emulator.ts +351 -0
- package/src/adapters/real/s3-storage.ts +233 -0
- package/src/adapters/real/sign-in-form.tsx +59 -0
- package/src/adapters/real/storage.ts +10 -0
- package/src/adapters/sentry/baseline.ts +90 -0
- package/src/adapters/sentry/client.ts +17 -0
- package/src/adapters/sentry/init.ts +17 -0
- package/src/authz/app-exemptions.ts +226 -0
- package/src/authz/authorize.ts +214 -0
- package/src/authz/route-policy.ts +153 -0
- package/src/authz/route-scan.ts +1516 -0
- package/src/components/agreements/acceptances-section.tsx +55 -0
- package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
- package/src/components/agreements/agreement-body.tsx +34 -0
- package/src/components/agreements/agreement-gate.tsx +45 -0
- package/src/components/app-header.tsx +45 -0
- package/src/components/auth/accept-invite-screen.tsx +126 -0
- package/src/components/auth/auth-icons.tsx +68 -0
- package/src/components/auth/org-switcher.tsx +76 -0
- package/src/components/auth/people-picker.tsx +50 -0
- package/src/components/auth/preview-row.tsx +64 -0
- package/src/components/auth/sign-in-screen.tsx +24 -0
- package/src/components/auth/user-menu.tsx +64 -0
- package/src/components/demo-badge.tsx +20 -0
- package/src/components/demo-banner.tsx +14 -0
- package/src/components/gates/gate-interstitial.tsx +23 -0
- package/src/components/job-timeline.tsx +64 -0
- package/src/components/notifications/notification-bell.tsx +120 -0
- package/src/components/notifications/notification-prefs-section.tsx +112 -0
- package/src/components/org-screen.tsx +197 -0
- package/src/components/profile-screen.tsx +100 -0
- package/src/components/simulator/actor-runtime.ts +180 -0
- package/src/components/simulator/actor-shell.tsx +275 -0
- package/src/components/simulator/actors-app.tsx +119 -0
- package/src/components/simulator/errors-app.tsx +84 -0
- package/src/components/simulator/events-app.tsx +210 -0
- package/src/components/simulator/format-when.ts +20 -0
- package/src/components/simulator/hooks-app.tsx +319 -0
- package/src/components/simulator/inbound-app.tsx +210 -0
- package/src/components/simulator/jobs-app.tsx +471 -0
- package/src/components/simulator/mail-app.tsx +290 -0
- package/src/components/simulator/messages-app.tsx +64 -0
- package/src/components/simulator/people-app.tsx +140 -0
- package/src/components/simulator/people-dimensions.ts +16 -0
- package/src/components/simulator/simulator-panel.tsx +716 -0
- package/src/components/simulator/snapshots-app.tsx +398 -0
- package/src/components/simulator/tab-mount.ts +25 -0
- package/src/components/simulator/tours-app.tsx +105 -0
- package/src/components/webhook-endpoints-card.tsx +172 -0
- package/src/core/abilities.ts +459 -0
- package/src/core/agreements.ts +139 -0
- package/src/core/gates.ts +157 -0
- package/src/core/greeting.ts +11 -0
- package/src/core/inbound-email.ts +129 -0
- package/src/core/jobs.ts +51 -0
- package/src/core/keyset.ts +227 -0
- package/src/core/llm-models.ts +10 -0
- package/src/core/locale.ts +3 -0
- package/src/core/notifications.ts +182 -0
- package/src/core/presets.ts +456 -0
- package/src/core/roles.ts +47 -0
- package/src/core/schedules.ts +147 -0
- package/src/core/standard-schema.ts +56 -0
- package/src/core/state-machine.ts +43 -0
- package/src/core/webhook-events.ts +86 -0
- package/src/core/webhook-hmac.ts +248 -0
- package/src/core/webhook-signing.ts +27 -0
- package/src/cutover/rows.json +101 -0
- package/src/db/agreements.ts +176 -0
- package/src/db/app-roles.ts +197 -0
- package/src/db/audit.ts +356 -0
- package/src/db/inbound-email.ts +145 -0
- package/src/db/jobs.ts +300 -0
- package/src/db/jsonb.ts +18 -0
- package/src/db/keyset.ts +179 -0
- package/src/db/migrate.ts +73 -0
- package/src/db/migrations/0001_tenants.ts +25 -0
- package/src/db/migrations/0003_organizations.ts +27 -0
- package/src/db/migrations/0004_jobs.ts +64 -0
- package/src/db/migrations/0005_service_keys.ts +33 -0
- package/src/db/migrations/0008_audit_events.ts +51 -0
- package/src/db/migrations/0009_job_schedules.ts +52 -0
- package/src/db/migrations/0010_webhooks.ts +100 -0
- package/src/db/migrations/0011_notifications.ts +98 -0
- package/src/db/migrations/0012_inbound_email.ts +74 -0
- package/src/db/migrations/0013_agreements.ts +98 -0
- package/src/db/migrations/0014_audit_credential.ts +29 -0
- package/src/db/migrations/0015_app_user_grant.ts +67 -0
- package/src/db/migrations/0016_audit_detail.ts +26 -0
- package/src/db/migrations/index.ts +49 -0
- package/src/db/notifications.ts +185 -0
- package/src/db/org-lookup.ts +104 -0
- package/src/db/owner-pass.ts +252 -0
- package/src/db/rls-coverage.ts +259 -0
- package/src/db/rls-proof-runner.ts +94 -0
- package/src/db/rls-proofs.ts +1176 -0
- package/src/db/schedules.ts +187 -0
- package/src/db/schema.ts +235 -0
- package/src/db/seed.ts +176 -0
- package/src/db/service-keys.ts +50 -0
- package/src/db/tenant-lookup.ts +13 -0
- package/src/db/webhooks.ts +483 -0
- package/src/db/with-tenant.ts +26 -0
- package/src/demo-static/actor-drivers.ts +161 -0
- package/src/demo-static/assistant-replay.ts +61 -0
- package/src/demo-static/contracts.ts +282 -0
- package/src/demo-static/email-html.ts +58 -0
- package/src/demo-static/hash-route.ts +24 -0
- package/src/demo-static/rows.ts +105 -0
- package/src/demo-static/shell.tsx +440 -0
- package/src/demo-static/tour/contracts.ts +97 -0
- package/src/demo-static/tour/driver.ts +320 -0
- package/src/demo-static/tour/tour-overlay.tsx +226 -0
- package/src/demo-static/tour/use-tours.tsx +394 -0
- package/src/demo-static/world.ts +1479 -0
- package/src/email/send.ts +12 -0
- package/src/email/templates/digest-email.tsx +61 -0
- package/src/email/templates/invite-email.tsx +57 -0
- package/src/email/templates/notification-email.tsx +39 -0
- package/src/guide.md +118 -0
- package/src/i18n/messages/en.json +373 -0
- package/src/i18n/messages/es.json +373 -0
- package/src/i18n/messages.ts +34 -0
- package/src/i18n/namespaces.ts +32 -0
- package/src/i18n/request.ts +34 -0
- package/src/i18n/routing.ts +7 -0
- package/src/inbound-email/handlers.ts +67 -0
- package/src/inbound-email/intake.ts +180 -0
- package/src/jobs/digest-email.ts +97 -0
- package/src/observability/scrub.ts +42 -0
- package/src/ports/README.md +8 -0
- package/src/ports/analytics.ts +8 -0
- package/src/ports/auth.ts +87 -0
- package/src/ports/db.ts +27 -0
- package/src/ports/email.ts +14 -0
- package/src/ports/errors.ts +46 -0
- package/src/ports/jobs.ts +48 -0
- package/src/ports/llm.ts +85 -0
- package/src/ports/storage.ts +132 -0
- package/src/seed/contracts.ts +129 -0
- package/src/server-lib/assistant.ts +45 -0
- package/src/server-lib/defer.ts +53 -0
- package/src/server-lib/demo-presets.ts +85 -0
- package/src/server-lib/invite.ts +92 -0
- package/src/server-lib/notify-deps.ts +15 -0
- package/src/server-lib/notify.ts +252 -0
- package/src/server-lib/preset-operations.ts +121 -0
- package/src/server-lib/scheduled-tick.ts +38 -0
- package/src/server-lib/sms.ts +43 -0
- package/src/server-lib/webhook-dispatch.ts +75 -0
- package/src/service-auth/mailgun.ts +70 -0
- package/src/service-auth/verify.ts +73 -0
- package/src/service-auth/webhook.ts +60 -0
- package/src/testing/checks.json +103 -0
- package/src/testing/conformance/authz.ts +46 -0
- package/src/testing/conformance/db.ts +258 -0
- package/src/testing/conformance/demo-presets.ts +295 -0
- package/src/testing/conformance/i18n.ts +80 -0
- package/src/testing/conformance/register.ts +200 -0
- package/src/testing/conformance/seam-map.ts +205 -0
- package/src/testing/conformance/suite.ts +59 -0
- package/src/testing/conformance/types.ts +18 -0
- package/src/testing/contract.ts +200 -0
- package/src/testing/e2e.ts +15 -0
- package/src/testing/index.ts +6 -0
- package/src/testing/seam-specifiers.json +22 -0
- package/src/testing/tmp-dir-marker.d.mts +4 -0
- package/src/testing/tmp-dir-marker.mjs +5 -0
- package/src/testing/tmp-dir.ts +182 -0
- package/src/theme.ts +28 -0
- package/README.md +0 -3
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type * as Sentry from '@sentry/nextjs'
|
|
2
|
+
|
|
3
|
+
type InitOptions = NonNullable<Parameters<typeof Sentry.init>[0]>
|
|
4
|
+
type Integration = { name: string }
|
|
5
|
+
|
|
6
|
+
/** 10.78's `PII_HEADER_SNIPPETS` (`@sentry/core`), the denylist its `sendDefaultPii`-off mapping used. */
|
|
7
|
+
const V10_DENIED_KEYS = ['forwarded', '-ip', 'remote-', 'via', '-user']
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The default integrations 10.78 installed, by `name`, on the three runtimes `@sentry/nextjs` inits: Node
|
|
11
|
+
* (`@sentry/node` `getDefaultIntegrations` with tracing on), edge (`@sentry/vercel-edge`) and the browser
|
|
12
|
+
* (`@sentry/browser`), plus what nextjs's own inits pushed: `DistDirRewriteFrames` (server and edge), and
|
|
13
|
+
* `BrowserTracing` and `NextjsClientStackFrameNormalization` (browser).
|
|
14
|
+
*/
|
|
15
|
+
const V10_DEFAULT_INTEGRATIONS = [
|
|
16
|
+
// Node
|
|
17
|
+
...['Amqplib', 'Anthropic_AI', 'ChildProcess', 'Connect', 'Console', 'Context', 'ContextLines'],
|
|
18
|
+
...['ConversationId', 'Express', 'Fastify', 'Firebase', 'FunctionToString', 'GenericPool', 'Google_GenAI'],
|
|
19
|
+
...['Graphql', 'Hapi', 'Hono', 'Http', 'InboundFilters', 'Kafka', 'Koa', 'LangChain', 'LangGraph'],
|
|
20
|
+
...['LinkedErrors', 'LocalVariablesAsync', 'LruMemoizer', 'Modules', 'Mongo', 'Mongoose', 'Mysql', 'Mysql2'],
|
|
21
|
+
...['NodeFetch', 'NodeSystemError', 'OnUncaughtException', 'OnUnhandledRejection', 'OpenAI', 'Postgres'],
|
|
22
|
+
...['PostgresJs', 'Prisma', 'ProcessSession', 'Redis', 'RequestData', 'Tedious', 'VercelAI'],
|
|
23
|
+
'DistDirRewriteFrames',
|
|
24
|
+
// Edge, beyond the Node names
|
|
25
|
+
...['Dedupe', 'WinterCGFetch'],
|
|
26
|
+
// Browser, beyond the names above
|
|
27
|
+
...['Breadcrumbs', 'BrowserApiErrors', 'BrowserSession', 'CultureContext', 'GlobalHandlers', 'HttpContext'],
|
|
28
|
+
...['BrowserTracing', 'NextjsClientStackFrameNormalization'],
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 11.x successors to a 10.78 default: `EventFilters` is `InboundFilters` renamed, and `WorkerThreads` is the
|
|
33
|
+
* worker-thread half of v10's `ChildProcess`. (The browser's new `Console` is the console-breadcrumb half of
|
|
34
|
+
* `Breadcrumbs` and keeps the name Node already had.)
|
|
35
|
+
*/
|
|
36
|
+
const V11_SUCCESSORS = ['EventFilters', 'WorkerThreads']
|
|
37
|
+
|
|
38
|
+
const ALLOWED_DEFAULT_INTEGRATIONS = new Set([...V10_DEFAULT_INTEGRATIONS, ...V11_SUCCESSORS])
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* An ALLOWLIST, so a default integration that 11.x (or any later 11.x) adds is dropped until someone decides
|
|
42
|
+
* otherwise. 11.12 adds, on Node: `Aws` (a span per AWS SDK command, with S3 bucket names and Secrets Manager
|
|
43
|
+
* ARNs), `AwsLambdaWeb` (Lambda context), `Dataloader` (cache keys verbatim), `Knex`, `Neon`, `Nitro`,
|
|
44
|
+
* `Mastra`, `PiDurable`, `McpServer` and four AI clients (`Groq`, `Mistral`, `TogetherAI`, `TypeSafe`); and on the
|
|
45
|
+
* Next.js server, `NextjsUseCache` (`'use cache'` tags verbatim). Several of them attach metadata that no
|
|
46
|
+
* `dataCollection` key gates; the rest are dropped too, because an allowlist does not judge.
|
|
47
|
+
* `default-integrations.test.ts` lists what this drops from the installed SDK's real defaults.
|
|
48
|
+
*/
|
|
49
|
+
function withV10DefaultsOnly<T extends Integration>(defaults: T[]): T[] {
|
|
50
|
+
return defaults.filter((integration) => ALLOWED_DEFAULT_INTEGRATIONS.has(integration.name))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* What the SDK may collect, held at or below what v10 collected with `sendDefaultPii` unset (ADR-0010, addendum
|
|
55
|
+
* 2026-11-17). v11 replaced `sendDefaultPii` with `dataCollection`, and an UNSET `dataCollection` now
|
|
56
|
+
* collects user info, cookies, HTTP bodies, database query data, queue arguments and GenAI/MCP payloads. From
|
|
57
|
+
* a multi-tenant framework that is tenant data, so every `dataCollection` key is set here and none is left to a
|
|
58
|
+
* default.
|
|
59
|
+
*
|
|
60
|
+
* Starts from the migration guide's "keep the v10 default behavior" block, which is stricter than 10.78's own
|
|
61
|
+
* unset mapping (`defaultPiiToCollectionOptions(false)` in `@sentry/core` 10.78) on `cookies` and `graphQL`, and in
|
|
62
|
+
* practice on `httpBodies` (10.78's Node HTTP integration attached incoming request bodies to error events
|
|
63
|
+
* regardless), and adds what that block leaves to a default:
|
|
64
|
+
* - `mcp`: 11.x resolves an omitted `mcp` to `{ inputs: true, outputs: true }` (`resolveDataCollectionOptions`).
|
|
65
|
+
* - `stackFrameVariables: false`: capture also needs `includeLocalVariables`, unset here, so this only pins it.
|
|
66
|
+
* - `frameContextLines: 5`: the 11.x default, fewer than v10's 7.
|
|
67
|
+
* - `attachStacktrace: false`: v10's default; v11 turned it on, which adds a synthetic stack trace with source
|
|
68
|
+
* context to `captureMessage` events.
|
|
69
|
+
* - `integrations`: keeps only the default integrations v10 had (or their renamed successors), above.
|
|
70
|
+
*
|
|
71
|
+
* Widening any of this is a privacy decision, not a dependency chore: `baseline.test.ts` pins it.
|
|
72
|
+
*/
|
|
73
|
+
export const SENTRY_V10_BASELINE = {
|
|
74
|
+
attachStacktrace: false,
|
|
75
|
+
integrations: withV10DefaultsOnly,
|
|
76
|
+
dataCollection: {
|
|
77
|
+
userInfo: false,
|
|
78
|
+
cookies: false,
|
|
79
|
+
httpHeaders: { request: { deny: V10_DENIED_KEYS }, response: { deny: V10_DENIED_KEYS } },
|
|
80
|
+
httpBodies: [],
|
|
81
|
+
urlQueryParams: { deny: V10_DENIED_KEYS },
|
|
82
|
+
genAI: { inputs: false, outputs: false },
|
|
83
|
+
mcp: { inputs: false, outputs: false },
|
|
84
|
+
databaseQueryData: false,
|
|
85
|
+
queues: false,
|
|
86
|
+
graphQL: { document: false, variables: false },
|
|
87
|
+
stackFrameVariables: false,
|
|
88
|
+
frameContextLines: 5,
|
|
89
|
+
},
|
|
90
|
+
} satisfies Pick<InitOptions, 'attachStacktrace' | 'dataCollection' | 'integrations'>
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import * as Sentry from '@sentry/nextjs'
|
|
2
|
+
import { scrubEvent } from '../../observability/scrub'
|
|
3
|
+
import { SENTRY_V10_BASELINE } from './baseline'
|
|
4
|
+
|
|
5
|
+
/** Browser Sentry init (ADR-0010) — dynamically imported only when a DSN is configured. */
|
|
6
|
+
export function initClientSentry(): void {
|
|
7
|
+
Sentry.init({
|
|
8
|
+
dsn: (process.env as { NEXT_PUBLIC_SENTRY_DSN?: string }).NEXT_PUBLIC_SENTRY_DSN,
|
|
9
|
+
tracesSampleRate: 0.1,
|
|
10
|
+
...SENTRY_V10_BASELINE,
|
|
11
|
+
beforeSend: (event) => scrubEvent(event),
|
|
12
|
+
})
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function forwardRouterTransition(href: string, navigationType: string): void {
|
|
16
|
+
Sentry.captureRouterTransitionStart(href, navigationType)
|
|
17
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import * as Sentry from '@sentry/nextjs'
|
|
2
|
+
import { scrubEvent } from '../../observability/scrub'
|
|
3
|
+
import { SENTRY_V10_BASELINE } from './baseline'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Server/edge Sentry init (ADR-0010). Loaded ONLY when a DSN is configured (cutover row
|
|
7
|
+
* `errors`) — importing @sentry/nextjs at all pulls OpenTelemetry hooks into every request, so
|
|
8
|
+
* src/instrumentation.ts gates the dynamic import on the DSN.
|
|
9
|
+
*/
|
|
10
|
+
export function initServerSentry(): void {
|
|
11
|
+
Sentry.init({
|
|
12
|
+
dsn: (process.env as { NEXT_PUBLIC_SENTRY_DSN?: string }).NEXT_PUBLIC_SENTRY_DSN,
|
|
13
|
+
tracesSampleRate: 0.1,
|
|
14
|
+
...SENTRY_V10_BASELINE,
|
|
15
|
+
beforeSend: (event) => scrubEvent(event),
|
|
16
|
+
})
|
|
17
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { FRAMEWORK_POLICY, isGate } from './route-policy'
|
|
5
|
+
import { type Exemption, type ScannedRoute, type ScanRoot, type ScanPolicy, judge, scanRoutes } from './route-scan'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* AN APP'S OWN AUTHORIZATION EXEMPTIONS, and the per-app authorization scan that applies them (the conformance
|
|
9
|
+
* suite's `authz-mutations` check, `@sssb/kit/testing`).
|
|
10
|
+
*
|
|
11
|
+
* The framework's exemption map (./route-policy.ts) is the kit's, and an adopter cannot edit it. A route the app
|
|
12
|
+
* owns that is genuinely not a per-actor product mutation is named in the app's own `authz-exemptions.mjs`, beside
|
|
13
|
+
* its `package.json`, the way `lint-exceptions.mjs` names the app's lint exceptions (ADR-0014 part 3):
|
|
14
|
+
*
|
|
15
|
+
* export default {
|
|
16
|
+
* files: { 'partner/ping/route.ts': { reason: '…', mustMatch: { kind: 'calls', callees: ['partner.ping'] } } },
|
|
17
|
+
* prefixes: { 'hooks/': { reason: '…', mustMatch: { kind: 'wrapped-by', callees: ['withPartnerSignature'] } } },
|
|
18
|
+
* }
|
|
19
|
+
*
|
|
20
|
+
* Keys are paths relative to the app's `src/app/api`, as the framework's are: `files` names one route file,
|
|
21
|
+
* `prefixes` a directory ending in `/`. Each entry carries a non-empty `reason` and a checkable `mustMatch` gate
|
|
22
|
+
* (./route-scan.ts, `Gate`), for the same reason the framework's do: a gateless entry exempts that path outright.
|
|
23
|
+
* An entry FAILS (and is not applied) when it is malformed, when it overlaps a framework entry (same key, under one
|
|
24
|
+
* of the framework's prefixes, or a prefix over one of its keys — an app cannot weaken a framework gate, the
|
|
25
|
+
* `service/` gate above all), when it is a prefix nested in another of the app's prefixes (both fail: a route under
|
|
26
|
+
* both would get one gate and silently lose the other), or when it matches no mutating route in the app's own tree: an app exemption is
|
|
27
|
+
* measured against the app, so a deleted route's exemption cannot wait for a new route at the same path.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** The file, beside the app's `package.json`. */
|
|
31
|
+
export const APP_EXEMPTIONS_FILE = 'authz-exemptions.mjs'
|
|
32
|
+
|
|
33
|
+
export interface AppExemptions {
|
|
34
|
+
files: Record<string, Exemption>
|
|
35
|
+
prefixes: Record<string, Exemption>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const KEYS = ['files', 'prefixes'] as const
|
|
39
|
+
const ROUTE_FILE = /(?:^|\/)route\.(?:mjs|[jt]sx?)$/
|
|
40
|
+
const GLOB = /[*?[\]{}]/
|
|
41
|
+
|
|
42
|
+
/** Two keys overlap when they are equal or one is a prefix (`…/`) the other sits under. */
|
|
43
|
+
function overlaps(a: string, b: string): boolean {
|
|
44
|
+
return a === b || (a.endsWith('/') && b.startsWith(a)) || (b.endsWith('/') && a.startsWith(b))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Validates a loaded `authz-exemptions.mjs` default export. Returns the entries that are well formed and do not
|
|
49
|
+
* collide with the framework's policy, and a problem for every one that is not. `label` names the file in messages.
|
|
50
|
+
*/
|
|
51
|
+
export function appExemptionsFrom(value: unknown, label: string): { exemptions: AppExemptions; problems: string[] } {
|
|
52
|
+
const exemptions: AppExemptions = { files: {}, prefixes: {} }
|
|
53
|
+
const problems: string[] = []
|
|
54
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
55
|
+
problems.push(`${label}: its default export must be an object with \`files\` and/or \`prefixes\``)
|
|
56
|
+
return { exemptions, problems }
|
|
57
|
+
}
|
|
58
|
+
const frameworkKeys = [
|
|
59
|
+
...Object.keys(FRAMEWORK_POLICY.exemptFiles),
|
|
60
|
+
...Object.keys(FRAMEWORK_POLICY.exemptPrefixes),
|
|
61
|
+
...Object.keys(FRAMEWORK_POLICY.requiredAlongside),
|
|
62
|
+
]
|
|
63
|
+
for (const [key, entries] of Object.entries(value)) {
|
|
64
|
+
if (!(KEYS as readonly string[]).includes(key)) {
|
|
65
|
+
problems.push(`${label}: unknown key \`${key}\` (only ${KEYS.map((k) => `\`${k}\``).join(' and ')})`)
|
|
66
|
+
continue
|
|
67
|
+
}
|
|
68
|
+
if (typeof entries !== 'object' || entries === null || Array.isArray(entries)) {
|
|
69
|
+
problems.push(`${label}: \`${key}\` must map a path to { reason, mustMatch }`)
|
|
70
|
+
continue
|
|
71
|
+
}
|
|
72
|
+
const prefix = key === 'prefixes'
|
|
73
|
+
for (const [rel, entry] of Object.entries(entries as Record<string, unknown>)) {
|
|
74
|
+
const where = `${label}: ${key} \`${rel}\``
|
|
75
|
+
if (
|
|
76
|
+
rel === '' ||
|
|
77
|
+
rel.startsWith('/') ||
|
|
78
|
+
rel.includes('\\') ||
|
|
79
|
+
rel.split('/').includes('..') ||
|
|
80
|
+
GLOB.test(rel)
|
|
81
|
+
) {
|
|
82
|
+
problems.push(
|
|
83
|
+
`${where} must be a literal path relative to the app's src/app/api, with / separators (no glob)`,
|
|
84
|
+
)
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
if (prefix && !rel.endsWith('/')) {
|
|
88
|
+
problems.push(`${where} is a prefix, so it must end with /`)
|
|
89
|
+
continue
|
|
90
|
+
}
|
|
91
|
+
if (!prefix && !ROUTE_FILE.test(rel)) {
|
|
92
|
+
problems.push(`${where} must name one route file (route.ts, route.tsx, route.js, route.jsx, route.mjs)`)
|
|
93
|
+
continue
|
|
94
|
+
}
|
|
95
|
+
const { reason, mustMatch } = (entry ?? {}) as { reason?: unknown; mustMatch?: unknown }
|
|
96
|
+
if (typeof reason !== 'string' || reason.trim() === '') {
|
|
97
|
+
problems.push(`${where} needs a non-empty reason`)
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
if (!isGate(mustMatch)) {
|
|
101
|
+
problems.push(
|
|
102
|
+
`${where} has no checkable mustMatch gate — a bare exemption exempts that path outright. ` +
|
|
103
|
+
'Name the gate the reason rests on (wrapped-by, calls or opens-with-simulated-404).',
|
|
104
|
+
)
|
|
105
|
+
continue
|
|
106
|
+
}
|
|
107
|
+
const collision = frameworkKeys.find((framework) => overlaps(rel, framework))
|
|
108
|
+
if (collision !== undefined) {
|
|
109
|
+
problems.push(
|
|
110
|
+
`${where} overlaps the framework's own entry \`${collision}\`; an app cannot replace or widen a ` +
|
|
111
|
+
'framework exemption or gate',
|
|
112
|
+
)
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
;(prefix ? exemptions.prefixes : exemptions.files)[rel] = { reason, mustMatch }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// Nested prefixes (`hooks/` and `hooks/partner/`) would leave the route under both to whichever the scan meets
|
|
119
|
+
// first, silently dropping the other's gate. Neither is applied: the app names one prefix per subtree.
|
|
120
|
+
const appPrefixes = Object.keys(exemptions.prefixes)
|
|
121
|
+
const nested = appPrefixes
|
|
122
|
+
.map((rel) => ({ rel, others: appPrefixes.filter((other) => other !== rel && overlaps(rel, other)) }))
|
|
123
|
+
.filter(({ others }) => others.length > 0)
|
|
124
|
+
for (const { rel, others } of nested) {
|
|
125
|
+
problems.push(
|
|
126
|
+
`${label}: prefixes \`${rel}\` overlaps the app's own prefix ${others.map((o) => `\`${o}\``).join(', ')}; ` +
|
|
127
|
+
'a route under both would get only one of their gates, so neither applies. Use one prefix per ' +
|
|
128
|
+
'subtree, or name the inner routes in `files` (an exact entry wins over a prefix).',
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
for (const { rel } of nested) delete exemptions.prefixes[rel]
|
|
132
|
+
return { exemptions, problems }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Reads `<appDir>/authz-exemptions.mjs`, if the app has one. A file that does not load is a problem, not a throw. */
|
|
136
|
+
async function readAppExemptions(appDir: string): Promise<{ exemptions: AppExemptions; problems: string[] }> {
|
|
137
|
+
const file = path.join(appDir, APP_EXEMPTIONS_FILE)
|
|
138
|
+
const label = `${path.basename(appDir)}/${APP_EXEMPTIONS_FILE}`
|
|
139
|
+
if (!existsSync(file)) return { exemptions: { files: {}, prefixes: {} }, problems: [] }
|
|
140
|
+
let loaded: { default?: unknown }
|
|
141
|
+
try {
|
|
142
|
+
// Node's own loader, not the test runner's: under a browser-like test environment (happy-dom) Vite reads an
|
|
143
|
+
// absolute path as a URL under the project root, and a file URL not at all. `require` of an ES module is
|
|
144
|
+
// Node's since 22.12; the file is plain JavaScript, as `lint-exceptions.mjs` is.
|
|
145
|
+
loaded = createRequire(file)(file) as { default?: unknown }
|
|
146
|
+
} catch (error) {
|
|
147
|
+
return {
|
|
148
|
+
exemptions: { files: {}, prefixes: {} },
|
|
149
|
+
problems: [`${label}: does not load: ${error instanceof Error ? error.message : String(error)}`],
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return appExemptionsFrom(loaded.default, label)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The framework's policy plus an app's (already validated, collision-free) exemptions. */
|
|
156
|
+
function policyWithApp(app: AppExemptions): ScanPolicy {
|
|
157
|
+
return {
|
|
158
|
+
...FRAMEWORK_POLICY,
|
|
159
|
+
exemptPrefixes: { ...FRAMEWORK_POLICY.exemptPrefixes, ...app.prefixes },
|
|
160
|
+
exemptFiles: { ...FRAMEWORK_POLICY.exemptFiles, ...app.files },
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** App exemptions that match no mutating route in the app's own tree (`mutatingRels`, relative to its `src/app/api`). */
|
|
165
|
+
function staleAppExemptions(app: AppExemptions, mutatingRels: readonly string[], label: string): string[] {
|
|
166
|
+
return [
|
|
167
|
+
...Object.keys(app.files)
|
|
168
|
+
.filter((rel) => !mutatingRels.includes(rel))
|
|
169
|
+
.map((rel) => `${label}: files \`${rel}\` is stale — the app's src/app/api has no mutating route there`),
|
|
170
|
+
...Object.keys(app.prefixes)
|
|
171
|
+
.filter((prefix) => !mutatingRels.some((rel) => rel.startsWith(prefix)))
|
|
172
|
+
.map(
|
|
173
|
+
(prefix) =>
|
|
174
|
+
`${label}: prefixes \`${prefix}\` is stale — it covers no mutating route in the app's src/app/api`,
|
|
175
|
+
),
|
|
176
|
+
]
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export interface AppScan {
|
|
180
|
+
root: ScanRoot
|
|
181
|
+
/** Every route file under the app's `src/app`, mutating or not. Empty when there is no `src/app`. */
|
|
182
|
+
routes: ScannedRoute[]
|
|
183
|
+
/** One message per mutating handler that fails, `<root>: <rel> <VERB> …why`. */
|
|
184
|
+
failures: string[]
|
|
185
|
+
/** The app's exemptions file: malformed, colliding or stale entries. */
|
|
186
|
+
exemptionProblems: string[]
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The authorization scan over ONE app: every `route.*` under `<appDir>/src/app` (Next serves one from anywhere
|
|
191
|
+
* there, so not only `api/`), judged against the framework's policy plus the app's own exemptions, which are
|
|
192
|
+
* measured from `<appDir>/src/app/api` (so a mutating route outside `api/` can match no exemption and must call
|
|
193
|
+
* `authorize(...)` itself). Re-exported handlers are followed with the app's `tsconfig.json` (or `jsconfig.json`).
|
|
194
|
+
*/
|
|
195
|
+
export async function scanApp(appDir: string): Promise<AppScan> {
|
|
196
|
+
const name = path.basename(appDir)
|
|
197
|
+
const root: ScanRoot = {
|
|
198
|
+
label: name,
|
|
199
|
+
dir: path.join(appDir, 'src/app'),
|
|
200
|
+
exemptDir: path.join(appDir, 'src/app/api'),
|
|
201
|
+
// An app without one (a JS app's jsconfig.json, or neither) still gets scanned: relative re-exports resolve
|
|
202
|
+
// without a config, and an alias that does not resolve is refused, loudly.
|
|
203
|
+
tsconfig: ['tsconfig.json', 'jsconfig.json'].map((file) => path.join(appDir, file)).find((f) => existsSync(f)),
|
|
204
|
+
}
|
|
205
|
+
const { exemptions, problems } = await readAppExemptions(appDir)
|
|
206
|
+
const routes = existsSync(root.dir) ? scanRoutes([root]) : []
|
|
207
|
+
const mutating = routes.filter((route) => route.handlers.length > 0)
|
|
208
|
+
const policy = policyWithApp(exemptions)
|
|
209
|
+
const failures = mutating.flatMap((route) =>
|
|
210
|
+
route.handlers.flatMap((handler) => judge(route, handler, policy) ?? []),
|
|
211
|
+
)
|
|
212
|
+
const label = `${name}/${APP_EXEMPTIONS_FILE}`
|
|
213
|
+
return {
|
|
214
|
+
root,
|
|
215
|
+
routes,
|
|
216
|
+
failures,
|
|
217
|
+
exemptionProblems: [
|
|
218
|
+
...problems,
|
|
219
|
+
...staleAppExemptions(
|
|
220
|
+
exemptions,
|
|
221
|
+
mutating.map((route) => route.rel),
|
|
222
|
+
label,
|
|
223
|
+
),
|
|
224
|
+
],
|
|
225
|
+
}
|
|
226
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { anchorSubjectExtras, staffOrgSlug } from '@sssb/app-config/abilities'
|
|
2
|
+
import type { AppMachineCredentialKind } from '@sssb/app-config/abilities'
|
|
3
|
+
import {
|
|
4
|
+
type AbilityAction,
|
|
5
|
+
type AbilityActor,
|
|
6
|
+
type AbilitySubject,
|
|
7
|
+
type Actor,
|
|
8
|
+
type MachineActor,
|
|
9
|
+
type PersonCredentialKind,
|
|
10
|
+
type SubjectType,
|
|
11
|
+
defineAbilitiesFor,
|
|
12
|
+
} from '../core/abilities'
|
|
13
|
+
import type { OrgIdentity } from '../db/org-lookup'
|
|
14
|
+
import type { AuthPort, AuthUser } from '../ports/auth'
|
|
15
|
+
import { ForbiddenError } from '../ports/errors'
|
|
16
|
+
import type { ServiceIdentity } from '../service-auth/verify'
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The server-side authorization seam. Product mutation routes call {@link authorize}
|
|
20
|
+
* explicitly after they've resolved the subject's org (the id is handler-derived, so it can't be
|
|
21
|
+
* pre-wrapped as middleware). A build-time scanner (the conformance suite's `authz-mutations` check, ./app-exemptions.ts) proves every
|
|
22
|
+
* mutating route either calls authorize(...) or is a justified exemption.
|
|
23
|
+
*
|
|
24
|
+
* It judges two kinds of actor (@sssb/kit/core/abilities `Actor`), each carrying the credential it came with:
|
|
25
|
+
* - a PERSON, lifted from a session by {@link abilityActorFromUser}, or from another credential a person
|
|
26
|
+
* holds (an inbound email, a personal API token) by {@link abilityActorFromCredential};
|
|
27
|
+
* - a MACHINE, from {@link abilityActorFromService} or {@link machineActor}.
|
|
28
|
+
* Whatever the credential, the route verifies it FIRST and builds the actor from what it proved. The
|
|
29
|
+
* actor's org is the credential's, never a request field.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Lift an AuthUser into the pure ability actor. `manageAll` is derived from the ACTIVE org:
|
|
34
|
+
* acting AS the staff org (`user.orgSlug === staffOrgSlug`) is what wields the cross-org manage-all
|
|
35
|
+
* power — a clean, explicit activation with no per-request membership-list lookup, mirroring how every
|
|
36
|
+
* other power in the model is anchored to the active org. A staff-org member acting in a NON-staff org
|
|
37
|
+
* (if they had another membership) would NOT have manageAll — activation is by wielding, not by mere
|
|
38
|
+
* membership. Reads `user.orgSlug` (the active org's slug) directly, so it holds whether the caller
|
|
39
|
+
* passes a uuid activeOrgId (routes) or the slug anchor (canInActiveOrg). NEVER crosses tenants:
|
|
40
|
+
* manageAll only short-circuits the per-subject rules, which are already tenant-bounded, and every
|
|
41
|
+
* product query still runs inside withTenant — see the decision log.
|
|
42
|
+
*/
|
|
43
|
+
export function abilityActorFromUser(user: AuthUser, activeOrgId: string): AbilityActor {
|
|
44
|
+
return {
|
|
45
|
+
kind: 'person',
|
|
46
|
+
credential: { kind: 'session', id: null },
|
|
47
|
+
userId: user.id,
|
|
48
|
+
role: user.role,
|
|
49
|
+
restricted: user.restricted,
|
|
50
|
+
activeOrgId,
|
|
51
|
+
manageAll: user.orgSlug === staffOrgSlug,
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Build the PERSON actor for someone who reached the app with a credential other than a session: an
|
|
57
|
+
* inbound email from their address, a personal API token they minted. The caller's verifier has
|
|
58
|
+
* already established WHO (`userId`) and WHERE (`org`, the org the credential is bound to), and only
|
|
59
|
+
* as firmly as that credential can: a token row is cryptographic, while an email sender rests on the
|
|
60
|
+
* mail provider's SPF/DKIM checks (the residual the inbound-email handlers record). This reads the
|
|
61
|
+
* person's standing there through the auth port. It takes no role, so a role can be neither cached in
|
|
62
|
+
* the credential nor derived from it, and it reads on every call, so a person who has been removed or
|
|
63
|
+
* demoted is judged by what they are now.
|
|
64
|
+
*
|
|
65
|
+
* `org` must be ONE organizations row's id and slug (`OrgIdentity`): the standing is read by slug, the way
|
|
66
|
+
* the auth port names orgs, and applied to the id every sameOrg check compares. Get it from
|
|
67
|
+
* `orgIdentityForSlug` (@sssb/kit/db/org-lookup), or from the inbound context's `ctx.org`, never by pairing
|
|
68
|
+
* two values, and never from the request.
|
|
69
|
+
*
|
|
70
|
+
* Returns null when the person is no longer an active member of that org: their credential is dead. A
|
|
71
|
+
* route that uses this should answer 401 (throw `AuthRequiredError`); the inbound-email handlers, its
|
|
72
|
+
* only callers in this repo, file the message 'unmatched'. The actor never wields `manageAll`, even acting in the staff org; that power
|
|
73
|
+
* belongs to a session, and @sssb/kit/core/abilities enforces it whatever this field says.
|
|
74
|
+
*
|
|
75
|
+
* @throws Error (a programming error, never a 403) when handed a `session` credential: a session's
|
|
76
|
+
* person comes from {@link abilityActorFromUser}, and letting one through here would let any caller
|
|
77
|
+
* claim the session-only rules.
|
|
78
|
+
*/
|
|
79
|
+
export async function abilityActorFromCredential(
|
|
80
|
+
auth: Pick<AuthPort, 'getMember'>,
|
|
81
|
+
input: {
|
|
82
|
+
userId: string
|
|
83
|
+
org: OrgIdentity
|
|
84
|
+
credential: { kind: Exclude<PersonCredentialKind, 'session'>; id: string }
|
|
85
|
+
},
|
|
86
|
+
): Promise<AbilityActor | null> {
|
|
87
|
+
// The type excludes `session`, but an app that registered it as one of its own kinds, or a cast,
|
|
88
|
+
// would not be stopped by the type.
|
|
89
|
+
const kind: string = input.credential.kind
|
|
90
|
+
if (kind === 'session') throw new Error('abilityActorFromCredential: a session is not a credential this builds')
|
|
91
|
+
const standing = await auth.getMember(input.org.slug, input.userId)
|
|
92
|
+
if (!standing) return null
|
|
93
|
+
return {
|
|
94
|
+
kind: 'person',
|
|
95
|
+
credential: input.credential,
|
|
96
|
+
userId: input.userId,
|
|
97
|
+
role: standing.role,
|
|
98
|
+
restricted: standing.restricted,
|
|
99
|
+
activeOrgId: input.org.id,
|
|
100
|
+
manageAll: false,
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Kinds a {@link machineActor} may not claim, checked at run time because the composed kind union cannot
|
|
106
|
+
* stop an app registering one. `service-key` is SSSB's own service keys, which only
|
|
107
|
+
* {@link abilityActorFromService} builds; it is the kind the framework's one machine grant names.
|
|
108
|
+
* `session` and `inbound-email` are PERSON credentials. `system` is what SSSB's background writers
|
|
109
|
+
* record as (`system:scheduler`, `system:webhooks`, `system:inbound-email`), so a machine claiming it
|
|
110
|
+
* would be indistinguishable from them in the audit trail.
|
|
111
|
+
*/
|
|
112
|
+
const RESERVED_MACHINE_KINDS: readonly string[] = ['service-key', 'session', 'inbound-email', 'system']
|
|
113
|
+
|
|
114
|
+
/** A credential kind is a short lowercase slug: it prefixes every principal id, so it may not contain `:`. */
|
|
115
|
+
const KIND = /^[a-z][a-z0-9-]*$/
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Build a MACHINE actor for a caller the APP verified, such as a CI identity or an integration's token.
|
|
119
|
+
* Call it only with what the verifier PROVED. `kind` is one of the app's machine credential kinds
|
|
120
|
+
* (`AppMachineCredentialKind` on the seam). `id` is the machine's identity within that kind (a
|
|
121
|
+
* repository, a client id). `credentialId` names the credential it presented this time (a workflow run,
|
|
122
|
+
* a key id), never a secret. `activeOrgId` is the org that credential is bound to. A machine gets
|
|
123
|
+
* exactly what the app's `appMachineAbilityRules` grants it, and no framework power at all.
|
|
124
|
+
*
|
|
125
|
+
* Neither SSSB app registers a machine kind of its own, so only SSSB's own tests call this today
|
|
126
|
+
* (`authorize.test.ts`, with the fixture seam's `fixture-intake` kind). Its intended first consumer is
|
|
127
|
+
* an adopter's CI identity (a GitHub OIDC token from a listed repository; docs/decision-log.md,
|
|
128
|
+
* 2026-11-16). The run-time checks below are what a hand-written `MachineActor` literal would not
|
|
129
|
+
* give it.
|
|
130
|
+
*
|
|
131
|
+
* @throws Error (a programming error, so a 500 — never a 403) on a malformed or reserved kind, or an
|
|
132
|
+
* empty id or org.
|
|
133
|
+
*/
|
|
134
|
+
export function machineActor(input: {
|
|
135
|
+
kind: AppMachineCredentialKind
|
|
136
|
+
id: string
|
|
137
|
+
credentialId?: string
|
|
138
|
+
activeOrgId: string
|
|
139
|
+
}): MachineActor {
|
|
140
|
+
const { kind, id, activeOrgId } = input
|
|
141
|
+
const name: string = kind
|
|
142
|
+
if (!KIND.test(name)) throw new Error(`machineActor: kind must be a lowercase slug, got "${name}"`)
|
|
143
|
+
if (RESERVED_MACHINE_KINDS.includes(name)) throw new Error(`machineActor: kind "${name}" is reserved`)
|
|
144
|
+
if (id.length === 0) throw new Error('machineActor: id must not be empty')
|
|
145
|
+
if (activeOrgId.length === 0) throw new Error('machineActor: activeOrgId must not be empty')
|
|
146
|
+
return {
|
|
147
|
+
kind: 'machine',
|
|
148
|
+
credential: { kind, id: input.credentialId ?? null },
|
|
149
|
+
principalId: `${name}:${id}`,
|
|
150
|
+
activeOrgId,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Lift a VERIFIED service caller (SSSB's per-org RS256 keys, `verifyServiceCaller`) into a machine
|
|
156
|
+
* actor. The verifying key row IS the org, so the actor acts in exactly that org. Its principal id is
|
|
157
|
+
* `service-key:<org slug>`, which is what an audit row records for it, and its credential names the
|
|
158
|
+
* key that verified the call.
|
|
159
|
+
*/
|
|
160
|
+
export function abilityActorFromService(identity: ServiceIdentity): MachineActor {
|
|
161
|
+
return {
|
|
162
|
+
kind: 'machine',
|
|
163
|
+
credential: { kind: 'service-key', id: identity.keyId },
|
|
164
|
+
principalId: `service-key:${identity.orgSlug}`,
|
|
165
|
+
activeOrgId: identity.orgId,
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Throw ForbiddenError (→ 403 via withPortErrors) unless the actor may perform the action.
|
|
171
|
+
*
|
|
172
|
+
* Two forms, one choke point (the build-time scan matches both):
|
|
173
|
+
* - `authorize(actor, action, subject)` — any {@link Actor}: a machine, or a person who arrived with
|
|
174
|
+
* another credential (from {@link abilityActorFromCredential}).
|
|
175
|
+
* - `authorize(user, activeOrgId, action, subject)` — a signed-in person; shorthand for
|
|
176
|
+
* `authorize(abilityActorFromUser(user, activeOrgId), action, subject)`, and what every session route
|
|
177
|
+
* calls.
|
|
178
|
+
*/
|
|
179
|
+
export function authorize(actor: Actor, action: AbilityAction, subject: AbilitySubject): void
|
|
180
|
+
export function authorize(user: AuthUser, activeOrgId: string, action: AbilityAction, subject: AbilitySubject): void
|
|
181
|
+
export function authorize(
|
|
182
|
+
...args: [Actor, AbilityAction, AbilitySubject] | [AuthUser, string, AbilityAction, AbilitySubject]
|
|
183
|
+
): void {
|
|
184
|
+
const [actor, action, subject] =
|
|
185
|
+
args.length === 4 ? ([abilityActorFromUser(args[0], args[1]), args[2], args[3]] as const) : args
|
|
186
|
+
if (!defineAbilitiesFor(actor).can(action, subject)) {
|
|
187
|
+
throw new ForbiddenError(`cannot ${action} ${subject.type}`)
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Non-throwing UI/read gate. Anchors BOTH the actor's active org and the subject's org to the
|
|
193
|
+
* session's active-org token, so create/manage checks need no uuid lookup: sameOrg only compares
|
|
194
|
+
* the two for equality, so any stable per-session token (the org slug) satisfies it. Use this to
|
|
195
|
+
* reflect ability in the UI (e.g. disable the app's create form for restricted members).
|
|
196
|
+
*
|
|
197
|
+
* For a TWO-SIDED subject — one whose seam-registered fields name a requester org and a responder org
|
|
198
|
+
* rather than a single `orgId` — the same anchor stands in for both sides, so a create-gate reads as
|
|
199
|
+
* "am I the requester" and an update-gate as "am I the responder" against my own active org — enough
|
|
200
|
+
* to decide whether to render the create form / the accept-reject controls. This is a UI gate ONLY;
|
|
201
|
+
* server enforcement (authorize) uses the request row's REAL org ids, never this slug anchor.
|
|
202
|
+
*/
|
|
203
|
+
export function canInActiveOrg(user: AuthUser, action: AbilityAction, type: SubjectType): boolean {
|
|
204
|
+
const anchor = user.orgSlug
|
|
205
|
+
const ability = defineAbilitiesFor(abilityActorFromUser(user, anchor))
|
|
206
|
+
return ability.can(action, {
|
|
207
|
+
type,
|
|
208
|
+
orgId: anchor,
|
|
209
|
+
ownerId: user.id,
|
|
210
|
+
// App-subject anchor extras (the two-sided request sides) come from the seam so this framework
|
|
211
|
+
// gate never hard-codes app-subject fields (ADR-0012).
|
|
212
|
+
...anchorSubjectExtras(anchor),
|
|
213
|
+
})
|
|
214
|
+
}
|