@sssb/kit 0.0.0 → 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 -5
- 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,139 @@
|
|
|
1
|
+
import type { Gate, GateBehavior, GateFacts, GateScope } from './gates'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Agreements / clickwrap — the WORKED EXAMPLE that plugs into the gate seam (./gates.ts).
|
|
5
|
+
* PURE TypeScript (ADR-0006): the version/acceptance arithmetic and the agreement→gate bridge live
|
|
6
|
+
* here, shared verbatim by the server (packages/kit/src/db/agreements.ts assembles the rows) and the static-demo
|
|
7
|
+
* twin. The reusable thing is the GATE (./gates.ts); agreements are one rider of it, with their
|
|
8
|
+
* gating behavior carried as DATA on each agreement row (block-all / advisory) rather than in code.
|
|
9
|
+
*
|
|
10
|
+
* TENANT-scoped, deliberately: an agreement (the site's Terms of Service / privacy notice) applies to
|
|
11
|
+
* EVERYONE in the tenant, not per-team — so unlike the org-scoped default (jobs, job_schedules, an
|
|
12
|
+
* app’s own product tables) these rows are keyed to the tenant only. See migration 0013 and the
|
|
13
|
+
* decision log for that deviation.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export type AgreementKind = 'tos' | 'privacy' | 'custom'
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* How an agreement gates when the actor hasn't accepted the current version.
|
|
20
|
+
*
|
|
21
|
+
* - 'block-all' — a hard block across the whole protected area (interstitial). Maps to a gate with
|
|
22
|
+
* behavior 'block', scope 'all'.
|
|
23
|
+
* - 'advisory' — a dismissible banner; the actor may proceed. Maps to behavior 'advisory'.
|
|
24
|
+
*
|
|
25
|
+
* FUTURE 'block-actions' (an action-scoped block — read allowed, writes blocked) is intentionally NOT
|
|
26
|
+
* a value here: it needs the action-scoped gate seam that ./gates.ts documents but does not build in
|
|
27
|
+
* v1. Add it with that rider, not speculatively.
|
|
28
|
+
*/
|
|
29
|
+
export type AgreementGating = 'block-all' | 'advisory'
|
|
30
|
+
|
|
31
|
+
/** A current agreement version (the world state). `bodyMd` is the agreement text — markdown, rendered
|
|
32
|
+
* simply; it is world CONTENT (like a note body), not UI chrome, so it is NOT an i18n key. */
|
|
33
|
+
export interface AgreementView {
|
|
34
|
+
id: string
|
|
35
|
+
kind: AgreementKind
|
|
36
|
+
version: number
|
|
37
|
+
title: string
|
|
38
|
+
bodyMd: string
|
|
39
|
+
gating: AgreementGating
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One acceptance record: the actor accepted `agreementId` AT `version` (the version is denormalized
|
|
43
|
+
* onto the acceptance so it survives later edits to the agreement — an old acceptance stays truthful
|
|
44
|
+
* about which version was agreed to). */
|
|
45
|
+
export interface AcceptanceView {
|
|
46
|
+
agreementId: string
|
|
47
|
+
version: number
|
|
48
|
+
acceptedAt: string
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A current agreement the actor still owes — never accepted, or accepted at an older version. Carries
|
|
52
|
+
* the full content so the interstitial/banner can render without a second lookup. */
|
|
53
|
+
export interface PendingAgreement {
|
|
54
|
+
id: string
|
|
55
|
+
kind: AgreementKind
|
|
56
|
+
version: number
|
|
57
|
+
title: string
|
|
58
|
+
bodyMd: string
|
|
59
|
+
gating: AgreementGating
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The pending agreements for one actor: for each CURRENT agreement, the actor owes it when they have
|
|
64
|
+
* no acceptance for it, OR their highest accepted version is BELOW the current version (a version bump
|
|
65
|
+
* re-arms the gate for everyone — the demo story). Order is preserved from `current`.
|
|
66
|
+
*
|
|
67
|
+
* Pure and side-effect-free — the same computation runs in the server data path and the twin. No
|
|
68
|
+
* agreements at all ⇒ empty ⇒ no gates (the "clean world" case the tests pin).
|
|
69
|
+
*/
|
|
70
|
+
export function computePendingAgreements(current: AgreementView[], acceptances: AcceptanceView[]): PendingAgreement[] {
|
|
71
|
+
// Highest accepted version per agreement id (an actor may have multiple acceptance rows across
|
|
72
|
+
// version bumps; the max is what counts).
|
|
73
|
+
const acceptedVersion = new Map<string, number>()
|
|
74
|
+
for (const acceptance of acceptances) {
|
|
75
|
+
const prior = acceptedVersion.get(acceptance.agreementId) ?? -Infinity
|
|
76
|
+
if (acceptance.version > prior) acceptedVersion.set(acceptance.agreementId, acceptance.version)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return current
|
|
80
|
+
.filter((agreement) => (acceptedVersion.get(agreement.id) ?? -Infinity) < agreement.version)
|
|
81
|
+
.map((agreement) => ({
|
|
82
|
+
id: agreement.id,
|
|
83
|
+
kind: agreement.kind,
|
|
84
|
+
version: agreement.version,
|
|
85
|
+
title: agreement.title,
|
|
86
|
+
bodyMd: agreement.bodyMd,
|
|
87
|
+
gating: agreement.gating,
|
|
88
|
+
}))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Bridge the agreements domain onto the generic gate seam: turn the CURRENT agreements (the world's
|
|
93
|
+
* universe of agreements) into the registry of gates evaluateGates expects. One gate per agreement;
|
|
94
|
+
* behavior derives from its gating; each gate's `pending` predicate is "is my agreement id in the
|
|
95
|
+
* actor's pending set" (read from GateFacts.pendingAgreementIds). scope is always 'all' in v1.
|
|
96
|
+
*
|
|
97
|
+
* This is the ONLY place agreements know about gates — the layout consumes the generic PendingGate
|
|
98
|
+
* shape, so a future rider registers its own gates the same way with no layout change.
|
|
99
|
+
*/
|
|
100
|
+
export function gatesForAgreements(current: AgreementView[]): Gate[] {
|
|
101
|
+
// v1 agreements are always area-wide ('all'); their block/advisory behavior comes from the row's
|
|
102
|
+
// `gating`. Typing these against the seam's vocabulary keeps the mapping honest.
|
|
103
|
+
const scope: GateScope = 'all'
|
|
104
|
+
return current.map((agreement): Gate => {
|
|
105
|
+
const behavior: GateBehavior = agreement.gating === 'advisory' ? 'advisory' : 'block'
|
|
106
|
+
return {
|
|
107
|
+
id: `agreement:${agreement.id}`,
|
|
108
|
+
scope,
|
|
109
|
+
behavior,
|
|
110
|
+
resolutionPath: '/agreements',
|
|
111
|
+
pending: (facts: GateFacts) => (facts.pendingAgreementIds ?? []).includes(agreement.id),
|
|
112
|
+
}
|
|
113
|
+
})
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Assemble the GateFacts an actor's pending agreements imply — the plain object the server hands to
|
|
117
|
+
* evaluateGates. Shared by server + twin so both feed the seam identically. */
|
|
118
|
+
export function agreementFacts(pending: PendingAgreement[]): GateFacts {
|
|
119
|
+
return { pendingAgreementIds: pending.map((agreement) => agreement.id) }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Recover the PendingAgreement a gate id refers to (the layout maps a pending BLOCK gate back to its
|
|
123
|
+
* agreement content for the interstitial). Returns undefined if the id isn't an agreement gate. */
|
|
124
|
+
export function pendingAgreementForGateId(gateId: string, pending: PendingAgreement[]): PendingAgreement | undefined {
|
|
125
|
+
const prefix = 'agreement:'
|
|
126
|
+
if (!gateId.startsWith(prefix)) return undefined
|
|
127
|
+
const agreementId = gateId.slice(prefix.length)
|
|
128
|
+
return pending.find((agreement) => agreement.id === agreementId)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Narrow an arbitrary string to a known AgreementKind (DB `kind` is text; validate at the boundary). */
|
|
132
|
+
export function isAgreementKind(value: string): value is AgreementKind {
|
|
133
|
+
return value === 'tos' || value === 'privacy' || value === 'custom'
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Narrow an arbitrary string to a known AgreementGating (DB `gating` is text; validate at the boundary). */
|
|
137
|
+
export function isAgreementGating(value: string): value is AgreementGating {
|
|
138
|
+
return value === 'block-all' || value === 'advisory'
|
|
139
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The access-gate seam — the reusable CLASS this slice exists to teach. PURE TypeScript
|
|
3
|
+
* (ADR-0006, lint-enforced): no framework imports, shared verbatim by the server wiring
|
|
4
|
+
* (src/app/[locale]/(protected)/layout.tsx) and the static-demo twin.
|
|
5
|
+
*
|
|
6
|
+
* A GATE is a condition an actor must satisfy before proceeding. It is DISTINCT from — and
|
|
7
|
+
* COMPLEMENTS — the per-action authorization seam (packages/kit/src/authz/authorize.ts + packages/kit/src/core/abilities.ts):
|
|
8
|
+
*
|
|
9
|
+
* - authorize() answers "may this actor perform THIS ONE action?" and DENIES (403) when not. It
|
|
10
|
+
* has no notion of resolution — a denied action is simply refused.
|
|
11
|
+
* - a gate answers "must this actor CLEAR something before proceeding?" and carries a
|
|
12
|
+
* resolution flow (how you clear it) plus a behavior (block vs advisory nudge).
|
|
13
|
+
*
|
|
14
|
+
* V1 ENFORCEMENT POSTURE (honest scope — pre-merge review): a block-all gate is enforced at the
|
|
15
|
+
* PROTECTED LAYOUT only. It blocks every protected screen, but direct API mutations by a
|
|
16
|
+
* blocked-but-authenticated user are NOT gated — API-level enforcement is exactly what the
|
|
17
|
+
* action-scoped seam below exists to add, by hooking gate facts into authorize(). This is a
|
|
18
|
+
* compliance/UX gate today, not a security boundary: the blocked actor holds unchanged abilities,
|
|
19
|
+
* so nothing is exposed that authorize()/RLS don't already govern.
|
|
20
|
+
*
|
|
21
|
+
* The template already taught per-action deny; nothing taught block-with-resolution, which is the
|
|
22
|
+
* new class here. The worked example shipped with the seam is agreements/clickwrap
|
|
23
|
+
* (packages/kit/src/core/agreements.ts) — but the seam is deliberately domain-agnostic so future RIDERS plug in
|
|
24
|
+
* without touching this file or the layout: email verification, MFA enrollment (the ADR-0003
|
|
25
|
+
* deferral), onboarding completeness, training/certification, account suspension, and billing
|
|
26
|
+
* entitlements are all gates of exactly this shape.
|
|
27
|
+
*
|
|
28
|
+
* The evaluation (evaluateGates) is PURE and INJECTABLE: the server assembles a plain `facts` object
|
|
29
|
+
* from its data path and hands it, with the registered gates, to evaluateGates. No IO lives here, so
|
|
30
|
+
* it is fully unit-testable and identical on every host.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Where a gate applies.
|
|
35
|
+
*
|
|
36
|
+
* - 'all' — blocks/advises across the WHOLE protected area. The only scope IMPLEMENTED in v1: the
|
|
37
|
+
* protected layout renders an interstitial (block) or a banner (advisory) instead of / above
|
|
38
|
+
* the app when such a gate is pending.
|
|
39
|
+
* - 'actions' — TYPED for the seam but NOT implemented this slice: a gate that gates a specific
|
|
40
|
+
* ability ACTION rather than the whole area (e.g. "you may read but not create until you
|
|
41
|
+
* re-accept"). See the SEAM NOTE at the bottom of this file for exactly where an
|
|
42
|
+
* action-scoped gate would hook into abilities/authorize — do NOT build it here.
|
|
43
|
+
*/
|
|
44
|
+
export type GateScope = 'all' | 'actions'
|
|
45
|
+
|
|
46
|
+
/** How a pending gate behaves: a block (interstitial replaces the protected UI — see the v1
|
|
47
|
+
* enforcement posture above) or an advisory nudge (dismissible banner, may proceed). */
|
|
48
|
+
export type GateBehavior = 'block' | 'advisory'
|
|
49
|
+
|
|
50
|
+
export interface Gate {
|
|
51
|
+
/** Stable id, unique within the registry (e.g. `agreement:<uuid>`). Names the pending gate the
|
|
52
|
+
* server maps back to its resolution content. */
|
|
53
|
+
id: string
|
|
54
|
+
scope: GateScope
|
|
55
|
+
behavior: GateBehavior
|
|
56
|
+
/**
|
|
57
|
+
* Route to the resolution flow. In v1 the agreements interstitial is rendered INSIDE the
|
|
58
|
+
* protected layout (there is no separate resolution route to navigate to — see the layout's
|
|
59
|
+
* comment and the decision log), so this is informational / telemetry for now and a genuine
|
|
60
|
+
* navigation target for a future rider whose resolution lives on its own page.
|
|
61
|
+
*/
|
|
62
|
+
resolutionPath: string
|
|
63
|
+
/**
|
|
64
|
+
* PURE predicate over the assembled facts: is this gate currently UNMET for the actor? Kept ON
|
|
65
|
+
* the gate (rather than in a separate registry→predicate map) so a rider ships its gate and the
|
|
66
|
+
* condition that makes it pending as ONE unit. evaluateGates calls this — it never inspects facts
|
|
67
|
+
* itself, which is what keeps the seam domain-agnostic.
|
|
68
|
+
*/
|
|
69
|
+
pending: (facts: GateFacts) => boolean
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A gate that evaluated as pending for the current actor — the layout/twin renders from these. */
|
|
73
|
+
export interface PendingGate {
|
|
74
|
+
id: string
|
|
75
|
+
scope: GateScope
|
|
76
|
+
behavior: GateBehavior
|
|
77
|
+
resolutionPath: string
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The facts a gate is evaluated against — a plain object the server assembles per request from its
|
|
82
|
+
* own data reads, then hands to evaluateGates. Deliberately an OPEN bag of optional keys: the
|
|
83
|
+
* worked example (agreements) supplies `pendingAgreementIds`; a future rider adds its own key
|
|
84
|
+
* (e.g. `emailVerified?: boolean`, `mfaEnrolled?: boolean`) without changing this signature or the
|
|
85
|
+
* evaluator. A gate reads only the key(s) it cares about in its own `pending` predicate.
|
|
86
|
+
*/
|
|
87
|
+
export interface GateFacts {
|
|
88
|
+
/** Ids of agreements the actor has NOT accepted at the current version (from packages/kit/src/core/agreements). */
|
|
89
|
+
pendingAgreementIds?: string[]
|
|
90
|
+
// FUTURE riders add fact keys here, e.g.:
|
|
91
|
+
// emailVerified?: boolean
|
|
92
|
+
// mfaEnrolled?: boolean
|
|
93
|
+
// onboardingComplete?: boolean
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Evaluate the registered gates against the actor's facts → the pending ones. Pure: filter each
|
|
98
|
+
* registered gate through its own predicate, project to the serializable PendingGate shape, and
|
|
99
|
+
* order BLOCK gates before advisory ones so a caller taking "the first blocker" is deterministic.
|
|
100
|
+
*
|
|
101
|
+
* `registered` is the UNIVERSE of gates that could apply (e.g. one per existing agreement); `facts`
|
|
102
|
+
* says which actually apply to THIS actor. The intersection is the pending set. This universe-vs-actor
|
|
103
|
+
* split is what lets a rider register a gate globally while the per-actor condition stays in facts.
|
|
104
|
+
*/
|
|
105
|
+
export function evaluateGates(registered: Gate[], facts: GateFacts): PendingGate[] {
|
|
106
|
+
return registered
|
|
107
|
+
.filter((gate) => gate.pending(facts))
|
|
108
|
+
.map((gate): PendingGate => ({
|
|
109
|
+
id: gate.id,
|
|
110
|
+
scope: gate.scope,
|
|
111
|
+
behavior: gate.behavior,
|
|
112
|
+
resolutionPath: gate.resolutionPath,
|
|
113
|
+
}))
|
|
114
|
+
.sort((a, b) => behaviorRank(a.behavior) - behaviorRank(b.behavior))
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The first pending BLOCK gate, if any — the one the protected layout renders an interstitial for.
|
|
118
|
+
* (evaluateGates already sorts block-first, but this states the intent at the call site.) */
|
|
119
|
+
export function firstBlockingGate(pending: PendingGate[]): PendingGate | undefined {
|
|
120
|
+
return pending.find((gate) => gate.behavior === 'block')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The pending ADVISORY gates — rendered as dismissible banners above the app, never blocking. */
|
|
124
|
+
export function advisoryGates(pending: PendingGate[]): PendingGate[] {
|
|
125
|
+
return pending.filter((gate) => gate.behavior === 'advisory')
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** block sorts before advisory. */
|
|
129
|
+
function behaviorRank(behavior: GateBehavior): number {
|
|
130
|
+
return behavior === 'block' ? 0 : 1
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/*
|
|
134
|
+
* ── SEAM NOTE: action-scoped gates (GateScope 'actions') — documented, NOT built ──────────────────
|
|
135
|
+
*
|
|
136
|
+
* A v1 gate is always scope 'all': it is consulted ONCE, in the protected layout's data path, and
|
|
137
|
+
* either blocks the whole area (interstitial) or advises (banner). An 'actions'-scoped gate would
|
|
138
|
+
* instead gate a SPECIFIC ability action while leaving the rest of the app reachable — e.g. "a lapsed
|
|
139
|
+
* ToS lets you READ but blocks CREATE until you re-accept".
|
|
140
|
+
*
|
|
141
|
+
* WHERE it would hook when built (do not implement now):
|
|
142
|
+
* - The natural point is packages/kit/src/authz/authorize.ts, alongside (and AFTER) the abilities check. After
|
|
143
|
+
* `defineAbilitiesFor(...).can(action, subject)` allows an action, authorize() would additionally
|
|
144
|
+
* consult the pending 'actions'-scoped gates for that (action, subjectType) and throw a distinct
|
|
145
|
+
* error (e.g. GateBlockedError → a 409/redirect carrying resolutionPath) rather than the plain
|
|
146
|
+
* 403 ForbiddenError. The gate's `pending(facts)` predicate stays pure and unchanged; only the
|
|
147
|
+
* facts assembly moves into the request's authorize path (which already resolves the actor + org).
|
|
148
|
+
* - The gate would additionally carry which actions it scopes (e.g. `actions: AbilityAction[]` and
|
|
149
|
+
* an optional `subjectTypes: SubjectType[]`), read by that authorize()-side consultation. Those
|
|
150
|
+
* fields are intentionally ABSENT from the Gate type above so the v1 seam stays minimal — add
|
|
151
|
+
* them with the rider, not speculatively.
|
|
152
|
+
* - resolutionPath finally earns its keep here: an action-scoped block can't render in-layout (the
|
|
153
|
+
* actor is mid-flow), so authorize() would surface resolutionPath for the client to navigate to.
|
|
154
|
+
*
|
|
155
|
+
* This is written down (not built) on purpose — the round-2 doctrine: known patterns get recorded so
|
|
156
|
+
* they aren't built early. The v1 'all'-scope gate is the whole implemented surface.
|
|
157
|
+
*/
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sample packages/kit/src/core module: pure TypeScript, framework-free (ADR-0006), unit-tested without any harness.
|
|
3
|
+
*/
|
|
4
|
+
export function normalizeDisplayName(input: string): string {
|
|
5
|
+
const trimmed = input.trim().replace(/\s+/g, ' ')
|
|
6
|
+
if (!trimmed) return ''
|
|
7
|
+
return trimmed
|
|
8
|
+
.split(' ')
|
|
9
|
+
.map((word) => word.charAt(0).toLocaleUpperCase() + word.slice(1))
|
|
10
|
+
.join(' ')
|
|
11
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inbound email address scheme + normalization — PURE, ISOMORPHIC TypeScript (ADR-0006,
|
|
3
|
+
* lint-enforced): no framework, no node builtins. The SAME parser runs on the server intake AND inside
|
|
4
|
+
* the file:// static-demo twin, so an inbound-email demo works with no server at all.
|
|
5
|
+
*
|
|
6
|
+
* ## Address scheme — plus (sub-addressing) convention: `<org-slug>+<handler>@<domain>`
|
|
7
|
+
*
|
|
8
|
+
* e.g. `sales+support@mg.example.com`. The base local part is the ORG slug, the `+tag` is the HANDLER
|
|
9
|
+
* slug. Chosen over the subdomain form (`support@sales.example.com`) because it needs a SINGLE Mailgun
|
|
10
|
+
* domain and a SINGLE catch-all route — no per-org DNS/MX. The plus sign is RFC-5321-valid in a local
|
|
11
|
+
* part and Mailgun routes match it with a regex (`match_recipient(".*\\+.*@domain")`); the classic
|
|
12
|
+
* client-side worry that a mail client strips `+tag` only bites addresses a HUMAN types as their own
|
|
13
|
+
* From/To — this is an intake address the app HANDS OUT for the world to send to, so stripping never
|
|
14
|
+
* applies. See the decision log.
|
|
15
|
+
*
|
|
16
|
+
* ## Org resolution
|
|
17
|
+
*
|
|
18
|
+
* The address names only the org slug (no tenant). Org slugs are unique per tenant in the schema, so a
|
|
19
|
+
* caller resolves the org GLOBALLY by slug (unique across the seed) which yields the tenant too; an
|
|
20
|
+
* ambiguous slug across tenants can't be disambiguated from the address alone and is treated as
|
|
21
|
+
* unresolved. A real MULTI-domain instance maps the recipient DOMAIN to the tenant first — documented
|
|
22
|
+
* as the single-domain simplification in the decision log. This module owns only the pure PARSE; the
|
|
23
|
+
* DB resolution lives in packages/kit/src/inbound-email/intake.ts.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The fake-world display domain the Simulator "compose inbound" flow and the static twin build intake
|
|
28
|
+
* addresses under (`sales+support@inbound.example.test`). It is a SIMULATED-WORLD value, not a
|
|
29
|
+
* deployment parameter — the real inbound domain is Mailgun's (`config/params.ts` mailgun.domain), and
|
|
30
|
+
* the real webhook only ever PARSES the domain a message arrives on, never constructs one. Matches the
|
|
31
|
+
* seed's `@example.test` person convention.
|
|
32
|
+
*/
|
|
33
|
+
export const DEMO_INBOUND_DOMAIN = 'inbound.example.test'
|
|
34
|
+
|
|
35
|
+
/** A parsed recipient: which org's which handler the message is addressed to. */
|
|
36
|
+
export interface InboundRecipient {
|
|
37
|
+
orgSlug: string
|
|
38
|
+
handler: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Slug shape shared by org slugs and handler slugs: lowercase alnum, internal hyphens. */
|
|
42
|
+
const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Pull the bare addr-spec out of a possibly-decorated address: `"Ada Keeper" <ada@x.test>` → `ada@x.test`,
|
|
46
|
+
* a bare `ada@x.test` → itself. Lowercased and trimmed (email domains are case-insensitive, and local
|
|
47
|
+
* parts are case-insensitive in every practical mail system — we normalize so a sender/member match is
|
|
48
|
+
* not defeated by case). Returns '' for anything without an addr-spec.
|
|
49
|
+
*/
|
|
50
|
+
export function normalizeEmailAddress(raw: string): string {
|
|
51
|
+
const angle = raw.match(/<([^>]+)>/)
|
|
52
|
+
const candidate = (angle ? angle[1]! : raw).trim().toLowerCase()
|
|
53
|
+
// A single '@' with non-empty both sides, else not a usable address.
|
|
54
|
+
const at = candidate.indexOf('@')
|
|
55
|
+
if (at <= 0 || at !== candidate.lastIndexOf('@') || at === candidate.length - 1) return ''
|
|
56
|
+
return candidate
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Parse a recipient address into `{ orgSlug, handler }`, or null when it doesn't fit the scheme. The
|
|
61
|
+
* local part must be `<org-slug>+<handler>`; both halves must be non-empty slugs. Everything is
|
|
62
|
+
* lowercased first (see normalizeEmailAddress). A recipient with no `+`, an empty half, or a
|
|
63
|
+
* non-slug half returns null (→ the message is filed 'unmatched' with no handler).
|
|
64
|
+
*/
|
|
65
|
+
export function parseInboundRecipient(rawRecipient: string): InboundRecipient | null {
|
|
66
|
+
const address = normalizeEmailAddress(rawRecipient)
|
|
67
|
+
if (!address) return null
|
|
68
|
+
const localPart = address.slice(0, address.indexOf('@'))
|
|
69
|
+
const plus = localPart.indexOf('+')
|
|
70
|
+
if (plus <= 0 || plus === localPart.length - 1) return null
|
|
71
|
+
const orgSlug = localPart.slice(0, plus)
|
|
72
|
+
const handler = localPart.slice(plus + 1)
|
|
73
|
+
if (!SLUG.test(orgSlug) || !SLUG.test(handler)) return null
|
|
74
|
+
return { orgSlug, handler }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* WHY intake filed an inbound email as it did: the `detail` of its `inbound-email.received` audit row
|
|
79
|
+
* (@sssb/kit/db/audit, migration 0016), written by the server intake and its static twin alike.
|
|
80
|
+
*
|
|
81
|
+
* A closed vocabulary on purpose. A handler's refusal `reason` is free text, and the reference handlers
|
|
82
|
+
* (the showcase's and SSSB's test fixture's) put the sender's address in it ("sender … is not a member of …"). It stays on the inbound_emails row, which
|
|
83
|
+
* `app_user` may UPDATE. The audit trail grants no UPDATE, so nothing a sender wrote goes there.
|
|
84
|
+
*/
|
|
85
|
+
export type InboundReceivedDetail =
|
|
86
|
+
| { outcome: 'handled' }
|
|
87
|
+
| { outcome: 'unmatched'; cause: 'no-handler' | 'declined' }
|
|
88
|
+
/**
|
|
89
|
+
* `handler-threw`: the handler did. `intake-threw`: the handler returned, and SSSB's own recording of
|
|
90
|
+
* its result then threw, so whatever the handler did may already have happened.
|
|
91
|
+
*/
|
|
92
|
+
| { outcome: 'failed'; cause: 'handler-threw' | 'intake-threw' }
|
|
93
|
+
|
|
94
|
+
/** Build the intake address for an org+handler under a domain — the inverse of parseInboundRecipient. */
|
|
95
|
+
export function formatInboundRecipient(orgSlug: string, handler: string, domain: string): string {
|
|
96
|
+
return `${orgSlug}+${handler}@${domain}`
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Reply-chain boundaries we recognize. Deliberately conservative (see normalizeInboundBody): only the
|
|
100
|
+
// top-posted reply above one of these markers is kept.
|
|
101
|
+
const REPLY_MARKERS: RegExp[] = [
|
|
102
|
+
// Gmail / Apple Mail: "On Tue, Jul 22, 2026 at 3:04 PM Ada Keeper <ada@x> wrote:"
|
|
103
|
+
/^\s*On .+ wrote:\s*$/m,
|
|
104
|
+
// Outlook / many clients: "-----Original Message-----"
|
|
105
|
+
/^\s*-{2,}\s*Original Message\s*-{2,}\s*$/im,
|
|
106
|
+
// Outlook header block: "From: someone" at the start of a line
|
|
107
|
+
/^\s*From:\s.+$/m,
|
|
108
|
+
]
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Normalize an inbound body to plain text, stripping the quoted reply chain MINIMALLY and HONESTLY:
|
|
112
|
+
* keep everything up to the FIRST recognized reply marker (see REPLY_MARKERS), trimmed. This keeps the
|
|
113
|
+
* top-posted new message and drops the quoted history — the common case — without pretending to a full
|
|
114
|
+
* MIME/quote parser. Its limits, recorded on purpose: bottom-posting and interleaved inline quoting are
|
|
115
|
+
* NOT handled (the whole body is kept if no marker appears), and a body that is ENTIRELY quoted would
|
|
116
|
+
* trim to empty — so if stripping would leave nothing, the original trimmed text is kept instead. In
|
|
117
|
+
* real mode Mailgun's own `stripped-text` is preferred upstream; this is the fallback and the twin's
|
|
118
|
+
* only stripper.
|
|
119
|
+
*/
|
|
120
|
+
export function normalizeInboundBody(raw: string): string {
|
|
121
|
+
const text = (raw ?? '').replace(/\r\n/g, '\n')
|
|
122
|
+
let cut = text.length
|
|
123
|
+
for (const marker of REPLY_MARKERS) {
|
|
124
|
+
const match = marker.exec(text)
|
|
125
|
+
if (match && match.index < cut) cut = match.index
|
|
126
|
+
}
|
|
127
|
+
const stripped = text.slice(0, cut).trim()
|
|
128
|
+
return stripped.length > 0 ? stripped : text.trim()
|
|
129
|
+
}
|
package/src/core/jobs.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { appJobKinds, type AppJobKind } from '@sssb/app-config/jobs'
|
|
2
|
+
import { defineStateMachine } from './state-machine'
|
|
3
|
+
|
|
4
|
+
export const JOB_STATUSES = ['queued', 'running', 'completed', 'failed'] as const
|
|
5
|
+
export type JobStatus = (typeof JOB_STATUSES)[number]
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The job lifecycle. No queued -> completed shortcut on purpose: even an instant fake records the
|
|
9
|
+
* full story (queued -> running -> completed), so the timeline reads identically whether the work
|
|
10
|
+
* ran in-process (fake) or on CodeBuild (real). Both terminal states have no outgoing transitions.
|
|
11
|
+
*/
|
|
12
|
+
export const jobStatusMachine = defineStateMachine<JobStatus>({
|
|
13
|
+
queued: ['running', 'failed'],
|
|
14
|
+
running: ['completed', 'failed'],
|
|
15
|
+
completed: [],
|
|
16
|
+
failed: [],
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
// The FRAMEWORK's own job kinds. digest-email: the scheduled-work worked example — a
|
|
20
|
+
// scheduler (packages/kit/src/db/schedules.ts) spawns it through this same jobs machinery, and its handler composes
|
|
21
|
+
// an org digest and sends it via the email port. App kinds register through the seam
|
|
22
|
+
// (src/app-config/jobs.ts appJobKinds), composed below exactly like the migration registry — a
|
|
23
|
+
// new kind is how instances extend jobs (ADR-0012; "one worked example per class").
|
|
24
|
+
export const FRAMEWORK_JOB_KINDS = ['digest-email'] as const
|
|
25
|
+
type FrameworkJobKind = (typeof FRAMEWORK_JOB_KINDS)[number]
|
|
26
|
+
|
|
27
|
+
/** The full kind union: framework base + the app's registered kinds. */
|
|
28
|
+
export type JobKind = FrameworkJobKind | AppJobKind
|
|
29
|
+
|
|
30
|
+
export function isJobKind(value: string): value is JobKind {
|
|
31
|
+
// Composed lazily (never a top-level spread) so the core↔seam value cycle stays safe: appJobKinds
|
|
32
|
+
// is only read when isJobKind is CALLED (request time), never at module-init. See ADR-0012 risks.
|
|
33
|
+
return (
|
|
34
|
+
(FRAMEWORK_JOB_KINDS as readonly string[]).includes(value) || (appJobKinds as readonly string[]).includes(value)
|
|
35
|
+
)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function isJobStatus(value: string): value is JobStatus {
|
|
39
|
+
return (JOB_STATUSES as readonly string[]).includes(value)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The storage namespace a job's export artifacts must live in. Encodes BOTH tenant AND org because
|
|
44
|
+
* storage isolation is purely by key convention: the service/webhook boundaries prefix-lock a
|
|
45
|
+
* caller-supplied resultKey to this, so a planted key can never point a signed download at another
|
|
46
|
+
* org's (or tenant's) artifact. Jobs with no active team use a reserved literal segment — org ids
|
|
47
|
+
* are uuids, so 'no-org' cannot collide with a real org's namespace.
|
|
48
|
+
*/
|
|
49
|
+
export function exportKeyPrefix(tenantId: string, orgId: string | null): string {
|
|
50
|
+
return `exports/${tenantId}/${orgId ?? 'no-org'}/`
|
|
51
|
+
}
|