@sssb/kit 0.4.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 (45) 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 +18 -2
  6. package/src/adapters/fake/data-dir.ts +32 -2
  7. package/src/adapters/fake/email.ts +2 -0
  8. package/src/adapters/real/accept-invite-form.tsx +32 -14
  9. package/src/adapters/real/analytics.ts +29 -2
  10. package/src/adapters/real/auth.ts +54 -18
  11. package/src/adapters/real/contract-postgres.ts +15 -11
  12. package/src/adapters/real/email.ts +2 -0
  13. package/src/adapters/real/jobs-in-process.ts +32 -14
  14. package/src/adapters/real/jobs.ts +6 -3
  15. package/src/adapters/real/migrate-handler.ts +3 -1
  16. package/src/adapters/real/rds-data-codec.ts +88 -4
  17. package/src/adapters/real/rds-data-emulator.ts +12 -4
  18. package/src/adapters/real/sign-in-form.tsx +29 -13
  19. package/src/authz/app-exemptions.ts +79 -9
  20. package/src/authz/route-scan.ts +626 -55
  21. package/src/components/auth/accept-invite-screen.tsx +5 -1
  22. package/src/components/auth/people-picker.tsx +20 -2
  23. package/src/components/profile-screen.tsx +27 -2
  24. package/src/core/inbound-email.ts +41 -6
  25. package/src/db/jobs.ts +15 -6
  26. package/src/db/keyset.ts +8 -6
  27. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  28. package/src/db/rls-coverage.ts +51 -17
  29. package/src/db/schedules.ts +9 -3
  30. package/src/demo-static/actor-drivers.ts +8 -2
  31. package/src/demo-static/email-html.ts +9 -0
  32. package/src/demo-static/tour/use-tours.tsx +8 -2
  33. package/src/demo-static/world.ts +76 -37
  34. package/src/email/send.ts +6 -2
  35. package/src/guide.md +20 -6
  36. package/src/i18n/messages/en.json +3 -0
  37. package/src/i18n/messages/es.json +3 -0
  38. package/src/i18n/messages.ts +3 -2
  39. package/src/server-lib/scheduled-tick.ts +5 -1
  40. package/src/server-lib/webhook-dispatch.ts +3 -0
  41. package/src/service-auth/mailgun.ts +19 -4
  42. package/src/testing/conformance/auth-provider.ts +17 -5
  43. package/src/testing/conformance/authz.ts +6 -2
  44. package/src/testing/conformance/i18n.ts +99 -5
  45. package/src/testing/conformance/suite.ts +63 -3
package/dist/release.json CHANGED
@@ -1 +1 @@
1
- {"commit":"dfc5cdde3b3fa3043efc03891ee5db574179f740"}
1
+ {"commit":"1f7bc710b87ea12442ba8f1505aaf2245c58fbec"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/kit",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -90,6 +90,7 @@
90
90
  "./core/notifications": "./src/core/notifications.ts",
91
91
  "./core/presets": "./src/core/presets.ts",
92
92
  "./core/roles": "./src/core/roles.ts",
93
+ "./core/same-origin-path": "./src/core/same-origin-path.ts",
93
94
  "./core/schedules": "./src/core/schedules.ts",
94
95
  "./core/state-machine": "./src/core/state-machine.ts",
95
96
  "./core/webhook-events": "./src/core/webhook-events.ts",
@@ -170,6 +171,7 @@
170
171
  "@aws-sdk/s3-request-presigner": "^3.1155.0",
171
172
  "@clerk/nextjs": "^7.9.19",
172
173
  "@electric-sql/pglite": "^0.5.11",
174
+ "@formatjs/icu-messageformat-parser": "^3.5.15",
173
175
  "@mantine/form": "^9.7.3",
174
176
  "@react-email/components": "^1.0.12",
175
177
  "@react-email/render": "^2.1.1",
@@ -0,0 +1,30 @@
1
+ import type { EmailMessage } from '../ports/email'
2
+
3
+ /**
4
+ * Refuses a message the email port must never send, before any adapter hands it on: a `to` that is not exactly one
5
+ * address, and a `subject` that could break a header. Mailgun's `to` takes a comma-separated list, so a `to` built from
6
+ * user input (`a@x.test, b@evil.test`) would otherwise mail everyone in it. Both the real adapter and the fake call this,
7
+ * so a test on the simulated world fails where a deployment would have sent to a list. Neither value is echoed in the
8
+ * error: both may be personal data, and the error may reach a log.
9
+ */
10
+ export function assertSendableMessage(message: EmailMessage): void {
11
+ const { to, subject } = message
12
+ if (typeof to !== 'string' || /[,;\p{Cc}]/u.test(to) || (to.match(/@/g) ?? []).length !== 1 || !isOneAddress(to)) {
13
+ throw new Error('email: `to` must be exactly one address')
14
+ }
15
+ if (/[\r\n]/.test(subject)) throw new Error('email: `subject` must not contain a line break')
16
+ }
17
+
18
+ /** An addr-spec with nothing a mailer could read as a display name, a comment or a second address around it. */
19
+ const BARE_ADDRESS = /^[^\s<>"()@]+@[^\s<>"()@]+$/
20
+
21
+ /**
22
+ * `to` is either a bare address (`ada@example.test`) or a display name and then one bracketed bare address at its very
23
+ * end (`Ada Lovelace <ada@example.test>`). Anything else lets the address a vendor mails differ from the one the caller
24
+ * recorded: in `a<b@c.d>` a mailer reads the display name `a` and mails `b@c.d`, and a trailing `(…)` is a comment.
25
+ */
26
+ function isOneAddress(to: string): boolean {
27
+ if (BARE_ADDRESS.test(to)) return true
28
+ const named = /^([^<>"()]*[^\s<>"()])\s+<([^<>]*)>$/.exec(to)
29
+ return named !== null && named[1]!.trim() !== '' && BARE_ADDRESS.test(named[2]!)
30
+ }
@@ -64,7 +64,7 @@ export const fakeAnalytics: AnalyticsPort = {
64
64
  },
65
65
  async isFlagEnabled(flag, defaultValue = false) {
66
66
  const flags = readFlags()
67
- return flag in flags ? flags[flag]! : defaultValue
67
+ return Object.hasOwn(flags, flag) ? flags[flag]! : defaultValue
68
68
  },
69
69
  }
