@sssb/kit 0.3.0 → 0.5.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 (67) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/email-message.ts +30 -0
  4. package/src/adapters/fake/analytics.ts +1 -1
  5. package/src/adapters/fake/auth.ts +31 -4
  6. package/src/adapters/fake/data-dir.ts +32 -2
  7. package/src/adapters/fake/db.ts +4 -2
  8. package/src/adapters/fake/email.ts +2 -0
  9. package/src/adapters/real/absent.ts +13 -0
  10. package/src/adapters/real/accept-invite-form.tsx +86 -21
  11. package/src/adapters/real/analytics.ts +30 -3
  12. package/src/adapters/real/auth.ts +82 -20
  13. package/src/adapters/real/contract-postgres.ts +15 -11
  14. package/src/adapters/real/db-port.ts +3 -2
  15. package/src/adapters/real/email.ts +2 -0
  16. package/src/adapters/real/index.ts +49 -12
  17. package/src/adapters/real/jobs-in-process.ts +32 -14
  18. package/src/adapters/real/jobs.ts +6 -3
  19. package/src/adapters/real/migrate-handler.ts +3 -1
  20. package/src/adapters/real/no-analytics.ts +17 -0
  21. package/src/adapters/real/optional-ports.ts +35 -1
  22. package/src/adapters/real/rds-data-codec.ts +88 -4
  23. package/src/adapters/real/rds-data-emulator.ts +12 -4
  24. package/src/adapters/real/s3-storage.ts +7 -1
  25. package/src/adapters/real/sign-in-form.tsx +29 -13
  26. package/src/adapters/real/storage-settings.ts +37 -0
  27. package/src/adapters/real/storage.ts +65 -0
  28. package/src/authz/app-exemptions.ts +79 -9
  29. package/src/authz/route-scan.ts +626 -55
  30. package/src/components/auth/accept-invite-screen.tsx +5 -1
  31. package/src/components/auth/people-picker.tsx +20 -2
  32. package/src/components/profile-screen.tsx +27 -2
  33. package/src/core/inbound-email.ts +41 -6
  34. package/src/cutover/rows.json +13 -1
  35. package/src/db/audit.ts +2 -2
  36. package/src/db/family-suite.ts +42 -0
  37. package/src/db/family.ts +91 -0
  38. package/src/db/jobs.ts +19 -9
  39. package/src/db/keyset.ts +19 -30
  40. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  41. package/src/db/notifications.ts +2 -2
  42. package/src/db/rls-coverage.ts +51 -17
  43. package/src/db/rls-proof-runner.ts +3 -2
  44. package/src/db/schedules.ts +11 -4
  45. package/src/db/webhooks.ts +4 -4
  46. package/src/demo-static/actor-drivers.ts +8 -2
  47. package/src/demo-static/email-html.ts +9 -0
  48. package/src/demo-static/tour/use-tours.tsx +8 -2
  49. package/src/demo-static/world.ts +76 -37
  50. package/src/email/send.ts +6 -2
  51. package/src/guide.md +26 -7
  52. package/src/i18n/messages/en.json +3 -0
  53. package/src/i18n/messages/es.json +3 -0
  54. package/src/i18n/messages.ts +3 -2
  55. package/src/ports/auth.ts +21 -2
  56. package/src/ports/db.ts +19 -0
  57. package/src/server-lib/invite.ts +34 -26
  58. package/src/server-lib/scheduled-tick.ts +5 -1
  59. package/src/server-lib/webhook-dispatch.ts +3 -0
  60. package/src/service-auth/mailgun.ts +19 -4
  61. package/src/testing/checks.json +9 -0
  62. package/src/testing/conformance/auth-provider.ts +308 -0
  63. package/src/testing/conformance/authz.ts +6 -2
  64. package/src/testing/conformance/db.ts +6 -5
  65. package/src/testing/conformance/i18n.ts +99 -5
  66. package/src/testing/conformance/suite.ts +65 -3
  67. package/src/testing/contract.ts +6 -4
@@ -5,6 +5,8 @@ import { Button, PasswordInput, Stack, Text, TextInput } from '@mantine/core'
5
5
  import { useForm } from '@mantine/form'
6
6
  import { useState } from 'react'
7
7
 
