@sssb/kit 0.8.0 → 0.9.1

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 (36) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/edge-headers.ts +171 -0
  4. package/src/adapters/fake/simulator-admin.ts +7 -3
  5. package/src/adapters/fake/storage.ts +60 -8
  6. package/src/adapters/origin-form.ts +24 -0
  7. package/src/adapters/real/auth.ts +3 -2
  8. package/src/adapters/real/clerk-authorized-parties.ts +3 -14
  9. package/src/adapters/real/index.ts +8 -0
  10. package/src/adapters/real/optional-ports.ts +3 -2
  11. package/src/adapters/real/s3-storage.ts +66 -5
  12. package/src/adapters/real/storage-settings.ts +7 -4
  13. package/src/adapters/real/storage.ts +9 -7
  14. package/src/authz/route-policy.ts +7 -4
  15. package/src/components/simulator/actors-app.tsx +1 -1
  16. package/src/components/simulator/errors-app.tsx +4 -1
  17. package/src/components/simulator/inbound-app.tsx +1 -1
  18. package/src/components/simulator/jobs-app.tsx +3 -3
  19. package/src/components/simulator/mail-app.tsx +1 -1
  20. package/src/components/simulator/mail-link.ts +27 -0
  21. package/src/components/simulator/simulator-host.tsx +556 -82
  22. package/src/components/simulator/simulator-panel.tsx +1 -1
  23. package/src/db/inbound-email.ts +7 -5
  24. package/src/db/migrations/0018_organizations_write.ts +87 -0
  25. package/src/db/migrations/index.ts +2 -0
  26. package/src/db/org-lookup.ts +4 -4
  27. package/src/db/rls-coverage.ts +140 -24
  28. package/src/db/rls-proofs.ts +147 -0
  29. package/src/demo-static/world.ts +2 -2
  30. package/src/guide.md +6 -0
  31. package/src/ports/storage.ts +50 -9
  32. package/src/server-lib/invite.ts +5 -1
  33. package/src/server-lib/simulator-api.ts +320 -3
  34. package/src/service-auth/secret-env.ts +19 -0
  35. package/src/service-auth/standard-webhooks.ts +358 -0
  36. package/src/service-auth/webhook.ts +39 -12
