@sssb/create 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.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/bin/create.js +135 -0
  3. package/package.json +22 -5
  4. package/src/args.js +270 -0
  5. package/src/files.js +660 -0
  6. package/src/generate.js +517 -0
  7. package/src/json.js +60 -0
  8. package/src/signals.js +72 -0
  9. package/src/template.js +496 -0
  10. package/src/yaml.js +17 -0
  11. package/template/app/DEMO-SIZE.md +55 -0
  12. package/template/app/config/app.ts +17 -0
  13. package/template/app/config/params.ts +70 -0
  14. package/template/app/infra/README.md +78 -0
  15. package/template/app/infra/app.ts +45 -0
  16. package/template/app/infra/cdk.json +9 -0
  17. package/template/app/infra/lib/tags.ts +35 -0
  18. package/template/app/infra/package.json +20 -0
  19. package/template/app/infra/tsconfig.json +13 -0
  20. package/template/app/messages/en.json +20 -0
  21. package/template/app/messages/es.json +20 -0
  22. package/template/app/next.config.ts +9 -0
  23. package/template/app/package.json +40 -0
  24. package/template/app/playwright.config.ts +50 -0
  25. package/template/app/playwright.demo.config.ts +10 -0
  26. package/template/app/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx +37 -0
  27. package/template/app/src/app/[locale]/(protected)/dashboard/page.tsx +21 -0
  28. package/template/app/src/app/[locale]/(protected)/header-glue.tsx +59 -0
  29. package/template/app/src/app/[locale]/(protected)/layout.tsx +43 -0
  30. package/template/app/src/app/[locale]/layout.tsx +55 -0
  31. package/template/app/src/app/[locale]/page.tsx +9 -0
  32. package/template/app/src/app/[locale]/signin/page.tsx +55 -0
  33. package/template/app/src/app/[locale]/signin/picker-glue.tsx +21 -0
  34. package/template/app/src/app/api/auth/dev-signin/route.ts +12 -0
  35. package/template/app/src/app/api/auth/org/route.ts +10 -0
  36. package/template/app/src/app/api/auth/signout/route.ts +9 -0
  37. package/template/app/src/app/api/items/route.ts +52 -0
  38. package/template/app/src/app/api/respond.ts +13 -0
  39. package/template/app/src/app/api/webhooks/cron/route.test.ts +59 -0
  40. package/template/app/src/app/api/webhooks/cron/route.ts +15 -0
  41. package/template/app/src/app/layout.tsx +7 -0
  42. package/template/app/src/app-config/abilities.ts +93 -0
  43. package/template/app/src/app-config/actors.ts +13 -0
  44. package/template/app/src/app-config/audit.ts +9 -0
  45. package/template/app/src/app-config/db/migrations/1001_items.ts +37 -0
  46. package/template/app/src/app-config/db/migrations/index.ts +11 -0
  47. package/template/app/src/app-config/db/rls-proofs.ts +81 -0
  48. package/template/app/src/app-config/db/schema.ts +23 -0
  49. package/template/app/src/app-config/digest.ts +10 -0
  50. package/template/app/src/app-config/identity.ts +8 -0
  51. package/template/app/src/app-config/inbound-email.ts +10 -0
  52. package/template/app/src/app-config/jobs.ts +28 -0
  53. package/template/app/src/app-config/messages.ts +18 -0
  54. package/template/app/src/app-config/notifications.ts +31 -0
  55. package/template/app/src/app-config/preset-operations.ts +9 -0
  56. package/template/app/src/app-config/presets.ts +18 -0
  57. package/template/app/src/app-config/seed.ts +7 -0
  58. package/template/app/src/app-config/simulator.ts +17 -0
  59. package/template/app/src/app-config/tours.ts +14 -0
  60. package/template/app/src/app-config/webhooks.ts +13 -0
  61. package/template/app/src/components/dashboard-screen.tsx +26 -0
  62. package/template/app/src/components/items-card.tsx +84 -0
  63. package/template/app/src/components/welcome-screen.tsx +20 -0
  64. package/template/app/src/demo-static/app.tsx +77 -0
  65. package/template/app/src/demo-static/index.html +12 -0
  66. package/template/app/src/demo-static/main.tsx +40 -0
  67. package/template/app/src/proxy.ts +9 -0
  68. package/template/app/src/seed/index.ts +93 -0
  69. package/template/app/src/sssb.conformance.test.ts +7 -0
  70. package/template/app/src/styles/index.css +1 -0
  71. package/template/app/tests/catalog.ts +15 -0
  72. package/template/app/tests/contract/rls-contract.test.ts +14 -0
  73. package/template/app/tests/demo-static/static-shell.spec.ts +32 -0
  74. package/template/app/tests/e2e/items.spec.ts +58 -0
  75. package/template/app/tsconfig.json +29 -0
  76. package/template/app/vite.demo.config.ts +8 -0
  77. package/template/guide.md +118 -0
  78. package/template/meta.json +633 -0
  79. package/template/root/_dot_editorconfig +12 -0
  80. package/template/root/_dot_husky/commit-msg +1 -0
  81. package/template/root/_dot_husky/pre-commit +1 -0
  82. package/template/root/_dot_nvmrc +1 -0
  83. package/template/root/_dot_prettierrc.json +5 -0
  84. package/template/root/commitlint.config.mjs +1 -0
  85. package/README.md +0 -3