8
+ import { sameOriginPath } from '../../core/same-origin-path'
9
+
8
10
  /**
9
11
  * Clerk-headless credential form (ADR-0003) using @clerk/nextjs v7's signals API
10
12
  * (signIn.password → status → finalize). MFA verification (status 'needs_second_factor') is a
@@ -12,6 +14,10 @@ import { useState } from 'react'
12
14
  *
13
15
  * AUTHORED — CUTOVER (`auth-dev`): never run against a real Clerk instance.
14
16
  * Lives in packages/kit/src/adapters because it imports the vendor SDK; the SignInScreen renders it as a slot.
17
+ *
18
+ * `returnTo` usually comes from the URL, so the form goes there only when `sameOriginPath` accepts it, and to `/`
19
+ * otherwise: a page that forgot to check it must not turn sign-in into an open redirect (`/\evil.example` and
20
+ * `/<tab>/evil.example` pass a `startsWith('/')` check and leave the origin).
15
21
  */
16
22
  export function RealSignInForm({ labels, returnTo }: { labels: SignInLabels; returnTo: string }) {
17
23
  const { signIn, fetchStatus } = useSignIn()
@@ -20,18 +26,24 @@ export function RealSignInForm({ labels, returnTo }: { labels: SignInLabels; ret
20
26
 
21
27
  const submit = form.onSubmit(async (values) => {
22
28
  setFormError(null)
23
- const { error } = await signIn.password({ identifier: values.email, password: values.password })
24
- if (error) {
25
- setFormError(labels.genericError)
26
- return
27
- }
28
- if (signIn.status === 'complete') {
29
- const finalized = await signIn.finalize()
30
- if (finalized.error) setFormError(labels.genericError)
31
- else window.location.assign(returnTo)
32
- } else if (signIn.status === 'needs_second_factor') {
33
- setFormError(labels.mfaNotImplemented)
34
- } else {
29
+ // A Clerk call that throws (the network, not a refused password) is shown as the same generic error, never left
30
+ // as an unhandled rejection with nothing on screen.
31
+ try {
32
+ const { error } = await signIn.password({ identifier: values.email, password: values.password })
33
+ if (error) {
34
+ setFormError(labels.genericError)
35
+ return
36
+ }
37
+ if (signIn.status === 'complete') {
38
+ const finalized = await signIn.finalize()
39
+ if (finalized.error) setFormError(labels.genericError)
40
+ else window.location.assign(sameOriginPath(returnTo) ?? '/')
41
+ } else if (signIn.status === 'needs_second_factor') {
42
+ setFormError(labels.mfaNotImplemented)
43
+ } else {
44
+ setFormError(labels.genericError)
45
+ }
46
+ } catch {
35
47
  setFormError(labels.genericError)
36
48
  }
37
49
  })
@@ -44,7 +56,11 @@ export function RealSignInForm({ labels, returnTo }: { labels: SignInLabels; ret
44
56
  <Button type="submit" loading={fetchStatus === 'fetching'}>
45
57
  {labels.submit}
46
58
  </Button>
47
- {formError ? <Text c="red.8">{formError}</Text> : null}
59
+ {formError ? (
60
+ <Text c="red.8" role="alert">
61
+ {formError}
62
+ </Text>
63
+ ) : null}
48
64
  </Stack>
49
65
  </form>
50
66
  )
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The values of `STORAGE_PROVIDER=s3-compatible` that choose behaviour, checked in one place that loads no SDK: the
3
+ * adapter (./storage.ts) checks them as it is built, and `assertRealEnv` (./index.ts) checks them too, so
4
+ * `sssb check-real-env` refuses what the server would refuse at boot. Each failure names its variable and, so that a
5
+ * secret pasted into the wrong one never reaches a log, never repeats a value that could hold one (the endpoint).
6
+ */
7
+
8
+ /** `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `none` if it does not. */
9
+ export function parseUploadTarget(value: string): 'post' | 'none' {
10
+ if (value === 'post' || value === 'none') return value
11
+ throw new Error(`STORAGE_UPLOAD_TARGET must be post or none (got "${value}")`)
12
+ }
13
+
14
+ /** `STORAGE_FORCE_PATH_STYLE`: `true`, `false`, or unset (an empty value counts as unset) for the SDK's own addressing. */
15
+ export function parseForcePathStyle(value: string | undefined): boolean | undefined {
16
+ if (value === undefined || value === '') return undefined
17
+ if (value === 'true') return true
18
+ if (value === 'false') return false
19
+ throw new Error(`STORAGE_FORCE_PATH_STYLE must be true or false when set (got "${value}")`)
20
+ }
21
+
22
+ /** `STORAGE_ENDPOINT`: an http(s) URL carrying no credentials (the key pair has settings of its own). */
23
+ export function assertEndpoint(endpoint: string): void {
24
+ let url: URL
25
+ try {
26
+ url = new URL(endpoint)
27
+ } catch {
28
+ throw new Error('STORAGE_ENDPOINT must be an http(s) URL')
29
+ }
30
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
31
+ throw new Error('STORAGE_ENDPOINT must be an http(s) URL')
32
+ if (url.username !== '' || url.password !== '') {
33
+ throw new Error(
34
+ 'STORAGE_ENDPOINT must not carry a user or password: the key pair is STORAGE_ACCESS_KEY_ID and STORAGE_SECRET_ACCESS_KEY',
35
+ )
36
+ }
37
+ }
@@ -1,5 +1,6 @@
1
1
  import type { StoragePort } from '../../ports/storage'
2
2
  import { createS3Storage } from './s3-storage'
3
+ import { assertEndpoint, parseForcePathStyle, parseUploadTarget } from './storage-settings'
3
4
 
4
5
  /**
5
6
  * The storage the real-mode registry builds (`./index.ts`): the published S3 adapter (`./s3-storage.ts`,
@@ -8,3 +9,67 @@ import { createS3Storage } from './s3-storage'
8
9
  export function createRealStorage(bucket: string, region: string): StoragePort {
9
10
  return createS3Storage({ bucket, region })
10
11
  }
12
+
13
+ /**
14
+ * Where an S3-compatible store (Cloudflare R2, MinIO, Backblaze B2) is, as `STORAGE_PROVIDER=s3-compatible` reads it
15
+ * (./optional-ports.ts). The two strings that choose behaviour arrive as the environment gave them and are checked
16
+ * here, so a wrong value fails at boot naming its variable.
17
+ */
18
+ export interface CompatibleStorageSettings {
19
+ /** `STORAGE_BUCKET`. */
20
+ bucket: string
21
+ /** `STORAGE_ENDPOINT`: the store's S3 API endpoint, as an http(s) URL. */
22
+ endpoint: string
23
+ /** `STORAGE_REGION`: what the store signs requests for (R2 takes `auto`). Not `AWS_REGION`, which Lambda reserves. */
24
+ region: string
25
+ /** `STORAGE_ACCESS_KEY_ID`. Not `AWS_ACCESS_KEY_ID`, which Lambda reserves for the function's own role. */
26
+ accessKeyId: string
27
+ /** `STORAGE_SECRET_ACCESS_KEY`. */
28
+ secretAccessKey: string
29
+ /** `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `none` if it does not. */
30
+ uploadTarget: string
31
+ /** `STORAGE_FORCE_PATH_STYLE`: `true`, `false`, or unset (empty counts as unset) for the SDK's own addressing. */
32
+ forcePathStyle?: string | undefined
33
+ }
34
+
35
+ /**
36
+ * The storage port on an S3-compatible store: the same adapter as `createRealStorage`, pointed at `endpoint` with the
37
+ * store's own key pair. Everything but the upload target is S3's API, which these stores implement (ADR-0015, section
38
+ * 6 lists what R2 does). `createUploadTarget` is an S3 presigned POST, which R2 does not accept, so it follows
39
+ * `uploadTarget`: with `none` it fails naming the setting rather than minting a URL the store would refuse.
40
+ *
41
+ * AUTHORED — CUTOVER (`storage-compatible-store`, `storage-compatible-credentials`, and the live round trip
42
+ * `storage-compatible-live`): typechecked and run with the SDK's transport replaced, never against a real store.
43
+ */
44
+ export function createCompatibleStorage(settings: CompatibleStorageSettings): StoragePort {
45
+ const { bucket, endpoint, region, accessKeyId, secretAccessKey, uploadTarget } = settings
46
+ const target = parseUploadTarget(uploadTarget)
47
+ const forcePathStyle = parseForcePathStyle(settings.forcePathStyle)
48
+ assertEndpoint(endpoint)
49
+
50
+ const s3 = createS3Storage({
51
+ bucket,
52
+ region,
53
+ endpoint,
54
+ credentials: { accessKeyId, secretAccessKey },
55
+ forcePathStyle,
56
+ // The SDK's default (since v3.729, `WHEN_SUPPORTED`) puts a CRC32 checksum on every PutObject, which stores
57
+ // older than that default can reject; Cloudflare tells R2 users to ask for checksums only where an operation
58
+ // requires one. `WHEN_REQUIRED` does that, and no more: DeleteObjects requires one, so it still carries CRC32
59
+ // and no Content-MD5, which a store that wants MD5 would refuse (the live row, `storage-compatible-live`, runs
60
+ // `delete` against the real store for that). AWS accepts both, so the `s3` choice keeps the default.
61
+ requestChecksumCalculation: 'WHEN_REQUIRED',
62
+ responseChecksumValidation: 'WHEN_REQUIRED',
63
+ })
64
+ if (target === 'post') return s3
65
+ return {
66
+ ...s3,
67
+ createUploadTarget: async () => {
68
+ throw new Error(
69
+ 'storage createUploadTarget: STORAGE_UPLOAD_TARGET=none, so this store is declared not to accept a ' +
70
+ 'presigned POST (Cloudflare R2 does not). Set STORAGE_UPLOAD_TARGET=post for a store that does, ' +
71
+ 'such as MinIO, or upload another way.',
72
+ )
73
+ },
74
+ }
75
+ }
@@ -1,8 +1,20 @@
1
- import { existsSync } from 'node:fs'
1
+ import { existsSync, statSync } from 'node:fs'
2
2
  import { createRequire } from 'node:module'
3
3
  import path from 'node:path'
4
4
  import { FRAMEWORK_POLICY, isGate } from './route-policy'
5
- import { type Exemption, type ScannedRoute, type ScanRoot, type ScanPolicy, judge, scanRoutes } from './route-scan'
5
+ import {
6
+ type Exemption,
7
+ type ScannedAction,
8
+ type ScannedRoute,
9
+ type ScanRoot,
10
+ type ScanPolicy,
11
+ judge,
12
+ judgeServerAction,
13
+ scanRoutes,
14
+ scanServerActions,
15
+ serverActionFilesOutsideSrc,
16
+ unreadRouteFiles,
17
+ } from './route-scan'
6
18
 
7
19
  /**
8
20
  * AN APP'S OWN AUTHORIZATION EXEMPTIONS, and the per-app authorization scan that applies them (the conformance
@@ -180,17 +192,38 @@ export interface AppScan {
180
192
  root: ScanRoot
181
193
  /** Every route file under the app's `src/app`, mutating or not. Empty when there is no `src/app`. */
182
194
  routes: ScannedRoute[]
183
- /** One message per mutating handler that fails, `<root>: <rel> <VERB> …why`. */
195
+ /** Every Server Action under the app's `src`. */
196
+ actions: ScannedAction[]
197
+ /**
198
+ * One message per mutating handler or Server Action that fails (`<root>: <rel> <VERB> …why`), and one for each
199
+ * Pages Router API directory the app has, which the scan cannot read.
200
+ */
184
201
  failures: string[]
185
202
  /** The app's exemptions file: malformed, colliding or stale entries. */
186
203
  exemptionProblems: string[]
187
204
  }
188
205
 
206
+ /** Whether `file` is a directory (through a link); false when it is missing or a file. */
207
+ function isDirectory(file: string): boolean {
208
+ try {
209
+ return statSync(file).isDirectory()
210
+ } catch {
211
+ return false
212
+ }
213
+ }
214
+
215
+ /** Where Next looks for Pages Router API routes: `pages/api` beside `src`, or inside it. */
216
+ const PAGES_API_DIRS = ['pages/api', 'src/pages/api']
217
+
189
218
  /**
190
219
  * The authorization scan over ONE app: every `route.*` under `<appDir>/src/app` (Next serves one from anywhere
191
- * there, so not only `api/`), judged against the framework's policy plus the app's own exemptions, which are
192
- * measured from `<appDir>/src/app/api` (so a mutating route outside `api/` can match no exemption and must call
193
- * `authorize(...)` itself). Re-exported handlers are followed with the app's `tsconfig.json` (or `jsconfig.json`).
220
+ * there, so not only `api/`, and through a symbolic link too), judged against the framework's policy plus the app's
221
+ * own exemptions, which are measured from `<appDir>/src/app/api` (so a mutating route outside `api/` can match no
222
+ * exemption and must call `authorize(...)` itself). Every Server Action under `<appDir>/src` (a `'use server'` file's
223
+ * exports, and each function whose body opens with `'use server'`) is judged as a POST is, and can match no
224
+ * exemption. A Pages Router API directory fails outright: SSSB apps are App Router, and the scan reads no
225
+ * `pages/api` handler. So does a root-level `app/` directory (Next serves it instead of `src/app`), and a file under
226
+ * `src/app` named `route.<ext>` for an extension the scan does not read (`pageExtensions` is not read). Re-exported handlers are followed with the app's `tsconfig.json` (or `jsconfig.json`).
194
227
  */
195
228
  export async function scanApp(appDir: string): Promise<AppScan> {
196
229
  const name = path.basename(appDir)
@@ -206,13 +239,50 @@ export async function scanApp(appDir: string): Promise<AppScan> {
206
239
  const routes = existsSync(root.dir) ? scanRoutes([root]) : []
207
240
  const mutating = routes.filter((route) => route.handlers.length > 0)
208
241
  const policy = policyWithApp(exemptions)
209
- const failures = mutating.flatMap((route) =>
210
- route.handlers.flatMap((handler) => judge(route, handler, policy) ?? []),
211
- )
242
+ const srcDir = path.join(appDir, 'src')
243
+ const actions = existsSync(srcDir) ? scanServerActions({ ...root, dir: srcDir, exemptDir: srcDir }) : []
244
+ const outsideUnreadable = new Map<string, string>()
245
+ const outsideActionFiles = serverActionFilesOutsideSrc(appDir, outsideUnreadable)
246
+ const failures = [
247
+ ...mutating.flatMap((route) => route.handlers.flatMap((handler) => judge(route, handler, policy) ?? [])),
248
+ ...actions.flatMap((action) => judgeServerAction(action) ?? []),
249
+ ...(isDirectory(path.join(appDir, 'app'))
250
+ ? [
251
+ `${name}: app/ is a root-level App Router directory. Next serves it and ignores src/app when both ` +
252
+ `exist, and the authorization scan reads only src/app, so no route in app/ is checked. Keep the ` +
253
+ `app's routes in src/app.`,
254
+ ]
255
+ : []),
256
+ ...(existsSync(root.dir) ? unreadRouteFiles(root.dir) : []).map(
257
+ (file) =>
258
+ `${name}: ${path.relative(appDir, file).split(path.sep).join('/')} is named like a route, but the ` +
259
+ `authorization scan reads only route.ts, route.tsx, route.js, route.jsx and route.mjs. If Next serves it ` +
260
+ `(a pageExtensions entry), nothing checked it: rename it to one of those, or rename it to something not ` +
261
+ `named route.`,
262
+ ),
263
+ ...[...outsideUnreadable].map(
264
+ ([dir, code]) =>
265
+ `${name}: ${path.relative(appDir, dir).split(path.sep).join('/') || '.'} could not be read (${code}), so ` +
266
+ `a Server Action in it would go unchecked. Make it readable to the user running the check.`,
267
+ ),
268
+ ...outsideActionFiles.map(
269
+ (file) =>
270
+ `${name}: ${path.relative(appDir, file).split(path.sep).join('/')} declares Server Actions outside src, ` +
271
+ `where the authorization scan does not judge them. Move them under src. (Actions a workspace package ` +
272
+ `exports are not read either.)`,
273
+ ),
274
+ ...PAGES_API_DIRS.filter((dir) => existsSync(path.join(appDir, dir))).map(
275
+ (dir) =>
276
+ `${name}: ${dir} is a Pages Router API directory. SSSB apps are App Router, and the authorization scan ` +
277
+ `reads only route handlers under src/app and Server Actions, so nothing in ${dir} is checked. Move ` +
278
+ `each handler to a route.ts under src/app/api.`,
279
+ ),
280
+ ]
212
281
  const label = `${name}/${APP_EXEMPTIONS_FILE}`
213
282
  return {
214
283
  root,
215
284
  routes,
285
+ actions,
216
286
  failures,
217
287
  exemptionProblems: [
218
288
  ...problems,