package/dist/release.json CHANGED
@@ -1 +1 @@
1
- {"commit":"80b2e6707b2431643c0b903a30a2d888ee697327"}
1
+ {"commit":"a3cbe350f96d2cf90dd7df14fe832a3cfe69c705"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/kit",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -34,6 +34,7 @@
34
34
  "./adapters/fake/sms": "./src/adapters/fake/sms.ts",
35
35
  "./adapters/fake/storage": "./src/adapters/fake/storage.ts",
36
36
  "./adapters/fake/webhooks": "./src/adapters/fake/webhooks.ts",
37
+ "./adapters/edge-headers": "./src/adapters/edge-headers.ts",
37
38
  "./adapters/index": "./src/adapters/index.ts",
38
39
  "./adapters/proxy": "./src/adapters/proxy.ts",
39
40
  "./adapters/real/accept-invite-form": "./src/adapters/real/accept-invite-form.tsx",
@@ -155,6 +156,7 @@
155
156
  "./server-lib/sms": "./src/server-lib/sms.ts",
156
157
  "./server-lib/webhook-dispatch": "./src/server-lib/webhook-dispatch.ts",
157
158
  "./service-auth/mailgun": "./src/service-auth/mailgun.ts",
159
+ "./service-auth/standard-webhooks": "./src/service-auth/standard-webhooks.ts",
158
160
  "./service-auth/verify": "./src/service-auth/verify.ts",
159
161
  "./service-auth/webhook": "./src/service-auth/webhook.ts",
160
162
  "./testing": "./src/testing/index.ts",
@@ -0,0 +1,171 @@
1
+ import { originProblem } from './origin-form'
2
+
3
+ /**
4
+ * What a request tells the server about the visitor: the origin they asked for (`publicOrigin`) and the address they
5
+ * connect from (`clientAddress`). Neither is on the request where it looks to be. Behind `SssbApp`, Next's
6
+ * `request.url` names the server's own bind address and port, never the visitor's host (Next builds it from where it
7
+ * listens: `next/dist/server/lib/router-utils/resolve-routes.js` and `next-server.js`, `attachRequestMeta`), and the
8
+ * first `X-Forwarded-For` entry is whatever the visitor wrote there (CloudFront appends the address it saw after the
9
+ * visitor's entries: CloudFront's guide, "Request and response behavior for custom origins", "Client IP addresses").
10
+ *
11
+ * Forwarded headers are believed only where the deployment says every request passed a proxy that overwrites them:
12
+ * `SSSB_EDGE=cloudfront`, which `SssbApp` sets on its server. Its distribution's viewer-request CloudFront Function
13
+ * (`@sssb/cdk`'s `forwarded-host.js`) runs on every behavior that reaches the server and writes, over anything the
14
+ * visitor sent, `x-forwarded-host` (the `Host` CloudFront routed by, port dropped) and `x-sssb-viewer-address`
15
+ * (the address CloudFront took from the connection, `event.viewer.ip`: CloudFront's guide, "CloudFront Functions event
16
+ * structure"). The Function URL admits only signed callers (IAM auth): a distribution given an origin access grant, and
17
+ * the account's own principals; and `SssbApp` refuses to synthesize a behavior that reaches the
18
+ * server without the function. Anywhere else, `pnpm dev` and a real-mode server of your own included, those headers
19
+ * are the client's to write, so neither helper reads them.
20
+ *
21
+ * `SSSB_EDGE` is `SssbApp`'s alone: it is refused off Lambda (no `AWS_LAMBDA_FUNCTION_NAME`), where a deployment's
22
+ * environment copied into `dev:real` would otherwise have the server believe headers any client writes. A request that
23
+ * reached the server without crossing the function (the scheduled tick invokes the server directly) carries no
24
+ * `x-sssb-viewer-address`, and Next fills a missing `x-forwarded-host` from `Host` (`base-server.js`), the Function
25
+ * URL's own: so `publicOrigin` takes the forwarded host only beside a viewer address, and only when it is not `Host`.
26
+ */
27
+
28
+ /** The header `SssbApp`'s viewer-request function writes the visitor's address into (`event.viewer.ip`). */
29
+ export const VIEWER_ADDRESS_HEADER = 'x-sssb-viewer-address'
30
+
31
+ /** The value of `SSSB_EDGE` that `SssbApp` sets on its server, the only one there is. */
32
+ export const SSSB_EDGE_CLOUDFRONT = 'cloudfront'
33
+
34
+ type Env = Readonly<Record<string, string | undefined>>
35
+
36
+ /** The headers a request carries; a `Request`, `NextRequest`, or the `Headers` from `next/headers`. */
37
+ type HasHeaders = { readonly headers: Pick<Headers, 'get'> }
38
+
39
+ /**
40
+ * The origin a visitor reaches the app on (`https://app.example.org`, no trailing slash), for an absolute URL the app
41
+ * builds: a link in an email, a URL it stores. A redirect needs none: Next's `redirect('/path')` and a relative URL
42
+ * are right as they are.
43
+ *
44
+ * In order:
45
+ * 1. `PUBLIC_ORIGIN`, when the server's environment sets it: the origin it is written as (a bare `https` origin, or
46
+ * `http` on `localhost`, `127.0.0.1` or `[::1]`), in a request or outside one. Set it where a deployment is served
47
+ * from more than one origin (a custom domain and the distribution's `*.cloudfront.net`), so every link names the
48
+ * one you mean, and wherever an absolute URL is built outside a request (a job, a scheduled email).
49
+ * 2. In a request, behind `SssbApp` (`SSSB_EDGE=cloudfront`): `https://` and the `x-forwarded-host` its function
50
+ * wrote. Every behavior redirects HTTP to HTTPS, and the visitor reached port 443.
51
+ * 3. In a request anywhere else (`pnpm dev`, a server of your own): the request's own origin, `request.url`'s. Behind
52
+ * a proxy or a tunnel of your own, set `PUBLIC_ORIGIN` instead.
53
+ *
54
+ * Throws, naming `PUBLIC_ORIGIN`, outside a request without it, and behind `SssbApp` on a request that reached the
55
+ * server without crossing the distribution's function (the scheduled tick's, which invokes it directly); and on a
56
+ * malformed `PUBLIC_ORIGIN` or `SSSB_EDGE`, rather than build a link from it.
57
+ */
58
+ export function publicOrigin(request?: HasHeaders & { readonly url: string }): string {
59
+ return publicOriginFrom(process.env, request)
60
+ }
61
+
62
+ /**
63
+ * The address the visitor connects from (`198.51.100.7`, `2001:db8::1`), for what keys on it: a rate limit, a
64
+ * lockout, an audit record's "from". `undefined` where the server cannot know it: in `pnpm dev`, on a server that is
65
+ * not behind `SssbApp` (`SSSB_EDGE` unset), and on a request that did not cross the distribution. A caller must treat
66
+ * `undefined` as unknown (one shared bucket for a rate limit, say), never as a free pass. One IPv6 visitor usually
67
+ * holds a whole /64, so a limit keyed on the full address is one a visitor can multiply.
68
+ *
69
+ * It never reads `X-Forwarded-For`, `X-Real-IP`, `CF-Connecting-IP` or `Forwarded`: behind CloudFront the first
70
+ * `X-Forwarded-For` entry, `X-Real-IP` and `CF-Connecting-IP` hold what the visitor wrote (CloudFront appends the
71
+ * address it saw after the visitor's entries), and `SssbApp`'s function drops a visitor's `Forwarded`, which anywhere
72
+ * else is theirs too.
73
+ */
74
+ export function clientAddress(request: HasHeaders): string | undefined {
75
+ return clientAddressFrom(process.env, request)
76
+ }
77
+
78
+ /** `publicOrigin` over a given environment. Exported for tests. */
79
+ export function publicOriginFrom(env: Env, request?: HasHeaders & { readonly url: string }): string {
80
+ const configured = configuredOrigin(env)
81
+ if (configured) return configured
82
+ if (!request) {
83
+ throw new Error(
84
+ "publicOrigin(): no request to read the visitor's origin from, and PUBLIC_ORIGIN is unset. Set the " +
85
+ "server's PUBLIC_ORIGIN to the origin the app is served from (https://app.example.org)",
86
+ )
87
+ }
88
+ if (!behindSssbEdge(env)) return new URL(request.url).origin
89
+ const host = request.headers.get('x-forwarded-host')
90
+ // The viewer address is the proof the request crossed the function, which writes it on every request; and a
91
+ // forwarded host equal to Host is the one Next filled in from the Function URL's own.
92
+ const crossed = clientAddressFrom(env, request) !== undefined && host !== request.headers.get('host')
93
+ if (!crossed || host === null || !HOST.test(host)) {
94
+ throw new Error(
95
+ "publicOrigin(): behind SssbApp (SSSB_EDGE=cloudfront), the request carries no host the distribution's " +
96
+ 'function wrote (it did not cross the distribution: the scheduled tick invokes the server directly). ' +
97
+ "Set the server's PUBLIC_ORIGIN to the origin the app is served from",
98
+ )
99
+ }
100
+ return `https://${host}`
101
+ }
102
+
103
+ /**
104
+ * Refuses a malformed `PUBLIC_ORIGIN` or `SSSB_EDGE`, as the helpers would when first called, so a real server's boot
105
+ * check (`assertRealEnv`, and with it `sssb check-real-env`) names it before a deploy. Both are optional.
106
+ */
107
+ export function assertEdgeSettings(env: Env): void {
108
+ configuredOrigin(env)
109
+ behindSssbEdge(env)
110
+ }
111
+
112
+ /** `clientAddress` over a given environment. Exported for tests. */
113
+ export function clientAddressFrom(env: Env, request: HasHeaders): string | undefined {
114
+ if (!behindSssbEdge(env)) return undefined
115
+ const address = request.headers.get(VIEWER_ADDRESS_HEADER)
116
+ return address !== null && isIpAddress(address) ? address : undefined
117
+ }
118
+
119
+ /**
120
+ * A host as `SssbApp`'s function writes it: lower case, no port, made of DNS labels (an internationalised name is
121
+ * its `xn--` form by then). One value, so a comma-joined list a second proxy appended to is refused.
122
+ */
123
+ const HOST = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/
124
+
125
+ function configuredOrigin(env: Env): string | undefined {
126
+ const value = env['PUBLIC_ORIGIN']
127
+ if (value === undefined) return undefined
128
+ const problem = originProblem(value)
129
+ if (problem) {
130
+ throw new Error(
131
+ `PUBLIC_ORIGIN "${value}" ${problem}. Set it to the origin the app is served from ` +
132
+ '(https://host[:port]), or unset it',
133
+ )
134
+ }
135
+ return value
136
+ }
137
+
138
+ function behindSssbEdge(env: Env): boolean {
139
+ const value = env['SSSB_EDGE']
140
+ if (value === undefined || value === '') return false
141
+ if (value !== SSSB_EDGE_CLOUDFRONT) {
142
+ throw new Error(
143
+ `SSSB_EDGE "${value}" is not "${SSSB_EDGE_CLOUDFRONT}", the one value there is. SssbApp sets it on its ` +
144
+ 'server; unset it anywhere else',
145
+ )
146
+ }
147
+ if (!env['AWS_LAMBDA_FUNCTION_NAME']) {
148
+ throw new Error(
149
+ 'SSSB_EDGE is set off Lambda (no AWS_LAMBDA_FUNCTION_NAME). SssbApp sets it on its server, behind the ' +
150
+ 'distribution that writes the headers it vouches for; anywhere else a client writes them. Unset it',
151
+ )
152
+ }
153
+ return true
154
+ }
155
+
156
+ const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/
157
+
158
+ /**
159
+ * An IPv4 address in dotted decimal, or an IPv6 address as CloudFront writes `viewer.ip`; checked by `URL`, which
160
+ * parses an IPv6 host and refuses anything else in brackets. No `node:net`, so the module also loads where the
161
+ * proxy runs on the edge runtime.
162
+ */
163
+ function isIpAddress(value: string): boolean {
164
+ if (IPV4.test(value)) return true
165
+ if (!value.includes(':') || !/^[0-9a-fA-F:.]+$/.test(value)) return false
166
+ try {
167
+ return new URL(`http://[${value}]/`).hostname !== ''
168
+ } catch {
169
+ return false
170
+ }
171
+ }
@@ -165,9 +165,13 @@ export async function saveSnapshot(name: string): Promise<void> {
165
165
  const dest = snapshotPath(name)
166
166
  rmSync(dest, { force: true, recursive: true })
167
167
  mkdirSync(dest, { recursive: true })
168
+ // The `turbopackIgnore` marks: these are the world's data directories at run time, never code, and a bundler
169
+ // that traced them as dynamic file access would ship the whole project with the server (Next's standalone).
168
170
  for (const dir of LIVE_DIRS) {
169
171
  const src = liveDirPath(dir)
170
- if (existsSync(src)) cpSync(src, path.join(dest, dir), { recursive: true })
172
+ if (existsSync(/*turbopackIgnore: true*/ src)) {
173
+ cpSync(src, path.join(/*turbopackIgnore: true*/ dest, dir), { recursive: true })
174
+ }
171
175
  }
172
176
  const meta: SnapshotMeta = { at: new Date().toISOString() }
173
177
  writeJsonAtomicSync(path.join(dest, 'meta.json'), meta)
@@ -196,8 +200,8 @@ export async function restoreSnapshot(name: string): Promise<void> {
196
200
  await closeFakeDb()
197
201
  wipeLiveDirsPreservingDevSecret()
198
202
  for (const dir of LIVE_DIRS) {
199
- const dirSrc = path.join(src, dir)
200
- if (existsSync(dirSrc)) cpSync(dirSrc, liveDirPath(dir), { recursive: true })
203
+ const dirSrc = path.join(/*turbopackIgnore: true*/ src, dir)
204
+ if (existsSync(/*turbopackIgnore: true*/ dirSrc)) cpSync(dirSrc, liveDirPath(dir), { recursive: true })
201
205
  }
202
206
  })
203
207
  }
