@sssb/kit 0.4.0 → 0.6.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 (64) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/auth-tenancy.ts +157 -0
  4. package/src/adapters/configured-auth.ts +183 -0
  5. package/src/adapters/email-message.ts +30 -0
  6. package/src/adapters/fake/analytics.ts +1 -1
  7. package/src/adapters/fake/auth.ts +53 -3
  8. package/src/adapters/fake/data-dir.ts +32 -2
  9. package/src/adapters/fake/email.ts +2 -0
  10. package/src/adapters/fake/jobs.ts +5 -4
  11. package/src/adapters/fake/simulated-auth.ts +24 -0
  12. package/src/adapters/index.ts +3 -2
  13. package/src/adapters/real/accept-invite-form.tsx +32 -14
  14. package/src/adapters/real/analytics.ts +29 -2
  15. package/src/adapters/real/auth.ts +127 -23
  16. package/src/adapters/real/contract-postgres.ts +15 -11
  17. package/src/adapters/real/email.ts +2 -0
  18. package/src/adapters/real/index.ts +19 -3
  19. package/src/adapters/real/jobs-in-process.ts +32 -14
  20. package/src/adapters/real/jobs.ts +6 -3
  21. package/src/adapters/real/migrate-handler.ts +3 -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/sign-in-form.tsx +29 -13
  25. package/src/authz/app-exemptions.ts +79 -9
  26. package/src/authz/authorize.ts +4 -1
  27. package/src/authz/route-scan.ts +626 -55
  28. package/src/components/auth/accept-invite-screen.tsx +5 -1
  29. package/src/components/auth/people-picker.tsx +20 -2
  30. package/src/components/profile-screen.tsx +27 -2
  31. package/src/core/abilities.ts +22 -6
  32. package/src/core/inbound-email.ts +41 -6
  33. package/src/core/jobs.ts +17 -0
  34. package/src/core/roles.ts +17 -2
  35. package/src/cutover/rows.json +4 -0
  36. package/src/db/jobs.ts +32 -11
  37. package/src/db/keyset.ts +8 -6
  38. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  39. package/src/db/migrations/0017_job_requester.ts +20 -0
  40. package/src/db/migrations/index.ts +2 -0
  41. package/src/db/rls-coverage.ts +51 -17
  42. package/src/db/schedules.ts +9 -3
  43. package/src/db/schema.ts +2 -0
  44. package/src/demo-static/actor-drivers.ts +8 -2
  45. package/src/demo-static/contracts.ts +9 -0
  46. package/src/demo-static/email-html.ts +9 -0
  47. package/src/demo-static/rows.ts +2 -0
  48. package/src/demo-static/tour/use-tours.tsx +8 -2
  49. package/src/demo-static/world.ts +98 -41
  50. package/src/email/send.ts +6 -2
  51. package/src/guide.md +37 -6
  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 +10 -1
  56. package/src/server-lib/notify.ts +51 -9
  57. package/src/server-lib/scheduled-tick.ts +5 -1
  58. package/src/server-lib/webhook-dispatch.ts +3 -0
  59. package/src/service-auth/mailgun.ts +19 -4
  60. package/src/testing/conformance/auth-provider.ts +17 -5
  61. package/src/testing/conformance/authz.ts +6 -2
  62. package/src/testing/conformance/demo-presets.ts +4 -4
  63. package/src/testing/conformance/i18n.ts +99 -5
  64. package/src/testing/conformance/suite.ts +63 -3