70
70
 
@@ -200,8 +200,11 @@ export async function acceptInvite(
200
200
  ): Promise<{ id: string; tenantSlug: string }> {
201
201
  const invite = findInvite(inviteId)
202
202
  if (!invite) throw new ForbiddenError(`unknown invite: ${inviteId}`)
203
+ if (typeof profile.name !== 'string') throw new ForbiddenError('invalid name')
203
204
  const name = profile.name.trim()
204
205
  if (!name) throw new ForbiddenError('name is required')
206
+ // The same bound updateProfile keeps, so a person cannot get a name at sign-up that they could not set later.
207
+ if (!isProfileName(name)) throw new ForbiddenError('invalid name')
205
208
 
206
209
  const person: SeedPerson = {
207
210
  id: `person-invited-${inviteId.slice(0, 8)}`,
@@ -254,9 +257,17 @@ export const fakeAuth: AuthPort = {
254
257
  async updateProfile(update: ProfileUpdate): Promise<AuthUser> {
255
258
  const session = await readSession()
256
259
  if (!session) throw new AuthRequiredError()
257
- if (update.locale && !LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
260
+ // Refused as the real adapter refuses (./../real/auth.ts), before anything is stored: a name that is not a
261
+ // non-blank string of at most 256 characters, a locale this app does not ship. Only the two known fields are
262
+ // stored, so a body with anything else in it cannot reach every page that renders this person.
263
+ if (update.name !== undefined && !isProfileName(update.name)) throw new ForbiddenError('invalid name')
264
+ if (update.locale !== undefined && !LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
258
265
  const overrides = readOverrides()
259
- overrides[session.person.id] = { ...overrides[session.person.id], ...update }
266
+ overrides[session.person.id] = {
267
+ ...overrides[session.person.id],
268
+ ...(update.name === undefined ? {} : { name: update.name }),
269
+ ...(update.locale === undefined ? {} : { locale: update.locale }),
270
+ }
260
271
  await writeJsonAtomic(overridesFile(), overrides)
261
272
  return toUser(session.person, session.orgSlug)
262
273
  },
@@ -322,3 +333,8 @@ export const fakeAuth: AuthPort = {
322
333
  updatePersonState(`person:${session.person.id}`, { activeOrgSlug: orgSlug })
323
334
  },
324
335
  }
336
+
337
+ /** A display name the auth port accepts: a string with something in it, at most 256 characters (SSSB's limit). */
338
+ function isProfileName(name: unknown): name is string {
339
+ return typeof name === 'string' && name.trim() !== '' && name.length <= 256
340
+ }
@@ -1,9 +1,39 @@
1
1
  import { mkdirSync } from 'node:fs'
2
2
  import path from 'node:path'
3
3
 
4
- /** The directory all fake-adapter state lives under: APP_DATA_DIR, else `.data/` (gitignored). Creates nothing. */
4
+ /**
5
+ * The directory all fake-adapter state lives under: APP_DATA_DIR, else `.data/` (gitignored), as an absolute path (a
6
+ * relative APP_DATA_DIR is read against the working directory). Absolute because fake storage keeps a key inside its
7
+ * directory by comparing resolved paths. Creates nothing.
8
+ */
5
9
  export function dataRoot(): string {
6
- return process.env['APP_DATA_DIR'] ?? path.join(process.cwd(), '.data')
10
+ const dir = process.env['APP_DATA_DIR']
11
+ if (dir === undefined) return path.join(process.cwd(), '.data')
12
+ return absolute(dir)
13
+ }
14
+
15
+ /**
16
+ * `dir` as a normalised absolute path, against the working directory when it is relative. Written out by hand, because
17
+ * of what a build showed: with `path.resolve(<APP_DATA_DIR>)` here, and again with `path.join(process.cwd(), <it>)` or
18
+ * `path.normalize(<it>)`, Next's file tracer copied this whole directory's TypeScript source into the standalone
19
+ * server (pack and consume fails on it); with this function it copies none. Other path calls on runtime values in
20
+ * this directory do not trip it, so the trigger is narrower than "any path call": keep the environment value out of
21
+ * one. On Windows a UNC root and a drive-relative value (`D:rel`) are not supported.
22
+ */
23
+ function absolute(dir: string): string {
24
+ const from = path.isAbsolute(dir) ? dir : `${process.cwd()}${path.sep}${dir}`
25
+ // A backslash separates only where it is the platform's separator: on POSIX it is a legal file-name character.
26
+ const separators = path.sep === '\\' ? /[\\/]+/ : /\/+/
27
+ const parts: string[] = []
28
+ for (const part of from.split(separators)) {
29
+ if (part === '.' || (part === '' && parts.length > 0)) continue
30
+ if (part === '..') {
31
+ if (parts.length > 1) parts.pop()
32
+ continue
33
+ }
34
+ parts.push(part)
35
+ }
36
+ return parts.length === 1 ? `${parts[0]}${path.sep}` : parts.join(path.sep)
7
37
  }
8
38
 
9
39
  /** A directory under the fake adapters' data root, created if missing. Tests point APP_DATA_DIR at a tmp dir. */
@@ -1,6 +1,7 @@
1
1
  import { readdirSync, readFileSync, rmSync } from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import type { EmailMessage, EmailPort } from '../../ports/email'
4
+ import { assertSendableMessage } from '../email-message'
4
5
  import { writeJsonAtomic } from './atomic-write'
5
6
  import { dataDir } from './data-dir'
6
7
 
@@ -19,6 +20,7 @@ let counter = 0
19
20
 
20
21
  export const fakeEmail: EmailPort = {
21
22
  async send(message) {
23
+ assertSendableMessage(message) // as the real adapter does, so a test on fakes catches a list in `to`
22
24
  const caught: CaughtEmail = {
23
25
  id: `${Date.now()}-${(counter++).toString().padStart(3, '0')}`,
24
26
  at: new Date().toISOString(),
@@ -4,6 +4,8 @@ import { useAuth, useSignIn, useSignUp } from '@clerk/nextjs'
4
4
  import { Stack, Text } from '@mantine/core'
5
5
  import { useEffect, useRef, useState } from 'react'
6
6
 
7
+ import { sameOriginPath } from '../../core/same-origin-path'
8
+
7
9
  /**
8
10
  * Clerk ticket-strategy acceptance (ADR-0003): the invitation mail carries Clerk's invitation URL (./auth.ts
9
11
  * `createInvite`), and Clerk sends the invitee on to this page with `__clerk_ticket` and `__clerk_status` query
@@ -18,6 +20,9 @@ import { useEffect, useRef, useState } from 'react'
18
20
  * ticket round-trip once a dev Clerk instance issues real invitation tickets (see
19
21
  * docs/cutover-checklist.md, `auth-dev` row).
20
22
  *
23
+ * `redirectTo` is followed only when `sameOriginPath` accepts it, and `/` otherwise, as RealSignInForm does with its
24
+ * `returnTo`: the form trusts no caller to have checked it.
25
+ *
21
26
  * Lives in packages/kit/src/adapters because it imports the vendor SDK; the AcceptInviteShell renders it as a
22
27
  * slot, and all copy arrives via `labels` from the page's next-intl lookup (same contract as
23
28
  * RealSignInForm — one auth UI, no vendor-side strings).
@@ -65,7 +70,7 @@ export function RealAcceptInviteForm({
65
70
  void (async () => {
66
71
  if (plan === 'accepted') {
67
72
  setAccepted(true)
68
- window.location.assign(redirectTo)
73
+ window.location.assign(sameOriginPath(redirectTo) ?? '/')
69
74
  return
70
75
  }
71
76
  if (plan === 'unknown' || !ticket) {
@@ -74,21 +79,30 @@ export function RealAcceptInviteForm({
74
79
  }
75
80
  const { signIn: currentSignIn, signUp: currentSignUp } = flows.current
76
81
  const flow = plan === 'sign-in' ? currentSignIn : currentSignUp
77
- const { error: ticketError } =
78
- plan === 'sign-in' ? await currentSignIn.ticket({ ticket }) : await currentSignUp.ticket({ ticket })
79
- if (ticketError) {
80
- setError(labels.genericError)
81
- return
82
- }
83
- if (flow.status === 'complete') {
84
- const finalized = await flow.finalize()
85
- if (finalized.error) {
82
+ setError(null) // a retry after a thrown call starts with no error on screen
83
+ try {
84
+ const { error: ticketError } =
85
+ plan === 'sign-in' ? await currentSignIn.ticket({ ticket }) : await currentSignUp.ticket({ ticket })
86
+ if (ticketError) {
86
87
  setError(labels.genericError)
87
88
  return
88
89
  }
89
- setAccepted(true)
90
- window.location.assign(redirectTo)
91
- } else {
90
+ if (flow.status === 'complete') {
91
+ const finalized = await flow.finalize()
92
+ if (finalized.error) {
93
+ setError(labels.genericError)
94
+ return
95
+ }
96
+ setAccepted(true)
97
+ window.location.assign(sameOriginPath(redirectTo) ?? '/')
98
+ } else {
99
+ setError(labels.genericError)
100
+ }
101
+ } catch {
102
+ // A call that THREW (the network) is not Clerk refusing the ticket: show the error, and forget that this
103
+ // ticket was started, so the effect's next run (Clerk reloading, the page remounting) submits it again.
104
+ // A refusal above is not retried: Clerk has answered, and a ticket is single-use.
105
+ started.current = null
92
106
  setError(labels.genericError)
93
107
  }
94
108
  })()
@@ -101,7 +115,11 @@ export function RealAcceptInviteForm({
101
115
  {!accepted && !error ? (
102
116
  <Text c="gray.7">{fetchStatus === 'fetching' ? labels.accepting : labels.oneMoment}</Text>
103
117
  ) : null}
104
- {error ? <Text c="red.8">{error}</Text> : null}
118
+ {error ? (
119
+ <Text c="red.8" role="alert">
120
+ {error}
121
+ </Text>
122
+ ) : null}
105
123
  </Stack>
106
124
  )
107
125
  }
@@ -1,16 +1,43 @@
1
1
  import { PostHog } from 'posthog-node'
2
2
  import type { AnalyticsPort } from '../../ports/analytics'
3
3
 
4
+ /**
5
+ * How long `capture` waits for PostHog before it gives up on the event. The server is a Lambda, frozen once its
6
+ * response is sent, so an event still in the client's queue then may never leave: `capture` therefore sends each event
7
+ * itself and waits for it, but never longer than this, so a PostHog outage costs a response at most this much.
8
+ */
9
+ export const CAPTURE_TIMEOUT_MS = 2_000
10
+
4
11
  /**
5
12
  * AUTHORED — CUTOVER (`analytics`): typechecked, never run against a real project. Enabled in
6
13
  * staging/prod only (ADR-0010): a real deployment without a key gets the no-op (./no-analytics.ts).
7
14
  */
8
15
  export function createRealAnalytics(apiKey: string, host: string): AnalyticsPort {
9
- const client = new PostHog(apiKey, { host, flushAt: 1, flushInterval: 5_000 })
16
+ const client = new PostHog(apiKey, { host, flushAt: 1, flushInterval: 5_000, requestTimeout: CAPTURE_TIMEOUT_MS })
10
17
 
11
18
  return {
19
+ // An event is never load-bearing either: a send that fails or outruns CAPTURE_TIMEOUT_MS is logged and dropped.
12
20
  async capture(event, properties, distinctId = 'server') {
13
- client.capture({ distinctId, event, ...(properties === undefined ? {} : { properties }) })
21
+ let timer: ReturnType<typeof setTimeout> | undefined
22
+ const timedOut = new Promise<'timed out'>((resolve) => {
23
+ timer = setTimeout(() => resolve('timed out'), CAPTURE_TIMEOUT_MS)
24
+ })
25
+ try {
26
+ const sent = client.captureImmediate({
27
+ distinctId,
28
+ event,
29
+ ...(properties === undefined ? {} : { properties }),
30
+ })
31
+ if ((await Promise.race([sent.then(() => 'sent' as const), timedOut])) === 'timed out') {
32
+ console.warn(`SSSB analytics: dropped event ${event}: PostHog did not answer in time`)
33
+ }
34
+ } catch (error) {
35
+ console.warn(
36
+ `SSSB analytics: dropped event ${event}: ${error instanceof Error ? error.message : String(error)}`,
37
+ )
38
+ } finally {
39
+ clearTimeout(timer)
40
+ }
14
41
  },
15
42
 
16
43
  async isFlagEnabled(flag, defaultValue = false) {
@@ -34,9 +34,14 @@ interface AppPublicMetadata {
34
34
  tenantSlug?: string
35
35
  }
36
36
 
37
- function roleFrom(metadata: unknown, fallback: Role): Role {
37
+ /**
38
+ * The role a membership or invitation records, or `guest` when it records none (or one this app does not know): the
39
+ * least privilege, and the same answer everywhere, so the switcher and the member list never show a role the session
40
+ * does not have.
41
+ */
42
+ function roleFrom(metadata: unknown): Role {
38
43
  const role = (metadata as AppPublicMetadata)?.role
39
- return role && isRole(role) ? role : fallback
44
+ return role && isRole(role) ? role : 'guest'
40
45
  }
41
46
 
42
47
  /** The accept page as a path (with any query), for Clerk to resolve against the instance's own domain. */
@@ -45,6 +50,35 @@ function acceptPagePath(acceptPageUrl: string): string {
45
50
  return `${url.pathname}${url.search}`
46
51
  }
47
52
 
53
+ /** Clerk's list calls answer a page at a time; this is the page size the adapter asks for. */
54
+ const PAGE_SIZE = 100
55
+
56
+ /** The most pages `allPages` reads before it gives up: 100,000 rows at PAGE_SIZE, far past any team or person. */
57
+ const MAX_PAGES = 1_000
58
+
59
+ /**
60
+ * Every row of a Clerk list, read a page at a time. A list read as one page would silently drop whoever is past it: a
61
+ * team's 101st member from its notifications, or a person's 101st org from their switcher. It stops on an empty page
62
+ * or once it holds `totalCount` rows, never on a page shorter than asked for, since a server may serve fewer rows per
63
+ * page than the limit; and it throws rather than loop without end on a list that never reaches its count.
64
+ */
65
+ async function allPages<T>(
66
+ page: (params: { limit: number; offset: number }) => Promise<{ data: T[]; totalCount: number }>,
67
+ ): Promise<T[]> {
68
+ const rows: T[] = []
69
+ for (let read = 0; read < MAX_PAGES; read += 1) {
70
+ const { data, totalCount } = await page({ limit: PAGE_SIZE, offset: rows.length })
71
+ rows.push(...data)
72
+ if (data.length === 0 || rows.length >= totalCount) return rows
73
+ }
74
+ throw new Error(`a Clerk list ran past ${MAX_PAGES} pages without reaching its count`)
75
+ }
76
+
77
+ /** A display name the auth port accepts: a string with something in it, at most 256 characters (SSSB's limit). */
78
+ function isProfileName(name: unknown): name is string {
79
+ return typeof name === 'string' && name.trim() !== '' && name.length <= 256
80
+ }
81
+
48
82
  async function organizationIdForSlug(slug: string): Promise<string> {
49
83
  const client = await clerkClient()
50
84
  const org = await client.organizations.getOrganization({ slug })
@@ -63,13 +97,12 @@ export const realAuth: AuthPort = {
63
97
  // Resolve the active org membership: the remembered currentOrgSlug if still a membership,
64
98
  // else the first one. Role comes from that membership (per-org), not the user object.
65
99
  const client = await clerkClient()
66
- const memberships = await client.users.getOrganizationMembershipList({ userId, limit: 100 })
100
+ const memberships = await allPages((page) => client.users.getOrganizationMembershipList({ userId, ...page }))
67
101
  const currentOrgSlug = (user.unsafeMetadata as { currentOrgSlug?: string })?.currentOrgSlug
68
102
  const active =
69
- memberships.data.find((m) => (m.organization.slug ?? m.organization.id) === currentOrgSlug) ??
70
- memberships.data[0]
103
+ memberships.find((m) => (m.organization.slug ?? m.organization.id) === currentOrgSlug) ?? memberships[0]
71
104
 
72
- const role = roleFrom(active?.publicMetadata, 'guest')
105
+ const role = roleFrom(active?.publicMetadata)
73
106
  return {
74
107
  id: userId,
75
108
  name: user.fullName ?? user.primaryEmailAddress?.emailAddress ?? userId,
@@ -110,14 +143,15 @@ export const realAuth: AuthPort = {
110
143
  async updateProfile(update: ProfileUpdate): Promise<AuthUser> {
111
144
  const { userId } = await auth()
112
145
  if (!userId) throw new AuthRequiredError()
146
+ // Same guards the fake adapter enforces, and as early: before any write, so a refused update changes nothing.
147
+ if (update.name !== undefined && !isProfileName(update.name)) throw new ForbiddenError('invalid name')
148
+ if (update.locale !== undefined && !LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
113
149
  const client = await clerkClient()
114
150
  if (update.name !== undefined) {
115
151
  const [firstName = '', ...rest] = update.name.split(' ')
116
152
  await client.users.updateUser(userId, { firstName, lastName: rest.join(' ') })
117
153
  }
118
154
  if (update.locale !== undefined) {
119
- // Same guard the fake adapter enforces — the two adapters must reject alike.
120
- if (!LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
121
155
  await client.users.updateUserMetadata(userId, { publicMetadata: { locale: update.locale } })
122
156
  }
123
157
  const user = await this.getCurrentUser()
@@ -151,7 +185,7 @@ export const realAuth: AuthPort = {
151
185
  // as "no standing" would hand an attacker a way to kill a victim's tokens.
152
186
  if (user.banned) return null
153
187
  const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
154
- const role = roleFrom(membership.publicMetadata, 'guest')
188
+ const role = roleFrom(membership.publicMetadata)
155
189
  return { role, restricted: isRestricted(metadata.restricted, role) }
156
190
  },
157
191
 
@@ -159,10 +193,12 @@ export const realAuth: AuthPort = {
159
193
  const client = await clerkClient()
160
194
  const organizationId = await organizationIdForSlug(orgSlug)
161
195
  const [members, invitations] = await Promise.all([
162
- client.organizations.getOrganizationMembershipList({ organizationId, limit: 100 }),
163
- client.organizations.getOrganizationInvitationList({ organizationId, status: ['pending'], limit: 100 }),
196
+ allPages((page) => client.organizations.getOrganizationMembershipList({ organizationId, ...page })),
197
+ allPages((page) =>
198
+ client.organizations.getOrganizationInvitationList({ organizationId, status: ['pending'], ...page }),
199
+ ),
164
200
  ])
165
- const active: Membership[] = members.data.map((m) => {
201
+ const active: Membership[] = members.map((m) => {
166
202
  const data = m.publicUserData
167
203
  return {
168
204
  // The USER id, never the membership resource id: Membership.id must share
@@ -171,15 +207,15 @@ export const realAuth: AuthPort = {
171
207
  id: data?.userId ?? m.id,
172
208
  name: data ? `${data.firstName ?? ''} ${data.lastName ?? ''}`.trim() || null : null,
173
209
  email: data?.identifier ?? '',
174
- role: roleFrom(m.publicMetadata, 'member'),
210
+ role: roleFrom(m.publicMetadata),
175
211
  status: 'active' as const,
176
212
  }
177
213
  })
178
- const invited: Membership[] = invitations.data.map((i) => ({
214
+ const invited: Membership[] = invitations.map((i) => ({
179
215
  id: i.id,
180
216
  name: null,
181
217
  email: i.emailAddress,
182
- role: roleFrom(i.publicMetadata, 'member'),
218
+ role: roleFrom(i.publicMetadata),
183
219
  status: 'invited' as const,
184
220
  }))
185
221
  return [...active, ...invited]
@@ -223,11 +259,11 @@ export const realAuth: AuthPort = {
223
259
  const { userId } = await auth()
224
260
  if (!userId) return []
225
261
  const client = await clerkClient()
226
- const memberships = await client.users.getOrganizationMembershipList({ userId, limit: 100 })
227
- return memberships.data.map((m) => ({
262
+ const memberships = await allPages((page) => client.users.getOrganizationMembershipList({ userId, ...page }))
263
+ return memberships.map((m) => ({
228
264
  slug: m.organization.slug ?? m.organization.id,
229
265
  name: m.organization.name,
230
- role: roleFrom(m.publicMetadata, 'member'),
266
+ role: roleFrom(m.publicMetadata),
231
267
  }))
232
268
  },
233
269
 
@@ -1,5 +1,4 @@
1
- import { Kysely, PostgresDialect, sql } from 'kysely'
2
- import { Pool } from 'pg'
1
+ import { type Kysely, sql } from 'kysely'
3
2
  import type { Login } from '../../db/owner-pass'
4
3
  import type { DB } from '../../db/schema'
5
4
  import { makeTestTmpDir } from '../../testing/tmp-dir'
@@ -33,7 +32,11 @@ export interface ContractServer {
33
32
  readonly maintenanceDatabase: string
34
33
  /** The URL of `database` on this server, as the superuser, or as `login` when given. */
35
34
  urlFor(database: string, login?: { user: string; password: string }): string
36
- /** A pooled connection for a login to a database, through `pg`. Closed by its caller, or by `stop`. */
35
+ /**
36
+ * A pooled connection for a login to a database, through the REAL adapter (`createRealDb`: its pool, its type
37
+ * parsers, its connection-error listener), so a contract pass proves the driver configuration an app deploys.
38
+ * Closed by its caller, or by `stop`.
39
+ */
37
40
  connect(login: Login): Kysely<DB>
38
41
  /** The superuser's connection to `database`. */
39
42
  connectAsSuperuser(database: string): Kysely<DB>
@@ -104,6 +107,10 @@ export async function startContractServer(label: string, options: ContractServer
104
107
  serverUrl = `postgres://postgres:postgres@localhost:${port}/postgres`
105
108
  }
106
109
 
110
+ // Loaded here, not at the top: ./db reaches the migration registry, which imports the app's seam
111
+ // (`@sssb/app-config/*`), and a module that only needs this file's helpers (contractDatabaseName, say) must load
112
+ // without one.
113
+ const { createRealDb } = await import('./db')
107
114
  const parsed = new URL(serverUrl)
108
115
  const superuser = { user: decodeURIComponent(parsed.username), password: decodeURIComponent(parsed.password) }
109
116
  const maintenanceDatabase = parsed.pathname.slice(1) || 'postgres'
@@ -120,14 +127,11 @@ export async function startContractServer(label: string, options: ContractServer
120
127
  }
121
128
 
122
129
  const connect = (login: Login): Kysely<DB> => {
123
- const pool = new Pool({ connectionString: urlFor(login.database, login), max: 3 })
124
- // A server that ends a connection (a CI container's hiccup, an idle-session timeout) is an 'error' EVENT on
125
- // that client, and an event with no listener is an uncaught exception: it would take the whole run down
126
- // instead of failing the one test that was using the connection. The client's own listener covers it idle
127
- // or checked out, as in the real adapter (./db.ts); the pool's re-emit of an idle one is already logged by it.
128
- pool.on('connect', (client) => client.on('error', (error) => console.warn(`contract db: ${error.message}`)))
129
- pool.on('error', () => undefined)
130
- const db = new Kysely<DB>({ dialect: new PostgresDialect({ pool }) })
130
+ // The real adapter's own pool, parsers and listeners: it used to be a bare `pg` Pool here, so an app's contract
131
+ // run proved a different driver configuration from the one it deploys (a `date` column came back as a JS Date
132
+ // here and as a string from the deployed adapter). Destroying the Kysely ends the pool, which `stop` does for
133
+ // every one still open.
134
+ const db = createRealDb(urlFor(login.database, login)).getDb()
131
135
  open.push(db)
132
136
  return db
133
137
  }
@@ -1,5 +1,6 @@
1
1
  import Mailgun from 'mailgun.js'
2
2
  import type { EmailPort } from '../../ports/email'
3
+ import { assertSendableMessage } from '../email-message'
3
4
 
4
5
  /**
5
6
  * AUTHORED — CUTOVER (`email-outbound`): typechecked against mailgun.js, never sent for real.
@@ -10,6 +11,7 @@ export function createRealEmail(domain: string, apiKey: string, from: string): E
10
11
 
11
12
  return {
12
13
  async send(message) {
14
+ assertSendableMessage(message)
13
15
  await client.messages.create(domain, {
14
16
  from,
15
17
  to: [message.to],
@@ -36,6 +36,15 @@ export const IN_PROCESS_LOST_AFTER_MS = 5 * 60_000
36
36
  * another runner holds `running` (a service caller's, through its status route, or one the jobs webhook is walking
37
37
  * to its end) is left to it.
38
38
  *
39
+ * The sweep also fails a job still `queued` after `IN_PROCESS_LOST_AFTER_MS`: its row committed but `start` never
40
+ * claimed it (the invocation ended between the two, the runner failed to load, the request's `start` threw). A queued
41
+ * job carries no claim, so age alone decides, and that is sound for this runner only: with `JOBS_RUNNER=in-process`
42
+ * every job is this runner's, and `start` claims it in the invocation that committed it, within that invocation's
43
+ * 30-second limit, so a job queued for minutes will never start. It is failed, never run: a handler is written to run
44
+ * at most once, and the request or tick that submitted it may have reported it already. The CodeBuild runner has no
45
+ * sweep (a build may wait in CodeBuild's own queue), and neither does the simulated world, whose held jobs stay
46
+ * `queued` on purpose.
47
+ *
39
48
  * A terminal status notifies the job's org admins as the jobs webhook route does, through `notify`, which the adapter
40
49
  * registry passes in (the notification modules import the registry). Best effort: `notifyJobTerminal` swallows its
41
50
  * own failures, and anything else `notify` throws is logged; neither fails a job that already finished.
@@ -68,22 +77,28 @@ export function createInProcessJobs(ports: JobRunPorts, notify: NotifyJobTermina
68
77
  return 0
69
78
  }
70
79
  for (const tenant of tenants) {
71
- let lost: { id: string }[]
80
+ let lost: { id: string; status: string }[]
72
81
  try {
73
82
  lost = await ports.db.withTenant(tenant.id, (trx) =>
74
83
  trx
75
84
  .selectFrom('jobs')
76
- .select('jobs.id')
77
- .where('jobs.status', '=', 'running')
85
+ .select(['jobs.id', 'jobs.status'])
78
86
  .where('jobs.updated_at', '<', before)
79
- .where(({ exists, selectFrom }) =>
80
- exists(
81
- selectFrom('job_status_changes')
82
- .select('job_status_changes.id')
83
- .whereRef('job_status_changes.job_id', '=', 'jobs.id')
84
- .where('job_status_changes.status', '=', 'running')
85
- .where('job_status_changes.message', '=', IN_PROCESS_CLAIM),
86
- ),
87
+ .where((eb) =>
88
+ eb.or([
89
+ eb('jobs.status', '=', 'queued'),
90
+ eb.and([
91
+ eb('jobs.status', '=', 'running'),
92
+ eb.exists(
93
+ eb
94
+ .selectFrom('job_status_changes')
95
+ .select('job_status_changes.id')
96
+ .whereRef('job_status_changes.job_id', '=', 'jobs.id')
97
+ .where('job_status_changes.status', '=', 'running')
98
+ .where('job_status_changes.message', '=', IN_PROCESS_CLAIM),
99
+ ),
100
+ ]),
101
+ ]),
87
102
  )
88
103
  .execute(),
89
104
  )
@@ -91,10 +106,13 @@ export function createInProcessJobs(ports: JobRunPorts, notify: NotifyJobTermina
91
106
  console.warn(`SSSB jobs: the in-process sweep skipped tenant ${tenant.id}: ${messageOf(error)}`)
92
107
  continue
93
108
  }
94
- for (const { id } of lost) {
109
+ for (const { id, status } of lost) {
95
110
  try {
96
111
  await recordJobStatus(ports.db, tenant.id, id, 'failed', {
97
- error: 'lost: the server stopped before the in-process runner recorded an outcome',
112
+ error:
113
+ status === 'queued'
114
+ ? 'lost: never started; the in-process runner did not claim it'
115
+ : 'lost: the server stopped before the in-process runner recorded an outcome',
98
116
  })
99
117
  } catch (error) {
100
118
  if (!(error instanceof InvalidTransitionError)) {
@@ -102,7 +120,7 @@ export function createInProcessJobs(ports: JobRunPorts, notify: NotifyJobTermina
102
120
  `SSSB jobs: the in-process sweep could not fail job ${id}: ${messageOf(error)}`,
103
121
  )
104
122
  }
105
- continue // InvalidTransitionError: it finished, or another sweep failed it, meanwhile
123
+ continue // InvalidTransitionError: it started or finished, or another sweep failed it, meanwhile
106
124
  }
107
125
  failed += 1
108
126
  await notifyBestEffort(tenant.id, id, 'failed')
@@ -8,9 +8,11 @@ import type { JobsPort } from '../../ports/jobs'
8
8
  * the deployment's CloudFront replaces with its own signature) and
9
9
  * `{ jobId, tenantId, status: 'completed' | 'failed', resultKey?, error? }`, which records the
10
10
  * terminal transition via packages/kit/src/db/jobs.recordWebhookCompletion (idempotent under redelivery). The
11
- * build receives its context through environment overrides, mirroring the fake handler's args —
12
- * including JOB_TENANT_ID, which the webhook echoes back as `tenantId` so the completion is scoped
13
- * to the right tenant without the build having to look it up.
11
+ * build receives its context through environment overrides, mirroring a handler's `JobContext`: JOB_ID, JOB_KIND,
12
+ * JOB_TENANT_ID, which the webhook echoes back as `tenantId` so the completion is scoped to the right tenant without the
13
+ * build having to look it up, JOB_ORG_ID (empty for a job with no org), and JOB_PAYLOAD. Every override is PLAINTEXT,
14
+ * readable in the CodeBuild console and in CloudTrail, so a job's payload must never carry a secret or personal data:
15
+ * pass an id the build reads with its own access instead.
14
16
  */
15
17
  export function createRealJobs(project: string, region: string): JobsPort {
16
18
  const client = new CodeBuildClient({ region })
@@ -24,6 +26,7 @@ export function createRealJobs(project: string, region: string): JobsPort {
24
26
  { name: 'JOB_ID', value: job.id, type: 'PLAINTEXT' },
25
27
  { name: 'JOB_KIND', value: job.kind, type: 'PLAINTEXT' },
26
28
  { name: 'JOB_TENANT_ID', value: job.tenantId, type: 'PLAINTEXT' },
29
+ { name: 'JOB_ORG_ID', value: job.orgId ?? '', type: 'PLAINTEXT' },
27
30
  { name: 'JOB_PAYLOAD', value: JSON.stringify(job.payload ?? {}), type: 'PLAINTEXT' },
28
31
  ],
29
32
  }),
@@ -58,8 +58,10 @@ export async function handler(): Promise<{ ok: true }> {
58
58
  // for infra that does not, and is there only if the cluster's secret attachment added it.
59
59
  const database = process.env['DATABASE_NAME'] ?? dbname
60
60
  if (!database) throw new Error('neither DATABASE_NAME nor the secret names the database to migrate')
61
+ // Every part a secret or a deployment supplies is encoded: a database name with a `/`, `?`, `#` or `%`
62
+ // would otherwise be read as a path, a query or an escape, and connect to a different database.
61
63
  const db = createRealDb(
62
- `postgres://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}/${database}`,
64
+ `postgres://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}/${encodeURIComponent(database)}`,
63
65
  )
64
66
  await db.migrateToLatest()
65
67
  return { ok: true }