@@ -8,6 +8,7 @@ import type {
8
8
  StoragePort,
9
9
  StoredObject,
10
10
  StoredObjectInfo,
11
+ PutUploadTarget,
11
12
  UploadConstraints,
12
13
  UploadTarget,
13
14
  } from '../../ports/storage'
@@ -103,23 +104,27 @@ function uploadSecret(): Buffer {
103
104
  const UPLOAD_TARGET_TTL_SECONDS = 900
104
105
 
105
106
  /** Canonical string the signature covers — order-fixed so signer and verifier never disagree. The
106
- * expiry is INSIDE the signature, so a caller can't extend a target's life by editing the field. */
107
- function canonical(key: string, contentType: string, maxBytes: number, expires: number): string {
108
- return `${key}\n${contentType}\n${maxBytes}\n${expires}`
107
+ * expiry is INSIDE the signature, so a caller can't extend a target's life by editing the field. A PUT target's
108
+ * also holds its exact size, after a `PUT` marker, so a POST target's signature never verifies as a PUT's, nor the
109
+ * other way round, whatever a caller adds or drops. */
110
+ function canonical(key: string, contentType: string, maxBytes: number, expires: number, size?: number): string {
111
+ const base = `${key}\n${contentType}\n${maxBytes}\n${expires}`
112
+ return size === undefined ? base : `${base}\nPUT\n${size}`
109
113
  }
110
114
 
111
115
  /** HMAC-SHA256 (hex) over the upload target's constraints — module-internal (mint signs, verify checks). */
112
- function signUploadFields(key: string, contentType: string, maxBytes: number, expires: number): string {
116
+ function signUploadFields(key: string, contentType: string, maxBytes: number, expires: number, size?: number): string {
113
117
  return createHmac('sha256', uploadSecret())
114
- .update(canonical(key, contentType, maxBytes, expires))
118
+ .update(canonical(key, contentType, maxBytes, expires, size))
115
119
  .digest('hex')
116
120
  }
117
121
 
118
- /** The verified constraints carried by a fake upload target's signed fields. */
122
+ /** The verified constraints carried by a fake upload target's signed fields. `size` is a PUT target's exact length. */
119
123
  export interface VerifiedUploadFields {
120
124
  key: string
121
125
  contentType: string
122
126
  maxBytes: number
127
+ size?: number
123
128
  }
124
129
 
125
130
  /**
@@ -133,19 +138,23 @@ export function verifyUploadFields(fields: Record<string, string | undefined>):
133
138
  const contentType = fields['content-type']
134
139
  const maxBytesRaw = fields['max-bytes']
135
140
  const expiresRaw = fields['expires']
141
+ const sizeRaw = fields['size']
136
142
  const signature = fields['signature']
137
143
  if (!key || !contentType || !maxBytesRaw || !expiresRaw || !signature) return null
144
+ // Present for a PUT target only; a size that is not a whole number cannot have been signed.
145
+ const size = sizeRaw === undefined ? undefined : Number(sizeRaw)
146
+ if (size !== undefined && (!Number.isInteger(size) || size < 0)) return null
138
147
  const maxBytes = Number(maxBytesRaw)
139
148
  if (!Number.isInteger(maxBytes) || maxBytes < 0) return null
140
149
  const expires = Number(expiresRaw)
141
150
  if (!Number.isInteger(expires) || expires < 0) return null
142
- const expected = signUploadFields(key, contentType, maxBytes, expires)
151
+ const expected = signUploadFields(key, contentType, maxBytes, expires, size)
143
152
  const got = Buffer.from(signature, 'utf8')
144
153
  const want = Buffer.from(expected, 'utf8')
145
154
  if (got.length !== want.length || !timingSafeEqual(got, want)) return null
146
155
  // Expiry check AFTER the signature check, so the timestamp we trust is the one that was signed.
147
156
  if (expires * 1000 < Date.now()) return null
148
- return { key, contentType, maxBytes }
157
+ return size === undefined ? { key, contentType, maxBytes } : { key, contentType, maxBytes, size }
149
158
  }
150
159
 
151
160
  export const fakeStorage: StoragePort = {
@@ -275,6 +284,7 @@ export const fakeStorage: StoragePort = {
275
284
  // when the bytes finally land.
276
285
  const expires = Math.floor(Date.now() / 1000) + UPLOAD_TARGET_TTL_SECONDS
277
286
  return {
287
+ method: 'POST',
278
288
  url: '/api/storage-upload',
279
289
  fields: {
280
290
  key,
@@ -286,3 +296,45 @@ export const fakeStorage: StoragePort = {
286
296
  }
287
297
  },
288
298
  }
299
+
300
+ /**
301
+ * The fake store, with `createUploadTarget` minting the form `uploadTarget` names: `post` (the default, which is
302
+ * `fakeStorage` itself) or `put`, so a test, or an app that registers it as its storage, can exercise the browser's
303
+ * PUT path against the local endpoint as it would a real one (the real adapter's form is `STORAGE_UPLOAD_TARGET`).
304
+ */
305
+ export function createFakeStorage(options: { uploadTarget?: 'post' | 'put' } = {}): StoragePort {
306
+ if ((options.uploadTarget ?? 'post') === 'post') return fakeStorage
307
+ return {
308
+ ...fakeStorage,
309
+ async createUploadTarget(
310
+ key,
311
+ { contentType, maxBytes, sizeBytes }: UploadConstraints,
312
+ ): Promise<PutUploadTarget> {
313
+ // The PUT form, as the real adapter mints it: the exact size is signed in (a PUT has no policy), and the
314
+ // browser sends the file as the body with the content type as a header. The signed values ride in the
315
+ // URL's query, as a presigned URL's do, so the endpoint can verify them without a session.
316
+ if (sizeBytes === undefined) {
317
+ throw new Error('storage createUploadTarget: a PUT upload target needs constraints.sizeBytes')
318
+ }
319
+ if (!Number.isSafeInteger(sizeBytes) || sizeBytes < 0 || sizeBytes > maxBytes) {
320
+ throw new Error(
321
+ `storage createUploadTarget: sizeBytes must be an integer from 0 to maxBytes (${maxBytes}), got ${sizeBytes}`,
322
+ )
323
+ }
324
+ const expires = Math.floor(Date.now() / 1000) + UPLOAD_TARGET_TTL_SECONDS
325
+ const query = new URLSearchParams({
326
+ key,
327
+ 'content-type': contentType,
328
+ 'max-bytes': String(maxBytes),
329
+ size: String(sizeBytes),
330
+ expires: String(expires),
331
+ signature: signUploadFields(key, contentType, maxBytes, expires, sizeBytes),
332
+ })
333
+ return {
334
+ method: 'PUT',
335
+ url: `/api/storage-upload?${query.toString()}`,
336
+ headers: { 'Content-Type': contentType },
337
+ }
338
+ },
339
+ }
340
+ }
@@ -0,0 +1,24 @@
1
+ /** The hosts a browser reaches on the machine itself, the only ones served over plain `http` in a real run. */
2
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
3
+
4
+ /**
5
+ * Why `entry` is not an origin the app can be served from, or `null` when it is one: exactly its own origin as the
6
+ * browser writes it (`new URL(entry).origin`: no path, query or trailing slash, lower case, no default port, no user
7
+ * info), over `https`, or over `http` for the loopback hosts only. Shared by the settings that name the app's own
8
+ * origins: `CLERK_AUTHORIZED_PARTIES` (./real/clerk-authorized-parties.ts) and `PUBLIC_ORIGIN` (./edge-headers.ts).
9
+ */
10
+ export function originProblem(entry: string): string | null {
11
+ if (entry === '') return 'is empty'
12
+ if (entry.includes('*')) return 'is a wildcard: name one origin'
13
+ let url: URL
14
+ try {
15
+ url = new URL(entry)
16
+ } catch {
17
+ return 'is not a URL'
18
+ }
19
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK.has(url.hostname))) {
20
+ return 'is not https (http is for localhost, 127.0.0.1 and [::1] only)'
21
+ }
22
+ if (url.origin !== entry) return `is not a bare origin: write it as ${url.origin}`
23
+ return null
24
+ }
@@ -261,8 +261,9 @@ export const realAuth: AuthPort = {
261
261
  * `auth-dev` cutover row's to settle.
262
262
  *
263
263
  * The page goes to Clerk as a PATH, which Clerk's `redirectUrl` accepts ("The full URL or path"), never as the
264
- * absolute URL it arrives as: that is built from the request's URL, whose host behind `SssbApp` is the server's own
265
- * (`localhost`), not the app's (safeinsights/sssb#131).
264
+ * absolute URL it arrives as, so the link Clerk mails is right whatever origin the caller built it on. Callers
265
+ * build it on `publicOrigin` (../edge-headers.ts); before that existed, on `request.url`, whose host behind
266
+ * `SssbApp` is the server's own (`localhost`), not the app's (safeinsights/sssb#131).
266
267
  */
267
268
  async createInvite(invite: InviteInput): Promise<CreatedInvite> {
268
269
  const { userId } = await auth()
@@ -1,3 +1,5 @@
1
+ import { originProblem as appOriginProblem } from '../origin-form'
2
+
1
3
  /**
2
4
  * The origins whose Clerk session tokens this deployment accepts: `CLERK_AUTHORIZED_PARTIES`, the app's own origins,
3
5
  * comma-separated (`https://app.example.org,https://preview.example.org`), handed to Clerk's middleware as
@@ -34,21 +36,8 @@ export function clerkAuthorizedParties(value: string | undefined): string[] | un
34
36
  return entries
35
37
  }
36
38
 
37
- /** The hosts a browser reaches on the machine itself, the only ones served over plain `http` in a real run. */
38
- const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
39
-
40
39
  function originProblem(entry: string): string | null {
41
40
  if (entry === '') return 'is empty (an empty list would turn the check off)'
42
41
  if (entry.includes('*')) return 'is a wildcard, which Clerk does not expand: list each origin'
43
- let url: URL
44
- try {
45
- url = new URL(entry)
46
- } catch {
47
- return 'is not a URL'
48
- }
49
- if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK.has(url.hostname))) {
50
- return 'is not https (http is for localhost, 127.0.0.1 and [::1] only)'
51
- }
52
- if (url.origin !== entry) return `is not a bare origin: write it as ${url.origin}`
53
- return null
42
+ return appOriginProblem(entry)
54
43
  }
@@ -12,6 +12,7 @@ import { authRequiredEnv, authSettings, fixedOrgProblem } from '../auth-tenancy'
12
12
  import { configuredAuth } from '../configured-auth'
13
13
  import { orgNameForSlugs } from '../../db/org-lookup'
14
14
  import { clerkIdentitySource, realAuth } from './auth'
15
+ import { assertEdgeSettings } from '../edge-headers'
15
16
  import { clerkAuthorizedParties } from './clerk-authorized-parties'
16
17
  import { DATABASE_ENV, databaseResumeBudgetMs, databaseTransport } from './database-transport'
17
18
  import { noAnalytics } from './no-analytics'
@@ -98,6 +99,13 @@ export function assertRealEnv(): void {
98
99
  } catch (error) {
99
100
  throw new CutoverPendingError(['auth-dev'], (error as Error).message)
100
101
  }
102
+ // The app's public origin and the edge switch, both optional (../edge-headers.ts): `publicOrigin` refuses a
103
+ // malformed one when first called, which would be the first link a visitor needs; this refuses it at boot.
104
+ try {
105
+ assertEdgeSettings(process.env)
106
+ } catch (error) {
107
+ throw new CutoverPendingError(['domains-and-certs'], (error as Error).message)
108
+ }
101
109
  }
102
110
 
103
111
  /**
@@ -16,8 +16,9 @@
16
16
  * do. `s3-compatible` is a choice of its own, not `s3` reading an endpoint when one is set: which settings happen
17
17
  * to be set never picks behaviour (below). Beyond the required settings it reads `STORAGE_FORCE_PATH_STYLE`
18
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
19
+ * `post` if the store accepts a presigned POST, `put` if it takes a presigned PUT instead (R2 does not accept a
20
+ * POST), or `none` for an app that takes no browser upload, so that `createUploadTarget` fails naming the setting.
21
+ * A PUT upload target signs the file's exact size into the URL (`UploadConstraints.sizeBytes`). Explicit and with no default, because either default
21
22
  * would be a guess that fails on some store only when a browser first uploads.
22
23
  *
23
24
  * `AWS_REGION` is required by the choices that call AWS (`s3`, `codebuild`) and by the Data API transport
@@ -11,7 +11,7 @@ import {
11
11
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
12
12
  import { createPresignedPost } from '@aws-sdk/s3-presigned-post'
13
13
  import { NotFoundError, PreconditionFailedError } from '../../ports/errors'
14
- import type { CopyOptions, StoragePort, StoredObject, StoredObjectInfo } from '../../ports/storage'
14
+ import type { CopyOptions, PutUploadTarget, StoragePort, StoredObject, StoredObjectInfo } from '../../ports/storage'
15
15
 
16
16
  /** S3's hard cap on keys in one DeleteObjects request. */
17
17
  const DELETE_BATCH_SIZE = 1000
@@ -28,6 +28,53 @@ function copySourceFor(bucket: string, key: string): string {
28
28
  return `${bucket}/${key.split('/').map(encodeURIComponent).join('/')}`
29
29
  }
30
30
 
31
+ /** Seconds a presigned URL lives: the same window for a POST and a PUT, and the fake's. */
32
+ const UPLOAD_EXPIRES_SECONDS = 900
33
+
34
+ /**
35
+ * A presigned PUT. Its URL signs `Content-Type` and the exact `Content-Length`. Measured against the SDK's presigner
36
+ * (@aws-sdk/s3-request-presigner): by default it signs `content-length` and `host` but NOT `content-type`, and
37
+ * `signableHeaders` adds it; both are named so neither rests on that default. So the store refuses another type, and a body of another length if it honours a
38
+ * signed length (AWS S3 does; Cloudflare R2 is to be measured by cutover row `storage-compatible-store`). The browser
39
+ * is sent only the headers it must set; it adds the length itself from the body.
40
+ */
41
+ async function createPutTarget(
42
+ client: S3Client,
43
+ bucket: string,
44
+ key: string,
45
+ contentType: string,
46
+ maxBytes: number,
47
+ sizeBytes: number | undefined,
48
+ ): Promise<PutUploadTarget> {
49
+ if (sizeBytes === undefined) {
50
+ throw new Error(
51
+ 'storage createUploadTarget: STORAGE_UPLOAD_TARGET=put needs constraints.sizeBytes, the exact size of the ' +
52
+ 'file the browser will send: a PUT has no size policy, so the size is signed into the URL.',
53
+ )
54
+ }
55
+ if (!Number.isSafeInteger(sizeBytes) || sizeBytes < 0 || sizeBytes > maxBytes) {
56
+ throw new Error(
57
+ `storage createUploadTarget: sizeBytes must be an integer from 0 to maxBytes (${maxBytes}), got ${sizeBytes}`,
58
+ )
59
+ }
60
+ const url = await getSignedUrl(
61
+ client,
62
+ new PutObjectCommand({ Bucket: bucket, Key: key, ContentType: contentType, ContentLength: sizeBytes }),
63
+ { expiresIn: UPLOAD_EXPIRES_SECONDS, signableHeaders: new Set(['content-type', 'content-length']) },
64
+ )
65
+ // The SDK's default checksum setting puts the CRC32 of an EMPTY body into the signed URL, which no real upload
66
+ // matches. Fail here, where the cause is the client's setting, not at the browser with the store's refusal.
67
+ for (const name of new URL(url).searchParams.keys()) {
68
+ if (/^x-amz-(sdk-)?checksum/i.test(name)) {
69
+ throw new Error(
70
+ `storage createUploadTarget: the presigned PUT carries ${name}, which no upload can match. Build the ` +
71
+ "client with requestChecksumCalculation: 'WHEN_REQUIRED', or let createS3Storage build it.",
72
+ )
73
+ }
74
+ }
75
+ return { method: 'PUT', url, headers: { 'Content-Type': contentType } }
76
+ }
77
+
31
78
  /**
32
79
  * Where the adapter's bucket is, and how it reaches it. Only `bucket` is required: with the rest left out, the
33
80
  * S3 client finds its region and credentials the AWS SDK's own way (environment, profile, the Lambda's role).
@@ -55,6 +102,15 @@ export interface S3StorageOptions {
55
102
  * silently ignored.
56
103
  */
57
104
  client?: S3Client | undefined
105
+ /**
106
+ * The form of upload target `createUploadTarget` mints: `post` (the default), an S3 presigned POST, or `put`, a
107
+ * presigned PUT for a store that has no POST (Cloudflare R2). A PUT signs the exact `Content-Length` and the
108
+ * `Content-Type` into the URL (see `UploadConstraints.sizeBytes`), and must not carry the checksum the SDK's
109
+ * default settings add to a request: an adapter that builds its own client then defaults
110
+ * `requestChecksumCalculation` to `WHEN_REQUIRED`, and a `client` the caller built must already be set so
111
+ * (`createUploadTarget` throws, naming it, when the URL it signed carries a checksum).
112
+ */
113
+ uploadTarget?: 'post' | 'put' | undefined
58
114
  }