@@ -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) {
@@ -13,13 +13,19 @@ import type {
13
13
  ProfileUpdate,
14
14
  } from '../../ports/auth'
15
15
  import { AuthRequiredError, ForbiddenError } from '../../ports/errors'
16
+ import { authSettings } from '../auth-tenancy'
17
+ import type { ProviderIdentitySource } from '../configured-auth'
16
18
 
17
19
  /**
18
20
  * Clerk headless adapter (ADR-0003). Clerk organizations ARE our orgs
19
21
  * (product copy: "teams"); our org slug === Clerk org slug (no mapping layer). The tenant (site) is
20
- * ambient and lives in user publicMetadata.tenantSlug — one Clerk instance per tenant in prod, so
22
+ * ambient and lives in the user's publicMetadata, under the deployment's key (`tenantSlug` unless
23
+ * AUTH_TENANT_METADATA_KEY says otherwise) — one Clerk instance per tenant in prod, so
21
24
  * every org a user sees belongs to their tenant. The ACTIVE org rides in unsafeMetadata.currentOrgSlug,
22
25
  * and the request-time role comes from that org membership's publicMetadata.role (role is per-org).
26
+ * These are the default auth settings (multi tenancy, the provider's organizations); a single tenancy or a fixed
27
+ * org source (../auth-tenancy.ts) wraps this adapter with ../configured-auth.ts, which reads Clerk's accounts
28
+ * through `clerkIdentitySource` below.
23
29
  *
24
30
  * AUTHORED — CUTOVER (`auth-dev`): typechecked against @clerk/nextjs, never run against a real
25
31
  * Clerk instance. Verify the full port contract suite against the dev instance at cutover.
@@ -31,12 +37,37 @@ interface AppPublicMetadata {
31
37
  role?: string
32
38
  locale?: string
33
39
  restricted?: boolean
34
- tenantSlug?: string
35
40
  }
36
41
 
37
- function roleFrom(metadata: unknown, fallback: Role): Role {
42
+ /**
43
+ * The tenant a user's public metadata claims, under the deployment's key (`AUTH_TENANT_METADATA_KEY`, default
44
+ * `tenantSlug`: ../auth-tenancy.ts): the string it holds; `undefined` when it holds none (absent, null or empty); or
45
+ * `null` when it holds something else, which a single tenancy refuses and a multi tenancy reads as no tenant.
46
+ */
47
+ function tenantClaim(metadata: unknown): string | null | undefined {
48
+ const key = authSettings().tenantMetadataKey
49
+ // Its own property only: a key such as `toString` names something every object inherits.
50
+ const value =
51
+ metadata !== null && typeof metadata === 'object' && Object.hasOwn(metadata, key)
52
+ ? (metadata as Record<string, unknown>)[key]
53
+ : undefined
54
+ if (value === undefined || value === null || value === '') return undefined
55
+ return typeof value === 'string' ? value : null
56
+ }
57
+
58
+ function localeFrom(metadata: unknown): Locale {
59
+ const locale = (metadata as AppPublicMetadata | null | undefined)?.locale
60
+ return LOCALES.includes(locale as Locale) ? (locale as Locale) : DEFAULT_LOCALE
61
+ }
62
+
63
+ /**
64
+ * The role a membership or invitation records, or `guest` when it records none (or one this app does not know): the
65
+ * least privilege, and the same answer everywhere, so the switcher and the member list never show a role the session
66
+ * does not have.
67
+ */
68
+ function roleFrom(metadata: unknown): Role {
38
69
  const role = (metadata as AppPublicMetadata)?.role
39
- return role && isRole(role) ? role : fallback
70
+ return role && isRole(role) ? role : 'guest'
40
71
  }
41
72
 
42
73
  /** The accept page as a path (with any query), for Clerk to resolve against the instance's own domain. */
@@ -45,6 +76,35 @@ function acceptPagePath(acceptPageUrl: string): string {
45
76
  return `${url.pathname}${url.search}`
46
77
  }
47
78
 
79
+ /** Clerk's list calls answer a page at a time; this is the page size the adapter asks for. */
80
+ const PAGE_SIZE = 100
81
+
82
+ /** The most pages `allPages` reads before it gives up: 100,000 rows at PAGE_SIZE, far past any team or person. */
83
+ const MAX_PAGES = 1_000
84
+
85
+ /**
86
+ * 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
87
+ * team's 101st member from its notifications, or a person's 101st org from their switcher. It stops on an empty page
88
+ * or once it holds `totalCount` rows, never on a page shorter than asked for, since a server may serve fewer rows per
89
+ * page than the limit; and it throws rather than loop without end on a list that never reaches its count.
90
+ */
91
+ async function allPages<T>(
92
+ page: (params: { limit: number; offset: number }) => Promise<{ data: T[]; totalCount: number }>,
93
+ ): Promise<T[]> {
94
+ const rows: T[] = []
95
+ for (let read = 0; read < MAX_PAGES; read += 1) {
96
+ const { data, totalCount } = await page({ limit: PAGE_SIZE, offset: rows.length })
97
+ rows.push(...data)
98
+ if (data.length === 0 || rows.length >= totalCount) return rows
99
+ }
100
+ throw new Error(`a Clerk list ran past ${MAX_PAGES} pages without reaching its count`)
101
+ }
102
+
103
+ /** A display name the auth port accepts: a string with something in it, at most 256 characters (SSSB's limit). */
104
+ function isProfileName(name: unknown): name is string {
105
+ return typeof name === 'string' && name.trim() !== '' && name.length <= 256
106
+ }
107
+
48
108
  async function organizationIdForSlug(slug: string): Promise<string> {
49
109
  const client = await clerkClient()
50
110
  const org = await client.organizations.getOrganization({ slug })
@@ -58,18 +118,17 @@ export const realAuth: AuthPort = {
58
118
  const user = await currentUser()
59
119
  if (!user) return null
60
120
  const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
61
- const locale = LOCALES.includes(metadata.locale as Locale) ? (metadata.locale as Locale) : DEFAULT_LOCALE
121
+ const locale = localeFrom(metadata)
62
122
 
63
123
  // Resolve the active org membership: the remembered currentOrgSlug if still a membership,
64
124
  // else the first one. Role comes from that membership (per-org), not the user object.
65
125
  const client = await clerkClient()
66
- const memberships = await client.users.getOrganizationMembershipList({ userId, limit: 100 })
126
+ const memberships = await allPages((page) => client.users.getOrganizationMembershipList({ userId, ...page }))
67
127
  const currentOrgSlug = (user.unsafeMetadata as { currentOrgSlug?: string })?.currentOrgSlug
68
128
  const active =
69
- memberships.data.find((m) => (m.organization.slug ?? m.organization.id) === currentOrgSlug) ??
70
- memberships.data[0]
129
+ memberships.find((m) => (m.organization.slug ?? m.organization.id) === currentOrgSlug) ?? memberships[0]
71
130
 
72
- const role = roleFrom(active?.publicMetadata, 'guest')
131
+ const role = roleFrom(active?.publicMetadata)
73
132
  return {
74
133
  id: userId,
75
134
  name: user.fullName ?? user.primaryEmailAddress?.emailAddress ?? userId,
@@ -77,7 +136,7 @@ export const realAuth: AuthPort = {
77
136
  role,
78
137
  locale,
79
138
  // Ambient site claim — never the active org's business.
80
- tenantSlug: metadata.tenantSlug ?? '',
139
+ tenantSlug: tenantClaim(user.publicMetadata) ?? '',
81
140
  orgSlug: active ? (active.organization.slug ?? active.organization.id) : '',
82
141
  restricted: isRestricted(metadata.restricted, role),
83
142
  }
@@ -110,14 +169,15 @@ export const realAuth: AuthPort = {
110
169
  async updateProfile(update: ProfileUpdate): Promise<AuthUser> {
111
170
  const { userId } = await auth()
112
171
  if (!userId) throw new AuthRequiredError()
172
+ // Same guards the fake adapter enforces, and as early: before any write, so a refused update changes nothing.
173
+ if (update.name !== undefined && !isProfileName(update.name)) throw new ForbiddenError('invalid name')
174
+ if (update.locale !== undefined && !LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
113
175
  const client = await clerkClient()
114
176
  if (update.name !== undefined) {
115
177
  const [firstName = '', ...rest] = update.name.split(' ')
116
178
  await client.users.updateUser(userId, { firstName, lastName: rest.join(' ') })
117
179
  }
118
180
  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
181
  await client.users.updateUserMetadata(userId, { publicMetadata: { locale: update.locale } })
122
182
  }
123
183
  const user = await this.getCurrentUser()
@@ -151,18 +211,25 @@ export const realAuth: AuthPort = {
151
211
  // as "no standing" would hand an attacker a way to kill a victim's tokens.
152
212
  if (user.banned) return null
153
213
  const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
154
- const role = roleFrom(membership.publicMetadata, 'guest')
155
- return { role, restricted: isRestricted(metadata.restricted, role) }
214
+ const role = roleFrom(membership.publicMetadata)
215
+ return {
216
+ role,
217
+ restricted: isRestricted(metadata.restricted, role),
218
+ name: user.fullName ?? null,
219
+ email: user.primaryEmailAddress?.emailAddress ?? '',
220
+ }
156
221
  },
157
222
 
158
223
  async listMembers(orgSlug: string): Promise<Membership[]> {
159
224
  const client = await clerkClient()
160
225
  const organizationId = await organizationIdForSlug(orgSlug)
161
226
  const [members, invitations] = await Promise.all([
162
- client.organizations.getOrganizationMembershipList({ organizationId, limit: 100 }),
163
- client.organizations.getOrganizationInvitationList({ organizationId, status: ['pending'], limit: 100 }),
227
+ allPages((page) => client.organizations.getOrganizationMembershipList({ organizationId, ...page })),
228
+ allPages((page) =>
229
+ client.organizations.getOrganizationInvitationList({ organizationId, status: ['pending'], ...page }),
230
+ ),
164
231
  ])
165
- const active: Membership[] = members.data.map((m) => {
232
+ const active: Membership[] = members.map((m) => {
166
233
  const data = m.publicUserData
167
234
  return {
168
235
  // The USER id, never the membership resource id: Membership.id must share
@@ -171,15 +238,15 @@ export const realAuth: AuthPort = {
171
238
  id: data?.userId ?? m.id,
172
239
  name: data ? `${data.firstName ?? ''} ${data.lastName ?? ''}`.trim() || null : null,
173
240
  email: data?.identifier ?? '',
174
- role: roleFrom(m.publicMetadata, 'member'),
241
+ role: roleFrom(m.publicMetadata),
175
242
  status: 'active' as const,
176
243
  }
177
244
  })
178
- const invited: Membership[] = invitations.data.map((i) => ({
245
+ const invited: Membership[] = invitations.map((i) => ({
179
246
  id: i.id,
180
247
  name: null,
181
248
  email: i.emailAddress,
182
- role: roleFrom(i.publicMetadata, 'member'),
249
+ role: roleFrom(i.publicMetadata),
183
250
  status: 'invited' as const,
184
251
  }))
185
252
  return [...active, ...invited]
@@ -223,11 +290,11 @@ export const realAuth: AuthPort = {
223
290
  const { userId } = await auth()
224
291
  if (!userId) return []
225
292
  const client = await clerkClient()
226
- const memberships = await client.users.getOrganizationMembershipList({ userId, limit: 100 })
227
- return memberships.data.map((m) => ({
293
+ const memberships = await allPages((page) => client.users.getOrganizationMembershipList({ userId, ...page }))
294
+ return memberships.map((m) => ({
228
295
  slug: m.organization.slug ?? m.organization.id,
229
296
  name: m.organization.name,
230
- role: roleFrom(m.publicMetadata, 'member'),
297
+ role: roleFrom(m.publicMetadata),
231
298
  }))
232
299
  },
233
300
 
@@ -240,3 +307,40 @@ export const realAuth: AuthPort = {
240
307
  await client.users.updateUserMetadata(userId, { unsafeMetadata: { currentOrgSlug: orgSlug } })
241
308
  },
242
309
  }
310
+
311
+ /**
312
+ * Clerk's accounts as the auth settings see them (../configured-auth.ts): who is signed in and whether an account may
313
+ * still act, with no organization or role in it, so a fixed org source makes no membership call per request. A banned
314
+ * account may not act, as `getMember` says above; a locked one may, for the reason given there.
315
+ */
316
+ export const clerkIdentitySource: ProviderIdentitySource = {
317
+ async current() {
318
+ const { userId } = await auth()
319
+ if (!userId) return null
320
+ const user = await currentUser()
321
+ if (!user) return null
322
+ return {
323
+ id: userId,
324
+ name: user.fullName ?? user.primaryEmailAddress?.emailAddress ?? userId,
325
+ email: user.primaryEmailAddress?.emailAddress ?? '',
326
+ locale: localeFrom(user.publicMetadata),
327
+ tenantClaim: tenantClaim(user.publicMetadata),
328
+ }
329
+ },
330
+ async account(userId) {
331
+ const client = await clerkClient()
332
+ let user
333
+ try {
334
+ user = await client.users.getUser(userId)
335
+ } catch (error) {
336
+ if (isClerkAPIResponseError(error) && error.status === 404) return null
337
+ throw error
338
+ }
339
+ if (user.banned) return null
340
+ return {
341
+ tenantClaim: tenantClaim(user.publicMetadata),
342
+ name: user.fullName ?? null,
343
+ email: user.primaryEmailAddress?.emailAddress ?? '',
344
+ }
345
+ },
346
+ }
@@ -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],
@@ -1,3 +1,4 @@
1
+ import { staffOrgSlug } from '@sssb/app-config/abilities'
1
2
  import type { AnalyticsPort } from '../../ports/analytics'
2
3
  import type { AuthPort } from '../../ports/auth'
3
4
  import type { DbPort } from '../../ports/db'
@@ -7,7 +8,9 @@ import type { JobsPort } from '../../ports/jobs'
7
8
  import type { LlmPort } from '../../ports/llm'
8
9
  import type { StoragePort } from '../../ports/storage'
9
10
  import { absentEmail, absentJobs, absentLlm, absentStorage } from './absent'
10
- import { realAuth } from './auth'
11
+ import { authRequiredEnv, authSettings, fixedOrgProblem } from '../auth-tenancy'
12
+ import { configuredAuth } from '../configured-auth'
13
+ import { clerkIdentitySource, realAuth } from './auth'
11
14
  import { DATABASE_ENV, databaseTransport } from './database-transport'
12
15
  import { noAnalytics } from './no-analytics'
13
16
  import { optionalPortsEnv, portChoice } from './optional-ports'
@@ -49,6 +52,7 @@ export function assertRealEnv(): void {
49
52
  ...DATABASE_ENV[transport],
50
53
  ...(transport === 'data-api' ? DATA_API_REGION_ENV : {}),
51
54
  ...optionalPortsEnv(),
55
+ ...authRequiredEnv(),
52
56
  }
53
57
  const missing = Object.keys(required).filter((name) => !process.env[name])
54
58
  if (missing.length > 0) {
@@ -69,6 +73,15 @@ export function assertRealEnv(): void {
69
73
  throw new CutoverPendingError(['storage-compatible-store'], (error as Error).message)
70
74
  }
71
75
  }
76
+ // The auth settings: an unknown choice, a malformed slug, key or role, a setting its choice does not use, or a fixed
77
+ // org source that would hand everyone the staff org's manage-all.
78
+ let problem: string | null
79
+ try {
80
+ problem = fixedOrgProblem(authSettings().orgSource, staffOrgSlug)
81
+ } catch (error) {
82
+ problem = (error as Error).message
83
+ }
84
+ if (problem) throw new CutoverPendingError(['auth-tenancy'], problem)
72
85
  }
73
86
 
74
87
  /**
@@ -95,6 +108,9 @@ interface RealPortsHooks {
95
108
  export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealPorts> {
96
109
  assertRealEnv()
97
110
  const env = process.env
111
+ // Clerk, placed as the auth settings say (../auth-tenancy.ts), and Clerk itself on the defaults. Every port that
112
+ // reaches the people (the in-process runner's job context included) is handed this one.
113
+ const auth: AuthPort = configuredAuth(realAuth, authSettings(), clerkIdentitySource, staffOrgSlug)
98
114
  // assertRealEnv above already proved every required variable is set; this narrows the type.
99
115
  const need = (name: string): string => {
100
116
  const value = env[name]
@@ -144,7 +160,7 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
144
160
  runner === 'codebuild'
145
161
  ? (await import('./jobs')).createRealJobs(need('JOBS_CODEBUILD_PROJECT'), need('AWS_REGION'))
146
162
  : runner === 'in-process'
147
- ? await inProcessJobs(hooks, { db, storage, email, llm, auth: realAuth })
163
+ ? await inProcessJobs(hooks, { db, storage, email, llm, auth })
148
164
  : absentJobs
149
165
  // PostHog only where a key is configured (staging/prod per ADR-0010); a no-op otherwise (./no-analytics.ts), never
150
166
  // the simulated world's fake, which writes under `.data/`.
@@ -152,7 +168,7 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
152
168
  ? (await import('./analytics')).createRealAnalytics(env['POSTHOG_KEY'], env['POSTHOG_HOST'] ?? '')
153
169
  : noAnalytics
154
170
  return {
155
- auth: realAuth,
171
+ auth,
156
172
  db,
157
173
  storage,
158
174
  llm,
@@ -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 }