@@ -0,0 +1,21 @@
1
+ 'use client'
2
+
3
+ import { PeoplePicker, type PickerPerson } from '@sssb/kit/components/auth/people-picker'
4
+
5
+ /** Client half of the simulated-mode sign-in: pick a person, POST it, land wherever we came from. */
6
+ export function PickerGlue({ people, returnTo }: { people: PickerPerson[]; returnTo: string }) {
7
+ return (
8
+ <PeoplePicker
9
+ people={people}
10
+ onPick={(personId) => {
11
+ void fetch('/api/auth/dev-signin', {
12
+ method: 'POST',
13
+ headers: { 'content-type': 'application/json' },
14
+ body: JSON.stringify({ personId }),
15
+ }).then((response) => {
16
+ if (response.ok) window.location.assign(returnTo)
17
+ })
18
+ }}
19
+ />
20
+ )
21
+ }
@@ -0,0 +1,12 @@
1
+ import { devSignIn } from '@sssb/kit/adapters/fake/auth'
2
+ import { isSimulated } from '@sssb/kit/adapters/index'
3
+ import { withPortErrors } from '../../respond'
4
+
5
+ export async function POST(request: Request): Promise<Response> {
6
+ if (!isSimulated) return Response.json({ error: 'not found' }, { status: 404 })
7
+ return withPortErrors(async () => {
8
+ const { personId } = (await request.json()) as { personId: string }
9
+ await devSignIn(personId)
10
+ return Response.json({ ok: true })
11
+ })
12
+ }
@@ -0,0 +1,10 @@
1
+ import { auth } from '@sssb/kit/adapters/index'
2
+ import { withPortErrors } from '../../respond'
3
+
4
+ export async function POST(request: Request): Promise<Response> {
5
+ return withPortErrors(async () => {
6
+ const { orgSlug } = (await request.json()) as { orgSlug: string }
7
+ await auth.setActiveOrg(orgSlug)
8
+ return Response.json({ ok: true })
9
+ })
10
+ }
@@ -0,0 +1,9 @@
1
+ import { auth } from '@sssb/kit/adapters/index'
2
+ import { withPortErrors } from '../../respond'
3
+
4
+ export async function POST(): Promise<Response> {
5
+ return withPortErrors(async () => {
6
+ await auth.signOut()
7
+ return Response.json({ ok: true })
8
+ })
9
+ }
@@ -0,0 +1,52 @@
1
+ import { auth, db } from '@sssb/kit/adapters/index'
2
+ import { authorize } from '@sssb/kit/authz/authorize'
3
+ import { orgIdForSlug } from '@sssb/kit/db/org-lookup'
4
+ import { tenantIdForSlug } from '@sssb/kit/db/tenant-lookup'
5
+ import { withPortErrors } from '../respond'
6
+
7
+ /**
8
+ * The app's only product route. Items are tenant-scoped by RLS (the hostile-isolation boundary) AND
9
+ * filtered to the active org (the team boundary — an app-level WHERE, since org membership is enforced
10
+ * at the auth port; ADR-0004). Every query runs inside withTenant.
11
+ */
12
+ export async function GET(): Promise<Response> {
13
+ return withPortErrors(async () => {
14
+ const user = await auth.requireUser()
15
+ const tenantId = await tenantIdForSlug(db, user.tenantSlug)
16
+ if (!tenantId) return Response.json({ error: 'unknown tenant' }, { status: 404 })
17
+ const orgId = await orgIdForSlug(db, tenantId, user.orgSlug)
18
+ if (!orgId) return Response.json({ error: 'unknown org' }, { status: 404 })
19
+ const items = await db.withTenant(tenantId, (trx) =>
20
+ trx
21
+ .selectFrom('items')
22
+ .select(['id', 'title'])
23
+ .where('org_id', '=', orgId)
24
+ .orderBy('created_at', 'desc')
25
+ .execute(),
26
+ )
27
+ return Response.json({ items })
28
+ })
29
+ }
30
+
31
+ export async function POST(request: Request): Promise<Response> {
32
+ return withPortErrors(async () => {
33
+ const user = await auth.requireUser()
34
+ const { title } = (await request.json()) as { title: string }
35
+ if (!title?.trim()) return Response.json({ error: 'empty item' }, { status: 400 })
36
+ const tenantId = await tenantIdForSlug(db, user.tenantSlug)
37
+ if (!tenantId) return Response.json({ error: 'unknown tenant' }, { status: 404 })
38
+ const orgId = await orgIdForSlug(db, tenantId, user.orgSlug)
39
+ if (!orgId) return Response.json({ error: 'unknown org' }, { status: 404 })
40
+ // The authorization choke point: restricted members may read items but not author them.
41
+ // Throws ForbiddenError → 403 via withPortErrors.
42
+ authorize(user, orgId, 'create', { type: 'Item', orgId })
43
+ const item = await db.withTenant(tenantId, (trx) =>
44
+ trx
45
+ .insertInto('items')
46
+ .values({ tenant_id: tenantId, org_id: orgId, title: title.trim(), created_by_user_id: user.id })
47
+ .returning(['id', 'title'])
48
+ .executeTakeFirstOrThrow(),
49
+ )
50
+ return Response.json({ item })
51
+ })
52
+ }
@@ -0,0 +1,13 @@
1
+ import { AuthRequiredError, ForbiddenError, NotFoundError } from '@sssb/kit/ports/errors'
2
+
3
+ /** Maps port errors to HTTP for this app's route handlers. */
4
+ export async function withPortErrors(fn: () => Promise<Response>): Promise<Response> {
5
+ try {
6
+ return await fn()
7
+ } catch (error) {
8
+ if (error instanceof AuthRequiredError) return Response.json({ error: 'unauthorized' }, { status: 401 })
9
+ if (error instanceof ForbiddenError) return Response.json({ error: 'forbidden' }, { status: 403 })
10
+ if (error instanceof NotFoundError) return Response.json({ error: 'not found' }, { status: 404 })
11
+ throw error
12
+ }
13
+ }
@@ -0,0 +1,59 @@
1
+ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
2
+ import { makeTestTmpDir } from '@sssb/tools/testing/tmp-dir'
3
+ import { devWebhookSecret } from '@sssb/kit/adapters/fake/service-auth'
4
+ import { POST } from './route'
5
+
6
+ // The registry is the one thing the tick takes from @sssb/kit/adapters/index (a real import trips server-only in a
7
+ // test env): hand it the fake database and a jobs port that spawns nothing. Everything else is the real route,
8
+ // the real guard and the real tick.
9
+ const spawned = vi.hoisted(() => ({ calls: 0 }))
10
+ vi.mock('@sssb/kit/adapters/index', async () => {
11
+ const { fakeDb } = await import('@sssb/kit/adapters/fake/db')
12
+ return {
13
+ db: fakeDb,
14
+ jobs: {
15
+ async start() {
16
+ spawned.calls += 1
17
+ },
18
+ },
19
+ isSimulated: true,
20
+ }
21
+ })
22
+
23
+ const tmp = makeTestTmpDir('app-cron-route-')
24
+ beforeAll(() => {
25
+ process.env['APP_DATA_DIR'] = tmp
26
+ })
27
+ afterAll(() => {
28
+ delete process.env['APP_DATA_DIR']
29
+ })
30
+
31
+ function tick(authorization?: string): Promise<Response> {
32
+ const headers: Record<string, string> = {}
33
+ if (authorization !== undefined) headers['authorization'] = authorization
34
+ return POST(new Request('http://localhost/api/webhooks/cron', { method: 'POST', headers }))
35
+ }
36
+
37
+ describe('POST /api/webhooks/cron', () => {
38
+ test('is never open: no secret, a wrong secret and a malformed header are all an opaque 401', async () => {
39
+ const wrong = `Bearer ${'f'.repeat(devWebhookSecret().length)}`
40
+ for (const authorization of [undefined, wrong, `Basic ${devWebhookSecret()}`]) {
41
+ const response = await tick(authorization)
42
+ expect(response.status, String(authorization)).toBe(401)
43
+ expect(await response.json()).toEqual({ error: 'unauthorized' })
44
+ }
45
+ expect(spawned.calls).toBe(0)
46
+ })
47
+
48
+ test("with the shared secret it runs SSSB's tick and says what it did", async () => {
49
+ const response = await tick(`Bearer ${devWebhookSecret()}`)
50
+
51
+ expect(response.status).toBe(200)
52
+ expect(await response.json()).toEqual({
53
+ ok: true,
54
+ spawned: expect.any(Number),
55
+ failed: 0,
56
+ deliveries: { delivered: expect.any(Number), failed: expect.any(Number), dead: expect.any(Number) },
57
+ })
58
+ })
59
+ })
@@ -0,0 +1,15 @@
1
+ import { runScheduledTick } from '@sssb/kit/server-lib/scheduled-tick'
2
+ import { withWebhookSecret } from '@sssb/kit/service-auth/webhook'
3
+
4
+ /**
5
+ * The scheduled-work tick (cutover row `scheduled-tick`). A scheduler POSTs here on a fixed cadence with
6
+ * `Authorization: Bearer $WEBHOOK_SECRET`; a request without that secret is an opaque 401 before anything runs.
7
+ * The body is ignored and the whole job is SSSB's `runScheduledTick`: drain the due schedules and the due webhook
8
+ * deliveries. This app has no Simulator routes, so without this route nothing ticks SSSB's scheduler there,
9
+ * in a deployment or in `pnpm dev`.
10
+ *
11
+ * Authorization is the shared-secret guard, and the handler has to BE it: the authorize() scan exempts a
12
+ * `webhooks/` handler (a machine caller, not a user session) only if that verb's export is a call to an imported
13
+ * `withWebhookSecret` (or `withMailgunSignature`), as POST is here.
14
+ */
15
+ export const POST = withWebhookSecret(async () => Response.json({ ok: true, ...(await runScheduledTick()) }))
@@ -0,0 +1,7 @@
1
+ import type { ReactNode } from 'react'
2
+
3
+ // Passthrough: the real document shell (html/body, providers) lives in [locale]/layout.tsx
4
+ // so the lang attribute can reflect the active locale.
5
+ export default function RootLayout({ children }: { children: ReactNode }) {
6
+ return children
7
+ }
@@ -0,0 +1,93 @@
1
+ import type { AbilityAction, AbilityActor, AbilitySubject, NonSessionAdministration } from '@sssb/kit/core/abilities'
2
+
3
+ /**
4
+ * The APP's authorization extension (the seam side of @sssb/kit/core/abilities.ts, ADR-0012). The framework
5
+ * owns the base subjects and the deny-by-default switch; this app registers ONE subject and its rules.
6
+ * PURE TypeScript, same as core.
7
+ */
8
+
9
+ /** The subject types this app adds on top of the framework's BaseSubjectType. */
10
+ export type AppSubjectType = 'Item'
11
+
12
+ /**
13
+ * App-specific fields merged into the framework's AbilitySubject (`AbilitySubject extends
14
+ * AppSubjectFields`). This app has NONE: every one of its subjects is scoped by the framework's own
15
+ * `orgId`, so there is nothing to add.
16
+ *
17
+ * The empty interface is deliberate and is the one place "an unused capability needs no scaffolding"
18
+ * is not quite free: because the framework EXTENDS this type, it must be an interface (a mapped type
19
+ * such as `Record<never, never>` cannot be extended), and an empty interface is exactly what
20
+ * `@typescript-eslint/no-empty-object-type` exists to flag. The suppression is narrow and local; the
21
+ * alternative — inventing a field this app does not have — would be worse.
22
+ */
23
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
24
+ export interface AppSubjectFields {}
25
+
26
+ /**
27
+ * The credential kinds, beyond SSSB's own, by which a PERSON or a MACHINE can reach this app (composed
28
+ * into @sssb/kit/core/abilities' `PersonCredentialKind` / `MachineCredentialKind`; SSSB's are `session`,
29
+ * `inbound-email` and `service-key`). This app adds none. An app with personal API tokens registers its
30
+ * token kind as a person credential; one with a CI identity, that as a machine credential.
31
+ */
32
+ export type AppPersonCredentialKind = never
33
+ export type AppMachineCredentialKind = never
34
+
35
+ /**
36
+ * The designated staff/operator org slug. ACTIVE membership in this org grants the `manageAll`
37
+ * ability-layer superpower (derived in @sssb/kit/authz/authorize.ts). It is one ordinary org WITHIN a
38
+ * tenant: staff powers stop at the tenant boundary and NEVER cross tenants (ADR-0004). WHICH org is
39
+ * the operator org is an app choice, so it lives here; it must name a real seed org (`src/seed`).
40
+ */
41
+ export const staffOrgSlug = 'ops'
42
+
43
+ /**
44
+ * The app-subject anchor extras for the non-throwing UI gate (canInActiveOrg). This app adds no
45
+ * subject fields, so there is nothing to anchor — the framework's own `orgId` anchor is enough, and
46
+ * the injected anchor is ignored. (The parameter stays because the framework calls it with one.)
47
+ */
48
+ export function anchorSubjectExtras(anchor: string): AppSubjectFields {
49
+ void anchor // nothing to anchor: this app registers no subject fields of its own
50
+ return {}
51
+ }
52
+
53
+ /**
54
+ * The app's per-subject rules, invoked by @sssb/kit/core/abilities.ts's `default:` case (deny by default).
55
+ * `sameOrg` is injected by core so "the subject is org-scoped AND its org is the acting org" is
56
+ * defined once.
57
+ * - Item: read = sameOrg; create|update|delete = !restricted && sameOrg.
58
+ */
59
+ export function appAbilityRules(
60
+ actor: AbilityActor,
61
+ action: AbilityAction,
62
+ subject: AbilitySubject,
63
+ { sameOrg }: { sameOrg: (subject: AbilitySubject) => boolean },
64
+ ): boolean {
65
+ switch (subject.type) {
66
+ case 'Item':
67
+ if (action === 'read') return sameOrg(subject)
68
+ if (action === 'create' || action === 'update' || action === 'delete') {
69
+ return !actor.restricted && sameOrg(subject)
70
+ }
71
+ return false
72
+ default:
73
+ // Deny by default: an app subject added here without a rule is denied.
74
+ return false
75
+ }
76
+ }
77
+
78
+ /**
79
+ * The app's rules for MACHINE actors (@sssb/kit/core/abilities `MachineActor` — a caller that is not a
80
+ * person: a CI identity, an integration). This app grants machines nothing, so every machine is denied
81
+ * every app subject; this function is the off switch. To let one in, switch on `subject.type` and the
82
+ * machine's `actor.credential.kind` here, the way `appAbilityRules` does for people.
83
+ */
84
+ export function appMachineAbilityRules(): boolean {
85
+ return false
86
+ }
87
+
88
+ /**
89
+ * The framework's session-only subjects (inviting members, changing the org, managing webhook endpoints,
90
+ * accepting terms) take a browser SESSION. Here an app may widen one of them to a non-session person
91
+ * credential (a personal API token, say; never an inbound email). This app widens none.
92
+ */
93
+ export const nonSessionAdministration: NonSessionAdministration = {}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The Simulator "actors" registry (the app side — ADR-0012). Actors are in-page automations that drive
3
+ * the same service/webhook surfaces a real counterparty would.
4
+ *
5
+ * EMPTY REGISTRATION. This app simulates no counterparties, so the id union is `never` — which is
6
+ * exactly right: an `ActorSlot[]` for this app can only ever be empty, and the compiler says so. The
7
+ * framework imports `ActorId` type-only, so registering nothing costs nothing. The `actors` LIST is a
8
+ * value, read by one framework test only (the seam-conformance suite derives the actor ids a demo
9
+ * preset's `actor.hold` may name from it); an app with actors lists each `{ id, … }` there.
10
+ */
11
+ export type ActorId = never
12
+
13
+ export const actors: readonly { id: string }[] = []
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The APP's audit-action vocabulary (the seam side of @sssb/kit/db/audit.ts, ADR-0012).
3
+ *
4
+ * EMPTY REGISTRATION. This app records no audit verbs of its own, so the union it contributes is
5
+ * `never` and `AuditAction` collapses to the framework's own verbs. The audit trail still works —
6
+ * framework mutations (invites, agreement acceptances, webhook lifecycle) record as they always did.
7
+ * Adding a verb is one union member here plus the `recordAuditEvent` call at the mutation site.
8
+ */
9
+ export type AppAuditAction = never
@@ -0,0 +1,37 @@
1
+ import { Kysely, sql } from 'kysely'
2
+
3
+ /**
4
+ * The `items` table — this app's only tenant-scoped table, carrying SSSB's RLS pattern (ADR-0004). It runs after every framework migration (name-sorted, 0001–0999
5
+ * first), so it can reference `tenants` and `organizations` directly.
6
+ *
7
+ * Two deliberate differences from SSSB's reference app's `1001_tickets`: `org_id` is NOT NULL (this
8
+ * app has no legacy rows to keep valid), and DELETE is NOT granted — an item can be listed and created,
9
+ * never erased, which is the posture most real tables want and is proved in ../rls-proofs.ts.
10
+ */
11
+ export async function up(db: Kysely<any>): Promise<void> {
12
+ await db.schema
13
+ .createTable('items')
14
+ .addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
15
+ .addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
16
+ .addColumn('org_id', 'uuid', (col) => col.notNull().references('organizations.id'))
17
+ .addColumn('title', 'text', (col) => col.notNull())
18
+ .addColumn('created_by_user_id', 'text', (col) => col.notNull())
19
+ .addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
20
+ .execute()
21
+
22
+ await sql`GRANT SELECT, INSERT, UPDATE ON items TO app_user`.execute(db)
23
+ await sql`ALTER TABLE items ENABLE ROW LEVEL SECURITY`.execute(db)
24
+ await sql`ALTER TABLE items FORCE ROW LEVEL SECURITY`.execute(db)
25
+ // NULLIF: unset tenant context must mean zero rows, never a cast error — a session that has
26
+ // ever SET LOCAL this GUC reports '' (not NULL) afterwards. See ADR-0002 spike findings.
27
+ await sql`
28
+ CREATE POLICY tenant_isolation ON items
29
+ FOR ALL
30
+ USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
31
+ WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
32
+ `.execute(db)
33
+ }
34
+
35
+ export async function down(db: Kysely<any>): Promise<void> {
36
+ await db.schema.dropTable('items').execute()
37
+ }
@@ -0,0 +1,11 @@
1
+ import type { Migration } from 'kysely/migration'
2
+ import * as m1001 from './1001_items'
3
+
4
+ /**
5
+ * The APP's migrations (the seam side of @sssb/kit/db/migrations, ADR-0012). Numbering convention: framework
6
+ * 0001–0999, app ≥1001. Composed into the framework registry, which Kysely runs NAME-SORTED — so these
7
+ * run AFTER every framework table exists. Add new app migrations here in order.
8
+ */
9
+ export const appMigrations: Record<string, Migration> = {
10
+ '1001_items': m1001,
11
+ }
@@ -0,0 +1,81 @@
1
+ import { sql } from 'kysely'
2
+ import type { RlsProofSuite } from '@sssb/kit/db/rls-proofs'
3
+ import { runWithTenant } from '@sssb/kit/db/with-tenant'
4
+
5
+ /**
6
+ * The APP's tenant-isolation proofs (the seam side of @sssb/kit/db/rls-proofs.ts, ADR-0004 + ADR-0012) —
7
+ * one section per app table, asserting exactly what the framework half asserts for its own: read
8
+ * isolation both directions under UNFILTERED selects, WITH CHECK on cross-tenant writes, and the
9
+ * per-table privilege grants.
10
+ *
11
+ * @sssb/kit/db/rls-proof-runner.ts composes this with the framework half and runs the union, so these
12
+ * assertions execute wherever that runner does. An adopter with no tenant tables leaves the body empty
13
+ * (ADR-0012, "unused capability = empty registration"). Kept in lockstep with ./migrations.
14
+ */
15
+ export const appRlsProofs: RlsProofSuite = async ({
16
+ db,
17
+ appDb,
18
+ expect,
19
+ alphaTenantId,
20
+ demoTenantId,
21
+ alphaOrgId,
22
+ demoOrgId,
23
+ }) => {
24
+ // ---- items: tenant-only RLS (1001), single-org app scoping, SELECT/INSERT/UPDATE (no DELETE) ----
25
+
26
+ await db
27
+ .insertInto('items')
28
+ .values([
29
+ { tenant_id: alphaTenantId, org_id: alphaOrgId, title: 'first item', created_by_user_id: 'proof-user' },
30
+ { tenant_id: alphaTenantId, org_id: alphaOrgId, title: 'second item', created_by_user_id: 'proof-user' },
31
+ {
32
+ tenant_id: demoTenantId,
33
+ org_id: demoOrgId,
34
+ title: 'other tenant item',
35
+ created_by_user_id: 'proof-user',
36
+ },
37
+ ])
38
+ .execute()
39
+
40
+ // read isolation, both directions, via UNFILTERED selects under RLS
41
+ const ours = await runWithTenant(appDb, alphaTenantId, (trx) => trx.selectFrom('items').selectAll().execute())
42
+ expect(ours.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
43
+ expect(ours.filter((r) => r.tenant_id === alphaTenantId).length).toBe(2)
44
+ const theirs = await runWithTenant(appDb, demoTenantId, (trx) => trx.selectFrom('items').selectAll().execute())
45
+ expect(theirs.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
46
+ expect(theirs.filter((r) => r.tenant_id === demoTenantId).length).toBe(1)
47
+
48
+ // write isolation: an INSERT carrying the OTHER tenant's id is rejected by WITH CHECK, even though
49
+ // the org id is a real org — the tenant, not the org, is the RLS boundary.
50
+ let writeRejected = false
51
+ try {
52
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
53
+ trx
54
+ .insertInto('items')
55
+ .values({
56
+ tenant_id: demoTenantId,
57
+ org_id: demoOrgId,
58
+ title: 'smuggled',
59
+ created_by_user_id: 'proof-user',
60
+ })
61
+ .execute(),
62
+ )
63
+ } catch (error) {
64
+ writeRejected = /row-level security/.test(String(error))
65
+ }
66
+ expect(writeRejected).toBe(true)
67
+
68
+ // DELETE is denied at the PRIVILEGE layer — the 1001 grant is SELECT/INSERT/UPDATE only, so an
69
+ // item can never be erased even by a correctly-scoped caller.
70
+ let deleteRejected = false
71
+ try {
72
+ await appDb.transaction().execute(async (trx) => {
73
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
74
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
75
+ await sql`DELETE FROM items`.execute(trx)
76
+ })
77
+ } catch (error) {
78
+ deleteRejected = /permission denied/.test(String(error))
79
+ }
80
+ expect(deleteRejected).toBe(true)
81
+ }
@@ -0,0 +1,23 @@
1
+ import type { Generated } from 'kysely'
2
+
3
+ /**
4
+ * The APP's tenant-scoped tables (the seam side of @sssb/kit/db/schema.ts, ADR-0012). The framework owns its
5
+ * tables + the `DB` interface, which `extends AppTables` (a type-only seam import). Kept in lockstep
6
+ * with the migrations in ./migrations (numbered ≥1001).
7
+ */
8
+
9
+ interface ItemsTable {
10
+ id: Generated<string>
11
+ tenant_id: string
12
+ /** The team that owns the item. NOT NULL — an app-level filter, not an RLS anchor (1001). */
13
+ org_id: string
14
+ title: string
15
+ /** Opaque user id (no users table) — same convention as the framework's jobs / service_keys. */
16
+ created_by_user_id: string
17
+ created_at: Generated<string>
18
+ }
19
+
20
+ /** The app's tables, merged into the framework `DB` interface (@sssb/kit/db/schema.ts `extends AppTables`). */
21
+ export interface AppTables {
22
+ items: ItemsTable
23
+ }
@@ -0,0 +1,10 @@
1
+ import type { DigestBodySource } from '@sssb/kit/jobs/digest-email'
2
+
3
+ /**
4
+ * The APP's digest source (the seam side of @sssb/kit/jobs/digest-email.ts, ADR-0012).
5
+ *
6
+ * EMPTY REGISTRATION: this app has nothing to digest, so the framework's scheduled digest still
7
+ * composes and sends — with its empty-state copy. Removing the capability would mean deleting a
8
+ * framework job kind; leaving it registered-and-empty costs one line.
9
+ */
10
+ export const digestBodies: DigestBodySource = async () => []
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Host identity — the app half of the seam the framework reads its slug through (ADR-0012).
3
+ *
4
+ * `APP_SLUG` is the ONE value an adopter changes to rename the app's mechanical identity: session and
5
+ * viewpoint cookies, the fake-auth JWT issuer, the service-token audience, outbound webhook header
6
+ * names, and the infra resource names. See `config/app.ts` for the collision-risk doctrine.
7
+ */
8
+ export { APP_SLUG } from '../../config/app'
@@ -0,0 +1,10 @@
1
+ import type { InboundHandler } from '@sssb/kit/inbound-email/handlers'
2
+
3
+ /**
4
+ * The app's inbound-email handler registrations (ADR-0012 seam). The recipient address
5
+ * `<org-slug>+<slug>@domain` names the slug; the framework intake looks it up in the composed registry.
6
+ *
7
+ * EMPTY REGISTRATION: this app accepts no email. Every inbound message therefore files as 'unmatched',
8
+ * which is the framework's own fail-closed behaviour for an unknown slug — no removal surgery needed.
9
+ */
10
+ export const appInboundHandlers: Record<string, InboundHandler> = {}
@@ -0,0 +1,28 @@
1
+ import type { JobHandler } from '@sssb/kit/ports/jobs'
2
+ import { digestEmailHandler } from '@sssb/kit/jobs/digest-email'
3
+
4
+ /**
5
+ * The APP's job registrations (the seam side of @sssb/kit/core/jobs.ts, ADR-0012).
6
+ *
7
+ * EMPTY REGISTRATION: no app job kinds, so `AppJobKind` is `never` and `JobKind` collapses to the
8
+ * framework's own. `jobHandlers` is still the composition root the fake jobs adapter consumes, and it
9
+ * still carries the framework's `digest-email` handler — the framework reaches its OWN handler through
10
+ * this seam because the fence forbids the adapter importing app-side modules directly.
11
+ */
12
+ export const appJobKinds = [] as const
13
+ export type AppJobKind = (typeof appJobKinds)[number]
14
+
15
+ /** One handler per app job kind. Exhaustive over AppJobKind — which is empty. */
16
+ export const appJobHandlers: Record<AppJobKind, JobHandler> = {}
17
+
18
+ /** The composed dispatch map (framework kinds + app kinds) — the jobs adapter's single source. */
19
+ export const jobHandlers: Record<string, JobHandler> = {
20
+ 'digest-email': digestEmailHandler,
21
+ ...appJobHandlers,
22
+ }
23
+
24
+ /**
25
+ * Org slugs whose jobs are served by a dedicated service actor, excluded from the generic pending-build
26
+ * pool. EMPTY: this app registers no actors, so no org is service-managed.
27
+ */
28
+ export const serviceManagedOrgSlugs: readonly string[] = []
@@ -0,0 +1,18 @@
1
+ import type { MessageTree } from '@sssb/kit/i18n/messages'
2
+
3
+ /**
4
+ * The APP's i18n registration (the seam side of @sssb/kit/i18n/namespaces.ts, ADR-0012). The catalogs are
5
+ * physically split: the framework owns FRAMEWORK_NAMESPACES in `@sssb/kit/i18n/messages/*.json`;
6
+ * this app owns APP_NAMESPACES in its own `messages/*.json`. Together they partition the merged catalog
7
+ * (disjoint + exhaustive), enforced by the conformance suite's `i18n-partition` check (@sssb/kit/testing), which
8
+ * this app runs against these registrations from src/sssb.conformance.test.ts.
9
+ */
10
+ export const APP_NAMESPACES = ['welcome', 'dashboard', 'items'] as const
11
+
12
+ /**
13
+ * The app's catalog for one locale. Framework code (the next-intl request config, the parity tests)
14
+ * reaches the app's messages ONLY through this loader — the seam's one message door.
15
+ */
16
+ export async function loadAppMessages(locale: string): Promise<MessageTree> {
17
+ return (await import(`../../messages/${locale}.json`)).default as MessageTree
18
+ }
@@ -0,0 +1,31 @@
1
+ import type { NotificationCopy } from '@sssb/kit/core/notifications'
2
+
3
+ /**
4
+ * The APP's notification kinds (the seam side of @sssb/kit/core/notifications.ts, ADR-0012). The framework
5
+ * owns the channels, the resolver, and its own kinds (org.invited, job.completed).
6
+ *
7
+ * EMPTY REGISTRATION: no app kinds. The bell, the prefs screen, email and SMS fan-out all keep working
8
+ * on the framework's kinds.
9
+ */
10
+ export const appNotificationKinds = [] as const
11
+ export type AppNotificationKind = (typeof appNotificationKinds)[number]
12
+
13
+ /** Per-kind payload shapes for the app kinds. There are none, so this contributes nothing to the
14
+ * intersection the framework builds (`Framework & App`). */
15
+ export type AppNotificationPayloadMap = Record<never, never>
16
+
17
+ /**
18
+ * Copy mapping for the app kinds. Unreachable by construction: the framework's `default:` case
19
+ * delegates here only for a kind outside its own union, and this app registers none — so both
20
+ * parameters are `never`. Returning one is the type-safe way to say "cannot happen"; inventing a
21
+ * placeholder NotificationCopy would be a lie the compiler could not check.
22
+ *
23
+ * Worth naming as a rough edge in the seam: an app that registers zero notification kinds still has
24
+ * to write this function, because the framework calls it unconditionally from the switch's default.
25
+ */
26
+ export function appNotificationCopy(
27
+ kind: AppNotificationKind,
28
+ payload: AppNotificationPayloadMap[AppNotificationKind],
29
+ ): NotificationCopy {
30
+ return payload ?? kind
31
+ }
@@ -0,0 +1,9 @@
1
+ import type { ServerPresetOperationHandler } from '@sssb/kit/server-lib/preset-operations'
2
+
3
+ /**
4
+ * The SERVER halves of the app's demo-preset operation kinds (@sssb/kit/server-lib/demo-presets.ts composes
5
+ * them over SSSB's own) — a server-only seam module (ADR-0012), separate from `./presets.ts` because the
6
+ * static demo bundles that one and must never bundle a server half. EMPTY REGISTRATION: this app adds no
7
+ * kinds, so SSSB's `invite`, `inbound`, `flag` and `actor.hold` are the whole registry.
8
+ */
9
+ export const appPresetOperationHandlers: Record<string, ServerPresetOperationHandler> = {}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The APP's demo presets (@sssb/kit/core/presets.ts) — the seam side of the Snapshots tab's "Start from a
3
+ * preset" list (ADR-0012). EMPTY REGISTRATION: no presets, so the tab shows no presets section, and a
4
+ * tour can still start from `'reset'`, the one world start every host has. To add one, put it in its own
5
+ * file under `./presets/` and list it here — `/sssb:new-preset` walks through it.
6
+ *
7
+ * No operation kinds of its own either: a preset here can use SSSB's (`invite`, `inbound`, `flag`;
8
+ * `actor.hold` needs an actor, and this app registers none). Add one with `/sssb:new-preset-operation`, which
9
+ * registers its definition below and its server half in `./preset-operations.ts`.
10
+ */
11
+
12
+ import type { DemoPreset, PresetOperationDefinition } from '@sssb/kit/core/presets'
13
+
14
+ export type AppPresetOperation = never
15
+
16
+ export const appPresetOperations: PresetOperationDefinition[] = []
17
+
18
+ export const presets: DemoPreset[] = []
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The seam re-export of the app's seed data (ADR-0012). Framework code that needs the world — the fake
3
+ * auth adapter, the DB seeder, per-tenant theming, the static-demo twin — imports it THROUGH here, so
4
+ * WHERE an app keeps its seed is the app's business. SSSB's reference app keeps its in a workspace
5
+ * package (`@app/seed`); this app keeps its in `src/seed`. Neither can see the other's.
6
+ */
7
+ export * from '../seed'