59
115
 
60
116
  /**
@@ -66,7 +122,7 @@ export interface S3StorageOptions {
66
122
  * `storage-copy`): typechecked, never run against a real bucket by SSSB's own tests.
67
123
  */
68
124
  export function createS3Storage(options: S3StorageOptions): StoragePort {
69
- const { bucket, client: given, ...config } = options
125
+ const { bucket, client: given, uploadTarget = 'post', ...config } = options
70
126
  if (!bucket) throw new Error('createS3Storage: bucket is required')
71
127
  const configured = Object.entries(config).filter(([, value]) => value !== undefined)
72
128
  if (given && configured.length > 0) {
@@ -75,6 +131,10 @@ export function createS3Storage(options: S3StorageOptions): StoragePort {
75
131
  'configure the client instead',
76
132
  )
77
133
  }
134
+ // A presigned PUT has to be signed without the SDK's default checksum (see `S3StorageOptions.uploadTarget`).
135
+ if (uploadTarget === 'put' && config.requestChecksumCalculation === undefined && !given) {
136
+ configured.push(['requestChecksumCalculation', 'WHEN_REQUIRED'])
137
+ }
78
138
  const client = given ?? new S3Client(Object.fromEntries(configured) as S3ClientConfig)
79
139
 
80
140
  return {
@@ -218,7 +278,8 @@ export function createS3Storage(options: S3StorageOptions): StoragePort {
218
278
  }
219
279
  },
220
280
 
221
- async createUploadTarget(key, { contentType, maxBytes }) {
281
+ async createUploadTarget(key, { contentType, maxBytes, sizeBytes }) {
282
+ if (uploadTarget === 'put') return createPutTarget(client, bucket, key, contentType, maxBytes, sizeBytes)
222
283
  // A presigned POST the browser uploads to directly. The Conditions ARE the security policy:
223
284
  // the object lands at exactly `key` (server-built — never client-chosen), its declared
224
285
  // Content-Type must equal `contentType`, and its size must fall within [0, maxBytes]. AWS
@@ -231,9 +292,9 @@ export function createS3Storage(options: S3StorageOptions): StoragePort {
231
292
  ['eq', '$Content-Type', contentType],
232
293
  ],
233
294
  Fields: { 'Content-Type': contentType },
234
- Expires: 900,
295
+ Expires: UPLOAD_EXPIRES_SECONDS,
235
296
  })
236
- return { url, fields }
297
+ return { method: 'POST', url, fields }
237
298
  },
