@sssb/kit 0.3.0 → 0.4.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/dist/release.json CHANGED
@@ -1 +1 @@
1
- {"commit":"4fd7633d89d3116b66b28d6c7f9dbb7873874f05"}
1
+ {"commit":"dfc5cdde3b3fa3043efc03891ee5db574179f740"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/kit",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -10,6 +10,7 @@ import { isRestricted, isRole, type Role } from '../../core/roles'
10
10
  import type {
11
11
  AuthPort,
12
12
  AuthUser,
13
+ CreatedInvite,
13
14
  InviteInput,
14
15
  Membership,
15
16
  MemberStanding,
@@ -282,7 +283,7 @@ export const fakeAuth: AuthPort = {
282
283
  return { role: membership.role, restricted: isRestricted(person.restricted, membership.role) }
283
284
  },
284
285
 
285
- async createInvite(invite: InviteInput): Promise<Membership> {
286
+ async createInvite(invite: InviteInput): Promise<CreatedInvite> {
286
287
  if (!isRole(invite.role)) throw new ForbiddenError('unknown role')
287
288
  const stored: StoredInvite = {
288
289
  id: crypto.randomUUID(),
@@ -292,7 +293,17 @@ export const fakeAuth: AuthPort = {
292
293
  invitedAt: new Date().toISOString(),
293
294
  }
294
295
  await writeJsonAtomic(invitesFile(), [...readInvites(), stored])
295
- return { id: stored.id, name: null, email: stored.email, role: stored.role, status: 'invited' }
296
+ // The accept page finds the invitation by its id (`findInvite`).
297
+ const acceptUrl = new URL(invite.acceptPageUrl)
298
+ acceptUrl.searchParams.set('invite', stored.id)
299
+ return {
300
+ id: stored.id,
301
+ name: null,
302
+ email: stored.email,
303
+ role: stored.role,
304
+ status: 'invited',
305
+ acceptUrl: acceptUrl.toString(),
306
+ }
296
307
  },
297
308
 
298
309
  async listMyOrgs(): Promise<OrgRef[]> {
@@ -3,7 +3,7 @@ import { Kysely, type Transaction } from 'kysely'
3
3
  import { migrateToLatest } from '../../db/migrate'
4
4
  import type { DB } from '../../db/schema'
5
5
  import { seedDb } from '../../db/seed'
6
- import { runWithTenant } from '../../db/with-tenant'
6
+ import { family } from '../../db/family'
7
7
  import type { DbPort } from '../../ports/db'
8
8
  import { worldNow } from './clock'
9
9
  import { dataDir } from './data-dir'
@@ -53,6 +53,8 @@ export async function closeFakeDb(): Promise<void> {
53
53
  }
54
54
 
55
55
  export const fakeDb: DbPort = {
56
+ // pglite is a Postgres transport: the family's isolation and the family's tenant scope.
57
+ isolation: family.isolation,
56
58
  getDb() {
57
59
  return instance().db
58
60
  },
@@ -62,7 +64,7 @@ export const fakeDb: DbPort = {
62
64
  async withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T> {
63
65
  const { db, ready } = instance()
64
66
  await ready
65
- return runWithTenant(db, tenantId, fn)
67
+ return family.runWithTenant(db, tenantId, fn)
66
68
  },
67
69
  async migrateToLatest() {
68
70
  await instance().ready
@@ -1,6 +1,7 @@
1
1
  import type { EmailPort } from '../../ports/email'
2
2
  import type { JobsPort } from '../../ports/jobs'
3
3
  import type { LlmPort } from '../../ports/llm'
4
+ import type { StoragePort } from '../../ports/storage'
4
5
  import { OPTIONAL_PORTS, type OptionalPort } from './optional-ports'
5
6
 
6
7
  /**
@@ -39,3 +40,15 @@ export const absentEmail: EmailPort = {
39
40
  export const absentJobs: JobsPort = {
40
41
  start: async () => absent('jobs'),
41
42
  }
43
+
44
+ /** Every method throws: an app that stores nothing never calls it, and one that does learns which switch to change. */
45
+ export const absentStorage: StoragePort = {
46
+ put: async () => absent('storage'),
47
+ get: async () => absent('storage'),
48
+ getSignedDownloadUrl: async () => absent('storage'),
49
+ createUploadTarget: async () => absent('storage'),
50
+ list: async () => absent('storage'),
51
+ delete: async () => absent('storage'),
52
+ copy: async () => absent('storage'),
53
+ head: async () => absent('storage'),
54
+ }
@@ -1,15 +1,18 @@
1
1
  'use client'
2
2
 
3
- import { useSignUp } from '@clerk/nextjs'
3
+ import { useAuth, useSignIn, useSignUp } from '@clerk/nextjs'
4
4
  import { Stack, Text } from '@mantine/core'
5
- import { useEffect, useState } from 'react'
5
+ import { useEffect, useRef, useState } from 'react'
6
6
 
7
7
  /**
8
- * Clerk ticket-strategy sign-up (ADR-0003): at cutover, Clerk organization invitations carry a
9
- * `__clerk_ticket` query param onto this page's URL instead of the fake email's plain
10
- * `/accept-invite?invite=<id>` link. sign-in-form.tsx is the reference for the v7 signals API
11
- * (signIn.password() → status → finalize()) — the sign-up equivalent used here is
12
- * signUp.ticket() → status → finalize(), per @clerk/shared's SignUpFutureResource.
8
+ * Clerk ticket-strategy acceptance (ADR-0003): the invitation mail carries Clerk's invitation URL (./auth.ts
9
+ * `createInvite`), and Clerk sends the invitee on to this page with `__clerk_ticket` and `__clerk_status` query
10
+ * params, where the fake's link carries `?invite=<id>`. Clerk's guide to accepting organization invitations: a status
11
+ * of `sign_in` means the invitee already has an account, and takes a ticket sign-in; `sign_up` (or none), a ticket
12
+ * sign-up; `complete`, that Clerk accepted it already, so the form only redirects; any other is shown as the error.
13
+ * sign-in-form.tsx is the reference for the v7 signals API (signIn.password() → status → finalize()); here it is
14
+ * signIn.ticket() or signUp.ticket() → status → finalize(), per @clerk/shared's SignInFutureResource and
15
+ * SignUpFutureResource.
13
16
  *
14
17
  * AUTHORED — CUTOVER (`auth-dev`): never run against a real Clerk instance. Verify the full
15
18
  * ticket round-trip once a dev Clerk instance issues real invitation tickets (see
@@ -21,30 +24,64 @@ import { useEffect, useState } from 'react'
21
24
  */
22
25
  export function RealAcceptInviteForm({
23
26
  ticket,
27
+ status = null,
24
28
  redirectTo,
25
29
  labels,
26
30
  }: {
27
31
  ticket: string | null
32
+ /**
33
+ * Clerk's `__clerk_status` from the page's URL: `sign_in` for an invitee who already has an account, `sign_up` for
34
+ * one who has none, `complete` when Clerk accepted the invitation itself (the invitee was already signed in).
35
+ */
36
+ status?: string | null
28
37
  redirectTo: string
29
38
  labels: AcceptInviteTicketLabels
30
39
  }) {
31
- const { signUp, fetchStatus } = useSignUp()
40
+ const { isLoaded } = useAuth()
41
+ const { signUp, fetchStatus: signUpFetch } = useSignUp()
42
+ const { signIn, fetchStatus: signInFetch } = useSignIn()
32
43
  const [error, setError] = useState<string | null>(null)
33
44
  const [accepted, setAccepted] = useState(false)
45
+ const plan = planFor(status)
46
+ const fetchStatus = plan === 'sign-in' ? signInFetch : signUpFetch
34
47
 
48
+ // A ticket is single-use, so it is submitted once. The resources change identity as Clerk loads, so the effect
49
+ // reads the current ones through a ref rather than depending on them (a dependency would run it again), starts
50
+ // only once Clerk has loaded, and remembers what it started.
51
+ const flows = useRef({ signIn, signUp })
35
52
  useEffect(() => {
36
- if (!ticket) return
37
- // Driving an external SDK call on mount (Clerk's ticket-strategy sign-up) is the
53
+ flows.current = { signIn, signUp }
54
+ })
55
+ const started = useRef<string | null>(null)
56
+
57
+ useEffect(() => {
58
+ if (!isLoaded || (plan !== 'accepted' && !ticket)) return
59
+ const key = `${plan}:${ticket ?? ''}`
60
+ if (started.current === key) return
61
+ started.current = key
62
+ // Driving an external SDK call on mount (Clerk's ticket strategy) is the
38
63
  // legitimate "sync with an external system" case the set-state-in-effect rule guards —
39
64
  // same as the Simulator glue's fetch-on-mount effects.
40
65
  void (async () => {
41
- const { error: ticketError } = await signUp.ticket({ ticket })
66
+ if (plan === 'accepted') {
67
+ setAccepted(true)
68
+ window.location.assign(redirectTo)
69
+ return
70
+ }
71
+ if (plan === 'unknown' || !ticket) {
72
+ setError(labels.genericError)
73
+ return
74
+ }
75
+ const { signIn: currentSignIn, signUp: currentSignUp } = flows.current
76
+ const flow = plan === 'sign-in' ? currentSignIn : currentSignUp
77
+ const { error: ticketError } =
78
+ plan === 'sign-in' ? await currentSignIn.ticket({ ticket }) : await currentSignUp.ticket({ ticket })
42
79
  if (ticketError) {
43
80
  setError(labels.genericError)
44
81
  return
45
82
  }
46
- if (signUp.status === 'complete') {
47
- const finalized = await signUp.finalize()
83
+ if (flow.status === 'complete') {
84
+ const finalized = await flow.finalize()
48
85
  if (finalized.error) {
49
86
  setError(labels.genericError)
50
87
  return
@@ -55,9 +92,9 @@ export function RealAcceptInviteForm({
55
92
  setError(labels.genericError)
56
93
  }
57
94
  })()
58
- }, [ticket, signUp, redirectTo, labels.genericError])
95
+ }, [isLoaded, plan, ticket, redirectTo, labels.genericError])
59
96
 
60
- if (!ticket) return <Text c="gray.7">{labels.missingTicket}</Text>
97
+ if (!ticket && plan !== 'accepted') return <Text c="gray.7">{labels.missingTicket}</Text>
61
98
 
62
99
  return (
63
100
  <Stack gap="sm">
@@ -69,6 +106,16 @@ export function RealAcceptInviteForm({
69
106
  )
70
107
  }
71
108
 
109
+ type Plan = 'sign-in' | 'sign-up' | 'accepted' | 'unknown'
110
+
111
+ /** What Clerk's `__clerk_status` asks of the form. A missing status is a sign-up, as before the status was read. */
112
+ function planFor(status: string | null): Plan {
113
+ if (status === 'complete') return 'accepted'
114
+ if (status === 'sign_in') return 'sign-in'
115
+ if (status === null || status === 'sign_up') return 'sign-up'
116
+ return 'unknown'
117
+ }
118
+
72
119
  export interface AcceptInviteTicketLabels {
73
120
  missingTicket: string
74
121
  accepting: string
@@ -3,7 +3,7 @@ import type { AnalyticsPort } from '../../ports/analytics'
3
3
 
4
4
  /**
5
5
  * AUTHORED — CUTOVER (`analytics`): typechecked, never run against a real project. Enabled in
6
- * staging/prod only (ADR-0010); everywhere else the no-op fake is wired even in real mode.
6
+ * staging/prod only (ADR-0010): a real deployment without a key gets the no-op (./no-analytics.ts).
7
7
  */
8
8
  export function createRealAnalytics(apiKey: string, host: string): AnalyticsPort {
9
9
  const client = new PostHog(apiKey, { host, flushAt: 1, flushInterval: 5_000 })
@@ -5,6 +5,7 @@ import { isRestricted, isRole, type Role } from '../../core/roles'
5
5
  import type {
6
6
  AuthPort,
7
7
  AuthUser,
8
+ CreatedInvite,
8
9
  InviteInput,
9
10
  Membership,
10
11
  MemberStanding,
@@ -38,6 +39,12 @@ function roleFrom(metadata: unknown, fallback: Role): Role {
38
39
  return role && isRole(role) ? role : fallback
39
40
  }
40
41
 
42
+ /** The accept page as a path (with any query), for Clerk to resolve against the instance's own domain. */
43
+ function acceptPagePath(acceptPageUrl: string): string {
44
+ const url = new URL(acceptPageUrl)
45
+ return `${url.pathname}${url.search}`
46
+ }
47
+
41
48
  async function organizationIdForSlug(slug: string): Promise<string> {
42
49
  const client = await clerkClient()
43
50
  const org = await client.organizations.getOrganization({ slug })
@@ -178,7 +185,18 @@ export const realAuth: AuthPort = {
178
185
  return [...active, ...invited]
179
186
  },
180
187
 
181
- async createInvite(invite: InviteInput): Promise<Membership> {
188
+ /**
189
+ * Clerk's organization invitation. `redirectUrl` sends the invitee to the app's accept page, which reads the
190
+ * `__clerk_ticket` and `__clerk_status` Clerk adds to the URL (./accept-invite-form.tsx); the invitation's own
191
+ * `url` is the link to mail, which Clerk documents as "The URL that the user can use to accept the invitation" and
192
+ * types as nullable. Clerk can also deliver the invitation email itself; which of the two an invitee gets is the
193
+ * `auth-dev` cutover row's to settle.
194
+ *
195
+ * The page goes to Clerk as a PATH, which Clerk's `redirectUrl` accepts ("The full URL or path"), never as the
196
+ * absolute URL it arrives as: that is built from the request's URL, whose host behind `SssbApp` is the server's own
197
+ * (`localhost`), not the app's (.claude/future-tasks/request-url-is-not-the-public-url.md in SSSB's repository).
198
+ */
199
+ async createInvite(invite: InviteInput): Promise<CreatedInvite> {
182
200
  const { userId } = await auth()
183
201
  if (!userId) throw new AuthRequiredError()
184
202
  const client = await clerkClient()
@@ -189,8 +207,16 @@ export const realAuth: AuthPort = {
189
207
  inviterUserId: userId,
190
208
  role: 'org:member',
191
209
  publicMetadata: { role: invite.role },
210
+ redirectUrl: acceptPagePath(invite.acceptPageUrl),
192
211
  })
193
- return { id: created.id, name: null, email: created.emailAddress, role: invite.role, status: 'invited' }
212
+ return {
213
+ id: created.id,
214
+ name: null,
215
+ email: created.emailAddress,
216
+ role: invite.role,
217
+ status: 'invited',
218
+ acceptUrl: created.url,
219
+ }
194
220
  },
195
221
 
196
222
  async listMyOrgs(): Promise<OrgRef[]> {
@@ -1,7 +1,7 @@
1
1
  import type { Kysely, Transaction } from 'kysely'
2
2
  import { migrateToLatest } from '../../db/migrate'
3
3
  import type { DB } from '../../db/schema'
4
- import { runWithTenant } from '../../db/with-tenant'
4
+ import { family } from '../../db/family'
5
5
  import type { DbPort } from '../../ports/db'
6
6
 
7
7
  /**
@@ -10,6 +10,7 @@ import type { DbPort } from '../../ports/db'
10
10
  */
11
11
  export function dbPortFor(db: Kysely<DB>): DbPort {
12
12
  return {
13
+ isolation: family.isolation,
13
14
  getDb() {
14
15
  return db
15
16
  },
@@ -17,7 +18,7 @@ export function dbPortFor(db: Kysely<DB>): DbPort {
17
18
  // Real databases are provisioned/migrated by the deploy pipeline, not lazily.
18
19
  },
19
20
  async withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T> {
20
- return runWithTenant(db, tenantId, fn)
21
+ return family.runWithTenant(db, tenantId, fn)
21
22
  },
22
23
  async migrateToLatest() {
23
24
  await migrateToLatest(db)
@@ -6,12 +6,12 @@ import { CutoverPendingError } from '../../ports/errors'
6
6
  import type { JobsPort } from '../../ports/jobs'
7
7
  import type { LlmPort } from '../../ports/llm'
8
8
  import type { StoragePort } from '../../ports/storage'
9
- import { fakeAnalytics } from '../fake/analytics'
10
- import { absentEmail, absentJobs, absentLlm } from './absent'
9
+ import { absentEmail, absentJobs, absentLlm, absentStorage } from './absent'
11
10
  import { realAuth } from './auth'
12
11
  import { DATABASE_ENV, databaseTransport } from './database-transport'
12
+ import { noAnalytics } from './no-analytics'
13
13
  import { optionalPortsEnv, portChoice } from './optional-ports'
14
- import { createRealStorage } from './storage'
14
+ import { assertEndpoint, parseForcePathStyle, parseUploadTarget } from './storage-settings'
15
15
 
16
16
  interface RealPorts {
17
17
  auth: AuthPort
@@ -26,19 +26,30 @@ interface RealPorts {
26
26
  /**
27
27
  * Env var -> cutover-checklist row, for what every real deployment needs. Fails fast with the full list, not one var
28
28
  * at a time. The database's variables follow DATABASE_TRANSPORT (./database-transport.ts), and the optional ports'
29
- * (LLM, outbound and inbound email, the job runner) follow their switches (./optional-ports.ts).
29
+ * (LLM, outbound and inbound email, the job runner, storage) follow their switches (./optional-ports.ts).
30
30
  */
31
31
  const REQUIRED_ENV: Record<string, string> = {
32
32
  NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: 'auth-dev',
33
33
  CLERK_SECRET_KEY: 'auth-dev',
34
- STORAGE_BUCKET: 'cloud-accounts',
35
- AWS_REGION: 'cloud-accounts',
36
34
  // The shared secret the cron route (the scheduled tick) and the jobs webhook verify (`withWebhookSecret`).
37
35
  WEBHOOK_SECRET: 'job-runner',
38
36
  }
39
37
 
38
+ /**
39
+ * The Data API transport's region. Not in DATABASE_ENV, whose every variable SssbApp sets on the server: on Lambda the
40
+ * runtime sets AWS_REGION, a variable a function may not set itself. The optional ports that call AWS require it too
41
+ * (./optional-ports.ts).
42
+ */
43
+ const DATA_API_REGION_ENV: Record<string, string> = { AWS_REGION: 'cloud-accounts' }
44
+
40
45
  export function assertRealEnv(): void {
41
- const required = { ...REQUIRED_ENV, ...DATABASE_ENV[databaseTransport()], ...optionalPortsEnv() }
46
+ const transport = databaseTransport()
47
+ const required = {
48
+ ...REQUIRED_ENV,
49
+ ...DATABASE_ENV[transport],
50
+ ...(transport === 'data-api' ? DATA_API_REGION_ENV : {}),
51
+ ...optionalPortsEnv(),
52
+ }
42
53
  const missing = Object.keys(required).filter((name) => !process.env[name])
43
54
  if (missing.length > 0) {
44
55
  const rows = [...new Set(missing.map((name) => required[name]))]
@@ -47,6 +58,17 @@ export function assertRealEnv(): void {
47
58
  `Missing env: ${missing.join(', ')}. See docs/cutover-checklist.md.`,
48
59
  )
49
60
  }
61
+ // Present is not enough for the settings that choose behaviour: refuse here what the adapter would refuse at boot,
62
+ // in the same form (a CutoverPendingError, which `sssb check-real-env` prints), naming the row that holds them.
63
+ if (portChoice('storage') === 's3-compatible') {
64
+ try {
65
+ parseUploadTarget(process.env['STORAGE_UPLOAD_TARGET'] ?? '')
66
+ parseForcePathStyle(process.env['STORAGE_FORCE_PATH_STYLE'])
67
+ assertEndpoint(process.env['STORAGE_ENDPOINT'] ?? '')
68
+ } catch (error) {
69
+ throw new CutoverPendingError(['storage-compatible-store'], (error as Error).message)
70
+ }
71
+ }
50
72
  }
51
73
 
52
74
  /**
@@ -81,8 +103,8 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
81
103
  }
82
104
  // Each database transport, PostHog and every optional adapter below is a dynamic import, so a deployment loads
83
105
  // the SDK of what it chose and nothing else: a `pg` deployment never loads the RDS Data SDK and a Data API one never
84
- // loads `pg`, PostHog loads only with a key, and a port switched off (`none`) never loads its vendor's. Auth (Clerk)
85
- // and storage (S3) serve every deployment, so they are imported as this module is.
106
+ // loads `pg`, PostHog loads only with a key, and a port switched off (`none`) never loads its vendor's (storage's
107
+ // S3 SDK included). Auth (Clerk) serves every deployment, so it is imported as this module is.
86
108
  const db =
87
109
  databaseTransport() === 'data-api'
88
110
  ? (await import('./db-data-api')).createRealDataApiDb({
@@ -92,7 +114,21 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
92
114
  region: need('AWS_REGION'),
93
115
  })
94
116
  : (await import('./db')).createRealDb(need('DATABASE_URL'))
95
- const storage = createRealStorage(need('STORAGE_BUCKET'), need('AWS_REGION'))
117
+ const storageChoice = portChoice('storage')
118
+ const storage =
119
+ storageChoice === 's3'
120
+ ? (await import('./storage')).createRealStorage(need('STORAGE_BUCKET'), need('AWS_REGION'))
121
+ : storageChoice === 's3-compatible'
122
+ ? (await import('./storage')).createCompatibleStorage({
123
+ bucket: need('STORAGE_BUCKET'),
124
+ endpoint: need('STORAGE_ENDPOINT'),
125
+ region: need('STORAGE_REGION'),
126
+ accessKeyId: need('STORAGE_ACCESS_KEY_ID'),
127
+ secretAccessKey: need('STORAGE_SECRET_ACCESS_KEY'),
128
+ uploadTarget: need('STORAGE_UPLOAD_TARGET'),
129
+ forcePathStyle: env['STORAGE_FORCE_PATH_STYLE'],
130
+ })
131
+ : absentStorage
96
132
  const llm =
97
133
  portChoice('llm') === 'anthropic' ? (await import('./llm')).createRealLlm(need('ANTHROPIC_API_KEY')) : absentLlm
98
134
  const email =
@@ -110,10 +146,11 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
110
146
  : runner === 'in-process'
111
147
  ? await inProcessJobs(hooks, { db, storage, email, llm, auth: realAuth })
112
148
  : absentJobs
113
- // PostHog only where a key is configured (staging/prod per ADR-0010); the simulated one otherwise.
149
+ // PostHog only where a key is configured (staging/prod per ADR-0010); a no-op otherwise (./no-analytics.ts), never
150
+ // the simulated world's fake, which writes under `.data/`.
114
151
  const analytics = env['POSTHOG_KEY']
115
152
  ? (await import('./analytics')).createRealAnalytics(env['POSTHOG_KEY'], env['POSTHOG_HOST'] ?? '')
116
- : fakeAnalytics
153
+ : noAnalytics
117
154
  return {
118
155
  auth: realAuth,
119
156
  db,
@@ -0,0 +1,17 @@
1
+ import type { AnalyticsPort } from '../../ports/analytics'
2
+
3
+ /**
4
+ * Analytics in a real deployment that configures no PostHog key (ADR-0010 enables PostHog in staging and production
5
+ * only). It captures nothing, and every flag answers the default its caller declares, as the PostHog adapter does when
6
+ * PostHog cannot be reached (./analytics.ts): a flag read is never load-bearing.
7
+ *
8
+ * Never the simulated world's fake (../fake/analytics.ts), which writes each capture and reads each flag under `.data/`
9
+ * in the working directory. On Lambda that directory is the deployment package, which is read-only, so the fake threw
10
+ * into whatever called it there: sending an invite awaits a capture.
11
+ */
12
+ export const noAnalytics: AnalyticsPort = {
13
+ async capture() {},
14
+ async isFlagEnabled(_flag, defaultValue = false) {
15
+ return defaultValue
16
+ },
17
+ }
@@ -10,6 +10,20 @@
10
10
  * with (`@sssb/kit/service-auth/mailgun`). Without it that route refuses every request, as it always has.
11
11
  * - `JOBS_RUNNER`: `codebuild` (the default), `in-process` or `none`. The `jobs` port: a CodeBuild build per job, the
12
12
  * job's handler run in the server itself (./jobs-in-process.ts), or no jobs at all.
13
+ * - `STORAGE_PROVIDER`: `s3` (the default), `s3-compatible` or `none`. The `storage` port: an S3 bucket
14
+ * (./s3-storage.ts), the same adapter on another store that speaks the S3 API (Cloudflare R2, MinIO, Backblaze B2),
15
+ * or no object storage at all. The framework itself stores nothing; an app's attachments, uploads and job artifacts
16
+ * do. `s3-compatible` is a choice of its own, not `s3` reading an endpoint when one is set: which settings happen
17
+ * to be set never picks behaviour (below). Beyond the required settings it reads `STORAGE_FORCE_PATH_STYLE`
18
+ * (`true` or `false`; unset leaves the SDK's own, virtual-hosted addressing), and requires `STORAGE_UPLOAD_TARGET`:
19
+ * `post` if the store accepts a presigned POST, which `createUploadTarget` is, or `none` if it does not (R2 does
20
+ * not), so that `createUploadTarget` fails naming the setting. Explicit and with no default, because either default
21
+ * would be a guess that fails on some store only when a browser first uploads.
22
+ *
23
+ * `AWS_REGION` is required by the choices that call AWS (`s3`, `codebuild`) and by the Data API transport
24
+ * (./index.ts), not by every deployment: one on `pg` with no storage and no CodeBuild runner calls no AWS API.
25
+ * `s3-compatible` reads `STORAGE_REGION` and its own key pair instead of `AWS_REGION` and the AWS keys, which Lambda
26
+ * reserves for the function's own role and region.
13
27
  *
14
28
  * An unset switch is its default, which is what real mode required before the switches existed, so a deployment that
15
29
  * sets none of them boots as it did. `none` makes the port ABSENT (./absent.ts): its settings are not required, its
@@ -46,7 +60,27 @@ export const OPTIONAL_PORTS = {
46
60
  jobs: {
47
61
  variable: 'JOBS_RUNNER',
48
62
  default: 'codebuild',
49
- env: { codebuild: { JOBS_CODEBUILD_PROJECT: 'job-runner' }, 'in-process': {}, none: {} },
63
+ env: {
64
+ codebuild: { JOBS_CODEBUILD_PROJECT: 'job-runner', AWS_REGION: 'cloud-accounts' },
65
+ 'in-process': {},
66
+ none: {},
67
+ },
68
+ },
69
+ storage: {
70
+ variable: 'STORAGE_PROVIDER',
71
+ default: 's3',
72
+ env: {
73
+ s3: { STORAGE_BUCKET: 'cloud-accounts', AWS_REGION: 'cloud-accounts' },
74
+ 's3-compatible': {
75
+ STORAGE_BUCKET: 'storage-compatible-store',
76
+ STORAGE_ENDPOINT: 'storage-compatible-store',
77
+ STORAGE_REGION: 'storage-compatible-store',
78
+ STORAGE_UPLOAD_TARGET: 'storage-compatible-store',
79
+ STORAGE_ACCESS_KEY_ID: 'storage-compatible-credentials',
80
+ STORAGE_SECRET_ACCESS_KEY: 'storage-compatible-credentials',
81
+ },
82
+ none: {},
83
+ },
50
84
  },
51
85
  } as const satisfies Record<
52
86
  string,
@@ -43,9 +43,15 @@ export interface S3StorageOptions {
43
43
  credentials?: S3ClientConfig['credentials'] | undefined
44
44
  /** Address the bucket in the path (`https://host/bucket/key`), as most S3-compatible endpoints need. */
45
45
  forcePathStyle?: boolean | undefined
46
+ /**
47
+ * When the client adds a checksum to a request, and checks one on a response (the SDK's own: `WHEN_SUPPORTED`).
48
+ * `WHEN_REQUIRED` is for stores that reject the checksum headers the default adds.
49
+ */
50
+ requestChecksumCalculation?: S3ClientConfig['requestChecksumCalculation'] | undefined
51
+ responseChecksumValidation?: S3ClientConfig['responseChecksumValidation'] | undefined
46
52
  /**
47
53
  * A client the caller built, used as it is: for a client shared with other code, or one a test controls.
48
- * Given with any of `region`, `endpoint`, `credentials` or `forcePathStyle`, it is refused, since those would be
54
+ * Given with any of `region`, `endpoint`, `credentials`, `forcePathStyle` or a checksum setting, it is refused, since those would be
49
55
  * silently ignored.
50
56
  */
51
57
  client?: S3Client | undefined
@@ -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
+ }