@sssb/create 0.0.0 → 0.3.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/bin/create.js +136 -0
- package/package.json +26 -5
- package/src/add-app.js +165 -0
- package/src/args.js +270 -0
- package/src/files.js +677 -0
- package/src/generate.js +612 -0
- package/src/json.js +60 -0
- package/src/signals.js +72 -0
- package/src/template.js +496 -0
- package/src/yaml.js +17 -0
- package/template/app/DEMO-SIZE.md +55 -0
- package/template/app/config/app.ts +17 -0
- package/template/app/config/params.ts +85 -0
- package/template/app/infra/README.md +85 -0
- package/template/app/infra/app.ts +45 -0
- package/template/app/infra/cdk.json +9 -0
- package/template/app/infra/lib/tags.ts +35 -0
- package/template/app/infra/package.json +20 -0
- package/template/app/infra/tsconfig.json +13 -0
- package/template/app/messages/en.json +21 -0
- package/template/app/messages/es.json +21 -0
- package/template/app/next.config.ts +9 -0
- package/template/app/package.json +40 -0
- package/template/app/playwright.config.ts +50 -0
- package/template/app/playwright.demo.config.ts +10 -0
- package/template/app/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx +61 -0
- package/template/app/src/app/[locale]/(protected)/dashboard/page.tsx +21 -0
- package/template/app/src/app/[locale]/(protected)/header-glue.tsx +59 -0
- package/template/app/src/app/[locale]/(protected)/layout.tsx +43 -0
- package/template/app/src/app/[locale]/layout.tsx +63 -0
- package/template/app/src/app/[locale]/page.tsx +9 -0
- package/template/app/src/app/[locale]/signin/page.tsx +55 -0
- package/template/app/src/app/[locale]/signin/picker-glue.tsx +21 -0
- package/template/app/src/app/api/auth/dev-signin/route.ts +12 -0
- package/template/app/src/app/api/auth/org/route.ts +10 -0
- package/template/app/src/app/api/auth/signout/route.ts +9 -0
- package/template/app/src/app/api/items/route.ts +59 -0
- package/template/app/src/app/api/respond.ts +13 -0
- package/template/app/src/app/api/simulator/[...path]/route.ts +23 -0
- package/template/app/src/app/api/webhooks/cron/route.test.ts +59 -0
- package/template/app/src/app/api/webhooks/cron/route.ts +16 -0
- package/template/app/src/app/layout.tsx +7 -0
- package/template/app/src/app-config/abilities.ts +86 -0
- package/template/app/src/app-config/actors.ts +13 -0
- package/template/app/src/app-config/audit.ts +9 -0
- package/template/app/src/app-config/db/migrations/1001_items.ts +37 -0
- package/template/app/src/app-config/db/migrations/1002_items_keyset_index.ts +29 -0
- package/template/app/src/app-config/db/migrations/index.ts +13 -0
- package/template/app/src/app-config/db/rls-proofs.ts +186 -0
- package/template/app/src/app-config/db/schema.ts +23 -0
- package/template/app/src/app-config/digest.ts +10 -0
- package/template/app/src/app-config/identity.ts +8 -0
- package/template/app/src/app-config/inbound-email.ts +10 -0
- package/template/app/src/app-config/jobs.ts +28 -0
- package/template/app/src/app-config/messages.ts +18 -0
- package/template/app/src/app-config/notifications.ts +31 -0
- package/template/app/src/app-config/preset-operations.ts +9 -0
- package/template/app/src/app-config/presets.ts +18 -0
- package/template/app/src/app-config/seed.ts +7 -0
- package/template/app/src/app-config/simulator.ts +17 -0
- package/template/app/src/app-config/tours.ts +14 -0
- package/template/app/src/app-config/webhooks.ts +13 -0
- package/template/app/src/components/dashboard-screen.tsx +26 -0
- package/template/app/src/components/items-card.tsx +106 -0
- package/template/app/src/components/welcome-screen.tsx +20 -0
- package/template/app/src/demo-static/app.tsx +77 -0
- package/template/app/src/demo-static/index.html +12 -0
- package/template/app/src/demo-static/main.tsx +40 -0
- package/template/app/src/domain/db/items.ts +37 -0
- package/template/app/src/proxy.test.ts +44 -0
- package/template/app/src/proxy.ts +18 -0
- package/template/app/src/seed/index.ts +93 -0
- package/template/app/src/sssb.conformance.test.ts +7 -0
- package/template/app/src/styles/index.css +1 -0
- package/template/app/tests/catalog.ts +15 -0
- package/template/app/tests/contract/rls-contract.test.ts +14 -0
- package/template/app/tests/demo-static/static-shell.spec.ts +32 -0
- package/template/app/tests/e2e/items.spec.ts +102 -0
- package/template/app/tests/e2e/simulator.spec.ts +40 -0
- package/template/app/tsconfig.json +29 -0
- package/template/app/vite.demo.config.ts +8 -0
- package/template/guide.md +132 -0
- package/template/meta.json +633 -0
- package/template/root/_dot_editorconfig +12 -0
- package/template/root/_dot_husky/commit-msg +1 -0
- package/template/root/_dot_husky/pre-commit +1 -0
- package/template/root/_dot_nvmrc +1 -0
- package/template/root/_dot_prettierrc.json +5 -0
- package/template/root/commitlint.config.mjs +1 -0
- package/README.md +0 -3
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import '@mantine/core/styles.css'
|
|
2
|
+
import '@/styles/index.css'
|
|
3
|
+
|
|
4
|
+
import { ColorSchemeScript, MantineProvider, mantineHtmlProps } from '@mantine/core'
|
|
5
|
+
import { hasLocale, NextIntlClientProvider } from 'next-intl'
|
|
6
|
+
import { setRequestLocale } from 'next-intl/server'
|
|
7
|
+
import { notFound } from 'next/navigation'
|
|
8
|
+
import type { ReactNode } from 'react'
|
|
9
|
+
import { auth, isDemoMode, isSimulated } from '@sssb/kit/adapters/index'
|
|
10
|
+
import { DemoBadge } from '@sssb/kit/components/demo-badge'
|
|
11
|
+
import { routing } from '@sssb/kit/i18n/routing'
|
|
12
|
+
import { getTenantTheme } from '@sssb/kit/theme'
|
|
13
|
+
import { tenants } from '@/seed'
|
|
14
|
+
|
|
15
|
+
// The Simulator panel, in simulated mode only: a real build never renders it, so no page there loads its client code.
|
|
16
|
+
// Its server side is `src/app/api/simulator/[...path]/route.ts`.
|
|
17
|
+
async function SimulatorChrome({ locale, children }: { locale: string; children: ReactNode }) {
|
|
18
|
+
if (!isSimulated) return children
|
|
19
|
+
const { SimulatorHost } = await import('@sssb/kit/components/simulator/simulator-host')
|
|
20
|
+
return <SimulatorHost locale={locale}>{children}</SimulatorHost>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const metadata = {
|
|
24
|
+
title: 'Starter',
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function generateStaticParams() {
|
|
28
|
+
return routing.locales.map((locale) => ({ locale }))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export default async function LocaleLayout({
|
|
32
|
+
children,
|
|
33
|
+
params,
|
|
34
|
+
}: {
|
|
35
|
+
children: ReactNode
|
|
36
|
+
params: Promise<{ locale: string }>
|
|
37
|
+
}) {
|
|
38
|
+
const { locale } = await params
|
|
39
|
+
if (!hasLocale(routing.locales, locale)) notFound()
|
|
40
|
+
setRequestLocale(locale)
|
|
41
|
+
|
|
42
|
+
// The theming seam (ADR-0005): the ACTIVE tenant drives the theme. Signed-out pages fall back to
|
|
43
|
+
// this app's FIRST seeded tenant rather than SSSB's DEFAULT_TENANT_SLUG, which names the
|
|
44
|
+
// world of SSSB's reference app — see the seam notes in SSSB's adoption guide.
|
|
45
|
+
const user = await auth.getCurrentUser()
|
|
46
|
+
const theme = getTenantTheme(user?.tenantSlug ?? tenants[0]!.slug)
|
|
47
|
+
|
|
48
|
+
return (
|
|
49
|
+
<html lang={locale} {...mantineHtmlProps}>
|
|
50
|
+
<head>
|
|
51
|
+
<ColorSchemeScript />
|
|
52
|
+
</head>
|
|
53
|
+
<body>
|
|
54
|
+
<NextIntlClientProvider>
|
|
55
|
+
<MantineProvider theme={theme}>
|
|
56
|
+
<SimulatorChrome locale={locale}>{children}</SimulatorChrome>
|
|
57
|
+
{isDemoMode ? <DemoBadge /> : null}
|
|
58
|
+
</MantineProvider>
|
|
59
|
+
</NextIntlClientProvider>
|
|
60
|
+
</body>
|
|
61
|
+
</html>
|
|
62
|
+
)
|
|
63
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { setRequestLocale } from 'next-intl/server'
|
|
2
|
+
import { WelcomeScreen } from '@/components/welcome-screen'
|
|
3
|
+
|
|
4
|
+
// Route files are thin wrappers around router-agnostic screens (ADR-0006).
|
|
5
|
+
export default async function HomePage({ params }: { params: Promise<{ locale: string }> }) {
|
|
6
|
+
const { locale } = await params
|
|
7
|
+
setRequestLocale(locale)
|
|
8
|
+
return <WelcomeScreen dashboardHref={`/${locale}/dashboard`} />
|
|
9
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { Route } from 'next'
|
|
2
|
+
import { getTranslations, setRequestLocale } from 'next-intl/server'
|
|
3
|
+
import { redirect } from 'next/navigation'
|
|
4
|
+
import { auth, isSimulated } from '@sssb/kit/adapters/index'
|
|
5
|
+
import { listAllPeople } from '@sssb/kit/adapters/fake/auth'
|
|
6
|
+
import { SignInScreen } from '@sssb/kit/components/auth/sign-in-screen'
|
|
7
|
+
import { findTenant } from '@/seed'
|
|
8
|
+
import { PickerGlue } from './picker-glue'
|
|
9
|
+
|
|
10
|
+
export default async function SignInPage({
|
|
11
|
+
params,
|
|
12
|
+
searchParams,
|
|
13
|
+
}: {
|
|
14
|
+
params: Promise<{ locale: string }>
|
|
15
|
+
searchParams: Promise<{ returnTo?: string }>
|
|
16
|
+
}) {
|
|
17
|
+
const { locale } = await params
|
|
18
|
+
setRequestLocale(locale)
|
|
19
|
+
const { returnTo } = await searchParams
|
|
20
|
+
// Only same-origin, path-shaped targets; anything else falls back to the dashboard.
|
|
21
|
+
const safe = returnTo && returnTo.startsWith('/') && !returnTo.startsWith('//')
|
|
22
|
+
const target = (safe ? returnTo : `/${locale}/dashboard`) as Route
|
|
23
|
+
|
|
24
|
+
if (await auth.getCurrentUser()) redirect(target)
|
|
25
|
+
|
|
26
|
+
if (!isSimulated) {
|
|
27
|
+
const [{ RealSignInForm }, t] = await Promise.all([
|
|
28
|
+
import('@sssb/kit/adapters/real/sign-in-form'),
|
|
29
|
+
getTranslations('auth'),
|
|
30
|
+
])
|
|
31
|
+
const labels = {
|
|
32
|
+
email: t('emailLabel'),
|
|
33
|
+
password: t('passwordLabel'),
|
|
34
|
+
submit: t('signInButton'),
|
|
35
|
+
genericError: t('signInError'),
|
|
36
|
+
mfaNotImplemented: t('mfaNotImplemented'),
|
|
37
|
+
}
|
|
38
|
+
return <SignInScreen body={<RealSignInForm returnTo={target} labels={labels} />} />
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// A person with no membership has no role to sign in as, so the picker leaves them out.
|
|
42
|
+
const people = listAllPeople().flatMap((p) => {
|
|
43
|
+
const membership = p.memberships[0]
|
|
44
|
+
if (!membership) return []
|
|
45
|
+
return [
|
|
46
|
+
{
|
|
47
|
+
id: p.id,
|
|
48
|
+
name: p.name,
|
|
49
|
+
role: membership.role,
|
|
50
|
+
tenantName: findTenant(p.tenantSlug)?.name ?? p.tenantSlug,
|
|
51
|
+
},
|
|
52
|
+
]
|
|
53
|
+
})
|
|
54
|
+
return <SignInScreen body={<PickerGlue people={people} returnTo={target} />} />
|
|
55
|
+
}
|
|
@@ -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,59 @@
|
|
|
1
|
+
import { auth, db } from '@sssb/kit/adapters/index'
|
|
2
|
+
import { authorize } from '@sssb/kit/authz/authorize'
|
|
3
|
+
import { clampKeysetLimit } from '@sssb/kit/core/keyset'
|
|
4
|
+
import { parseDbKeysetCursor } from '@sssb/kit/db/keyset'
|
|
5
|
+
import { orgIdForSlug } from '@sssb/kit/db/org-lookup'
|
|
6
|
+
import { tenantIdForSlug } from '@sssb/kit/db/tenant-lookup'
|
|
7
|
+
import { listItems } from '@/domain/db/items'
|
|
8
|
+
import { withPortErrors } from '../respond'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The app's only product route. Items are tenant-scoped by RLS (the hostile-isolation boundary) AND
|
|
12
|
+
* filtered to the active org (the team boundary — an app-level WHERE, since org membership is enforced
|
|
13
|
+
* at the auth port; ADR-0004). Every query runs inside withTenant.
|
|
14
|
+
*
|
|
15
|
+
* GET lists ONE PAGE (`?cursor=<opaque>&limit=<n>`); both parameters are untrusted input. An unreadable
|
|
16
|
+
* cursor is a 400, never a silent first page, and the page size is clamped on the server: the query
|
|
17
|
+
* string may ask, it does not decide. A cursor carries no scope, since the tenant and the org are
|
|
18
|
+
* resolved from the session on every page.
|
|
19
|
+
*/
|
|
20
|
+
export async function GET(request: Request): Promise<Response> {
|
|
21
|
+
return withPortErrors(async () => {
|
|
22
|
+
const user = await auth.requireUser()
|
|
23
|
+
const params = new URL(request.url).searchParams
|
|
24
|
+
const cursor = parseDbKeysetCursor(params.get('cursor'))
|
|
25
|
+
if (cursor.kind === 'invalid') return Response.json({ error: 'invalid-cursor' }, { status: 400 })
|
|
26
|
+
const tenantId = await tenantIdForSlug(db, user.tenantSlug)
|
|
27
|
+
if (!tenantId) return Response.json({ error: 'unknown tenant' }, { status: 404 })
|
|
28
|
+
const orgId = await orgIdForSlug(db, tenantId, user.orgSlug)
|
|
29
|
+
if (!orgId) return Response.json({ error: 'unknown org' }, { status: 404 })
|
|
30
|
+
const { items, nextCursor } = await listItems(db, tenantId, orgId, {
|
|
31
|
+
after: cursor.position ?? null,
|
|
32
|
+
limit: clampKeysetLimit(params.get('limit')),
|
|
33
|
+
})
|
|
34
|
+
return Response.json({ items, nextCursor })
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function POST(request: Request): Promise<Response> {
|
|
39
|
+
return withPortErrors(async () => {
|
|
40
|
+
const user = await auth.requireUser()
|
|
41
|
+
const { title } = (await request.json()) as { title: string }
|
|
42
|
+
if (!title?.trim()) return Response.json({ error: 'empty item' }, { status: 400 })
|
|
43
|
+
const tenantId = await tenantIdForSlug(db, user.tenantSlug)
|
|
44
|
+
if (!tenantId) return Response.json({ error: 'unknown tenant' }, { status: 404 })
|
|
45
|
+
const orgId = await orgIdForSlug(db, tenantId, user.orgSlug)
|
|
46
|
+
if (!orgId) return Response.json({ error: 'unknown org' }, { status: 404 })
|
|
47
|
+
// The authorization choke point: restricted members may read items but not author them.
|
|
48
|
+
// Throws ForbiddenError → 403 via withPortErrors.
|
|
49
|
+
authorize(user, orgId, 'create', { type: 'Item', orgId })
|
|
50
|
+
const item = await db.withTenant(tenantId, (trx) =>
|
|
51
|
+
trx
|
|
52
|
+
.insertInto('items')
|
|
53
|
+
.values({ tenant_id: tenantId, org_id: orgId, title: title.trim(), created_by_user_id: user.id })
|
|
54
|
+
.returning(['id', 'title'])
|
|
55
|
+
.executeTakeFirstOrThrow(),
|
|
56
|
+
)
|
|
57
|
+
return Response.json({ item })
|
|
58
|
+
})
|
|
59
|
+
}
|
|
@@ -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,23 @@
|
|
|
1
|
+
import { isSimulated } from '@sssb/kit/adapters/index'
|
|
2
|
+
import type { SimulatorRouteContext } from '@sssb/kit/server-lib/simulator-api'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The Simulator panel's server side on this app's own `pnpm dev`: every `/api/simulator/<path>` call the panel makes
|
|
6
|
+
* lands here and is answered by SSSB's `simulatorApi` (People, Mail, and Jobs with the world clock). A route file of
|
|
7
|
+
* this app's own beside it, `api/simulator/<name>/route.ts`, still wins for its path.
|
|
8
|
+
*
|
|
9
|
+
* Each handler opens with the simulated-mode 404 and loads SSSB's handler only after it, so a real build never loads
|
|
10
|
+
* it. That first line is also the gate the authorization scan checks: these handlers are
|
|
11
|
+
* exempt from `authorize(...)` as a simulated-world surface, and only while each one opens with it.
|
|
12
|
+
*/
|
|
13
|
+
export async function GET(request: Request, context: SimulatorRouteContext): Promise<Response> {
|
|
14
|
+
if (!isSimulated) return new Response(null, { status: 404 })
|
|
15
|
+
const { simulatorApi } = await import('@sssb/kit/server-lib/simulator-api')
|
|
16
|
+
return simulatorApi(request, context)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function POST(request: Request, context: SimulatorRouteContext): Promise<Response> {
|
|
20
|
+
if (!isSimulated) return new Response(null, { status: 404 })
|
|
21
|
+
const { simulatorApi } = await import('@sssb/kit/server-lib/simulator-api')
|
|
22
|
+
return simulatorApi(request, context)
|
|
23
|
+
}
|
|
@@ -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,16 @@
|
|
|
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 the shared
|
|
6
|
+
* secret in `x-sssb-webhook-secret` (or `Authorization: Bearer`, which a deployment's CloudFront does not pass on); a
|
|
7
|
+
* request without that secret is an opaque 401 before anything runs.
|
|
8
|
+
* The body is ignored and the whole job is SSSB's `runScheduledTick`: drain the due schedules and the due webhook
|
|
9
|
+
* deliveries. The Simulator's Jobs tab runs what is due only when asked, so without this route nothing ticks SSSB's
|
|
10
|
+
* scheduler on its own, in a deployment or in `pnpm dev`.
|
|
11
|
+
*
|
|
12
|
+
* Authorization is the shared-secret guard, and the handler has to BE it: the authorize() scan exempts a
|
|
13
|
+
* `webhooks/` handler (a machine caller, not a user session) only if that verb's export is a call to an imported
|
|
14
|
+
* `withWebhookSecret` (or `withMailgunSignature`), as POST is here.
|
|
15
|
+
*/
|
|
16
|
+
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,86 @@
|
|
|
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 = AppSubjectFields & { … }`).
|
|
14
|
+
* This app has NONE: every one of its subjects is scoped by the framework's own `orgId`, so there is nothing
|
|
15
|
+
* to add, and `Record<never, never>` says so. An app with fields declares them here as an interface or a type.
|
|
16
|
+
*/
|
|
17
|
+
export type AppSubjectFields = Record<never, never>
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The credential kinds, beyond SSSB's own, by which a PERSON or a MACHINE can reach this app (composed
|
|
21
|
+
* into @sssb/kit/core/abilities' `PersonCredentialKind` / `MachineCredentialKind`; SSSB's are `session`,
|
|
22
|
+
* `inbound-email` and `service-key`). This app adds none. An app with personal API tokens registers its
|
|
23
|
+
* token kind as a person credential; one with a CI identity, that as a machine credential.
|
|
24
|
+
*/
|
|
25
|
+
export type AppPersonCredentialKind = never
|
|
26
|
+
export type AppMachineCredentialKind = never
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The designated staff/operator org slug. ACTIVE membership in this org grants the `manageAll`
|
|
30
|
+
* ability-layer superpower (derived in @sssb/kit/authz/authorize.ts). It is one ordinary org WITHIN a
|
|
31
|
+
* tenant: staff powers stop at the tenant boundary and NEVER cross tenants (ADR-0004). WHICH org is
|
|
32
|
+
* the operator org is an app choice, so it lives here; it must name a real seed org (`src/seed`).
|
|
33
|
+
*/
|
|
34
|
+
export const staffOrgSlug = 'ops'
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The app-subject anchor extras for the non-throwing UI gate (canInActiveOrg). This app adds no
|
|
38
|
+
* subject fields, so there is nothing to anchor — the framework's own `orgId` anchor is enough, and
|
|
39
|
+
* the injected anchor is ignored. (The parameter stays because the framework calls it with one.)
|
|
40
|
+
*/
|
|
41
|
+
export function anchorSubjectExtras(anchor: string): AppSubjectFields {
|
|
42
|
+
void anchor // nothing to anchor: this app registers no subject fields of its own
|
|
43
|
+
return {}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The app's per-subject rules, invoked by @sssb/kit/core/abilities.ts's `default:` case (deny by default).
|
|
48
|
+
* `sameOrg` is injected by core so "the subject is org-scoped AND its org is the acting org" is
|
|
49
|
+
* defined once.
|
|
50
|
+
* - Item: read = sameOrg; create|update|delete = !restricted && sameOrg.
|
|
51
|
+
*/
|
|
52
|
+
export function appAbilityRules(
|
|
53
|
+
actor: AbilityActor,
|
|
54
|
+
action: AbilityAction,
|
|
55
|
+
subject: AbilitySubject,
|
|
56
|
+
{ sameOrg }: { sameOrg: (subject: AbilitySubject) => boolean },
|
|
57
|
+
): boolean {
|
|
58
|
+
switch (subject.type) {
|
|
59
|
+
case 'Item':
|
|
60
|
+
if (action === 'read') return sameOrg(subject)
|
|
61
|
+
if (action === 'create' || action === 'update' || action === 'delete') {
|
|
62
|
+
return !actor.restricted && sameOrg(subject)
|
|
63
|
+
}
|
|
64
|
+
return false
|
|
65
|
+
default:
|
|
66
|
+
// Deny by default: an app subject added here without a rule is denied.
|
|
67
|
+
return false
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The app's rules for MACHINE actors (@sssb/kit/core/abilities `MachineActor` — a caller that is not a
|
|
73
|
+
* person: a CI identity, an integration). This app grants machines nothing, so every machine is denied
|
|
74
|
+
* every app subject; this function is the off switch. To let one in, switch on `subject.type` and the
|
|
75
|
+
* machine's `actor.credential.kind` here, the way `appAbilityRules` does for people.
|
|
76
|
+
*/
|
|
77
|
+
export function appMachineAbilityRules(): boolean {
|
|
78
|
+
return false
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The framework's session-only subjects (inviting members, changing the org, managing webhook endpoints,
|
|
83
|
+
* accepting terms) take a browser SESSION. Here an app may widen one of them to a non-session person
|
|
84
|
+
* credential (a personal API token, say; never an inbound email). This app widens none.
|
|
85
|
+
*/
|
|
86
|
+
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,29 @@
|
|
|
1
|
+
import { Kysely } from 'kysely'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The index that makes the items list pageable (`@sssb/kit/db/keyset`).
|
|
5
|
+
*
|
|
6
|
+
* A keyset page reads `WHERE tenant_id = … AND org_id = … AND (created_at, id) < ($1, $2)
|
|
7
|
+
* ORDER BY created_at DESC, id DESC LIMIT n`. Without a matching index that is a scan of the team's whole
|
|
8
|
+
* list on EVERY page. The column order mirrors the query: the equality columns first (`tenant_id` is a
|
|
9
|
+
* predicate RLS adds to every statement, so it belongs in the index), then the ordering pair in the
|
|
10
|
+
* direction the walk reads it.
|
|
11
|
+
*
|
|
12
|
+
* A SEPARATE migration rather than an edit to 1001: an applied migration is a record, not a document to
|
|
13
|
+
* revise, and an app that already ran 1001 must be able to take this one. A brand-new table meant to be
|
|
14
|
+
* paged would carry its index in its own create migration instead.
|
|
15
|
+
*
|
|
16
|
+
* Not unique: two rows can share `(tenant_id, org_id, created_at)` (one transaction shares one `now()`),
|
|
17
|
+
* which is why `id` is in the key at all.
|
|
18
|
+
*/
|
|
19
|
+
export async function up(db: Kysely<unknown>): Promise<void> {
|
|
20
|
+
await db.schema
|
|
21
|
+
.createIndex('items_keyset_idx')
|
|
22
|
+
.on('items')
|
|
23
|
+
.columns(['tenant_id', 'org_id', 'created_at desc', 'id desc'])
|
|
24
|
+
.execute()
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function down(db: Kysely<unknown>): Promise<void> {
|
|
28
|
+
await db.schema.dropIndex('items_keyset_idx').execute()
|
|
29
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Migration } from 'kysely/migration'
|
|
2
|
+
import * as m1001 from './1001_items'
|
|
3
|
+
import * as m1002 from './1002_items_keyset_index'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The APP's migrations (the seam side of @sssb/kit/db/migrations, ADR-0012). Numbering convention: framework
|
|
7
|
+
* 0001–0999, app ≥1001. Composed into the framework registry, which Kysely runs NAME-SORTED — so these
|
|
8
|
+
* run AFTER every framework table exists. Add new app migrations here in order.
|
|
9
|
+
*/
|
|
10
|
+
export const appMigrations: Record<string, Migration> = {
|
|
11
|
+
'1001_items': m1001,
|
|
12
|
+
'1002_items_keyset_index': m1002,
|
|
13
|
+
}
|