238
299
  }
239
300
  }
@@ -5,10 +5,13 @@
5
5
  * secret pasted into the wrong one never reaches a log, never repeats a value that could hold one (the endpoint).
6
6
  */
7
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}")`)
8
+ /**
9
+ * `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `put` if it takes a presigned PUT instead
10
+ * (Cloudflare R2), `none` if the app takes no browser uploads.
11
+ */
12
+ export function parseUploadTarget(value: string): 'post' | 'put' | 'none' {
13
+ if (value === 'post' || value === 'put' || value === 'none') return value
14
+ throw new Error(`STORAGE_UPLOAD_TARGET must be post, put or none (got "${value}")`)
12
15
  }
13
16
 
14
17
  /** `STORAGE_FORCE_PATH_STYLE`: `true`, `false`, or unset (an empty value counts as unset) for the SDK's own addressing. */
@@ -26,7 +26,7 @@ export interface CompatibleStorageSettings {
26
26
  accessKeyId: string
27
27
  /** `STORAGE_SECRET_ACCESS_KEY`. */
28
28
  secretAccessKey: string
29
- /** `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `none` if it does not. */
29
+ /** `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `put` if it takes a presigned PUT, `none` for no browser upload. */
30
30
  uploadTarget: string
31
31
  /** `STORAGE_FORCE_PATH_STYLE`: `true`, `false`, or unset (empty counts as unset) for the SDK's own addressing. */
32
32
  forcePathStyle?: string | undefined
@@ -35,8 +35,9 @@ export interface CompatibleStorageSettings {
35
35
  /**
36
36
  * The storage port on an S3-compatible store: the same adapter as `createRealStorage`, pointed at `endpoint` with the
37
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.
38
+ * 6 lists what R2 does). `createUploadTarget` follows `uploadTarget`: an S3 presigned POST for `post` (MinIO),
39
+ * a presigned PUT for `put` (R2, which has no POST), and with `none` it fails naming the setting rather than minting a
40
+ * URL the store would refuse.
40
41
  *
41
42
  * AUTHORED — CUTOVER (`storage-compatible-store`, `storage-compatible-credentials`, and the live round trip
42
43
  * `storage-compatible-live`): typechecked and run with the SDK's transport replaced, never against a real store.
@@ -53,6 +54,7 @@ export function createCompatibleStorage(settings: CompatibleStorageSettings): St
53
54
  endpoint,
54
55
  credentials: { accessKeyId, secretAccessKey },
55
56
  forcePathStyle,
57
+ uploadTarget: target === 'put' ? 'put' : 'post',
56
58
  // The SDK's default (since v3.729, `WHEN_SUPPORTED`) puts a CRC32 checksum on every PutObject, which stores
57
59
  // older than that default can reject; Cloudflare tells R2 users to ask for checksums only where an operation
58
60
  // requires one. `WHEN_REQUIRED` does that, and no more: DeleteObjects requires one, so it still carries CRC32
@@ -61,14 +63,14 @@ export function createCompatibleStorage(settings: CompatibleStorageSettings): St
61
63
  requestChecksumCalculation: 'WHEN_REQUIRED',
62
64
  responseChecksumValidation: 'WHEN_REQUIRED',
63
65
  })
64
- if (target === 'post') return s3
66
+ if (target !== 'none') return s3
65
67
  return {
66
68
  ...s3,
67
69
  createUploadTarget: async () => {
68
70
  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.',
71
+ 'storage createUploadTarget: STORAGE_UPLOAD_TARGET=none, so this deployment takes no browser upload. Set ' +
72
+ 'STORAGE_UPLOAD_TARGET=post for a store that accepts a presigned POST (MinIO) or put for one that ' +
73
+ 'takes a presigned PUT instead (Cloudflare R2), or upload another way.',
72
74
  )
73
75
  },
74
76
  }