@fabrika/platform-node 0.9.0-dev.32 → 0.9.0-dev.34

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/platform-node",
3
- "version": "0.9.0-dev.32",
3
+ "version": "0.9.0-dev.34",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -38,6 +38,6 @@
38
38
  "test": "bun test"
39
39
  },
40
40
  "dependencies": {
41
- "@fabrika/platform": "0.9.0-dev.32"
41
+ "@fabrika/platform": "0.9.0-dev.34"
42
42
  }
43
43
  }
package/src/blob-s3.ts CHANGED
@@ -18,6 +18,13 @@ import {
18
18
  type ObjectWriteOptions,
19
19
  type StoredObject,
20
20
  } from '@fabrika/platform'
21
+ import {
22
+ type ContainerCredentialOptions,
23
+ type CredentialProvider,
24
+ credentialProvider,
25
+ type StorageConnection,
26
+ type StorageCredentials,
27
+ } from './storage-connection'
21
28
 
22
29
  /** Connection details for an S3-compatible bucket. `endpoint` is what makes it R2, MinIO, or AWS. */
23
30
  export interface S3BlobStoreOptions {
@@ -40,8 +47,31 @@ interface BlobBody {
40
47
  text(): Promise<string>
41
48
  }
42
49
 
50
+ /** The client a store's next request goes through: one fixed client, or one rebuilt when its credentials rotate. */
51
+ export type S3ClientSource = () => Promise<Bun.S3Client>
52
+
53
+ /** The options of one client, as `Bun.S3Client` takes them. */
54
+ export type S3ClientOptions = ConstructorParameters<typeof Bun.S3Client>[0]
55
+
56
+ export interface S3BlobStoreOpenOptions extends ContainerCredentialOptions {
57
+ /** Builds a client; `new Bun.S3Client` by default. Tests record what each client was built with. */
58
+ readonly client?: (options: S3ClientOptions) => Bun.S3Client
59
+ }
60
+
43
61
  export class S3BlobStore implements BlobStore, FileObjectStore {
44
- constructor(private readonly client: Bun.S3Client) {}
62
+ readonly #client: S3ClientSource
63
+
64
+ constructor(client: Bun.S3Client | S3ClientSource) {
65
+ this.#client = typeof client === 'function' ? client : () => Promise.resolve(client)
66
+ }
67
+
68
+ /**
69
+ * A store over a parsed connection (`parseStorageConnection`): its region and addressing, and credentials that are
70
+ * either fixed or the container endpoint's, refreshed before they expire. Never logs them.
71
+ */
72
+ static open(connection: StorageConnection, options: S3BlobStoreOpenOptions = {}): S3BlobStore {
73
+ return new S3BlobStore(storageClients(connection, credentialProvider(connection.credentials, options), options.client))
74
+ }
45
75
 
46
76
  /** Build a store from plain connection options. Never logs them. */
47
77
  static connect(options: S3BlobStoreOptions): S3BlobStore {
@@ -62,11 +92,11 @@ export class S3BlobStore implements BlobStore, FileObjectStore {
62
92
  // The S3 client takes bytes or a Response, not a bare stream — wrapping a stream in a Response
63
93
  // is what lets it be uploaded without buffering the whole body first.
64
94
  const payload = value instanceof ReadableStream ? new Response(value) : value
65
- await this.client.write(key, payload)
95
+ await (await this.#client()).write(key, payload)
66
96
  }
67
97
 
68
98
  async get(key: string): Promise<BlobBody | null> {
69
- const file = this.client.file(key)
99
+ const file = (await this.#client()).file(key)
70
100
  if (!(await file.exists())) {
71
101
  return null
72
102
  }
@@ -82,13 +112,15 @@ export class S3BlobStore implements BlobStore, FileObjectStore {
82
112
  }
83
113
 
84
114
  async delete(key: string): Promise<void> {
85
- await this.client.delete(key)
115
+ await (await this.#client()).delete(key)
86
116
  }
87
117
 
88
118
  async write(key: string, body: ReadableStream<Uint8Array>, options: ObjectWriteOptions): Promise<ObjectMetadata> {
89
119
  // Bun's client sends no `If-None-Match`; a file's key is a fresh UUID behind a unique row, and a download checks
90
120
  // the version the scan recorded, so this check refuses a reused key rather than racing a concurrent writer.
91
- if ((await statOrNull(this.client.file(key))) !== null) {
121
+ // One client for the whole write: its check, its upload and the cleanup of a failed one sign with one set.
122
+ const client = await this.#client()
123
+ if ((await statOrNull(client.file(key))) !== null) {
92
124
  await body.cancel()
93
125
  throw new ObjectExistsError()
94
126
  }
@@ -107,9 +139,9 @@ export class S3BlobStore implements BlobStore, FileObjectStore {
107
139
  }),
108
140
  )
109
141
  try {
110
- await this.client.write(key, new Response(bounded), { type: options.contentType })
142
+ await client.write(key, new Response(bounded), { type: options.contentType })
111
143
  } catch (error) {
112
- await this.client.delete(key).catch(() => undefined)
144
+ await client.delete(key).catch(() => undefined)
113
145
  throw size > options.maxBytes ? new ObjectTooLargeError(options.maxBytes) : error
114
146
  }
115
147
  return { size, contentType: options.contentType }
@@ -128,7 +160,7 @@ export class S3BlobStore implements BlobStore, FileObjectStore {
128
160
  * conditional header can be sent, which `Bun.S3File` does not offer. Errors never carry the URL: it is signed.
129
161
  */
130
162
  async #get(key: string, headers: Readonly<Record<string, string>>, signal: AbortSignal | undefined): Promise<StoredObject | null> {
131
- const url = this.client.file(key).presign({ method: 'GET', expiresIn: PRESIGNED_READ_SECONDS })
163
+ const url = (await this.#client()).file(key).presign({ method: 'GET', expiresIn: PRESIGNED_READ_SECONDS })
132
164
  let response: Response
133
165
  try {
134
166
  response = await fetch(url, { headers, ...(signal === undefined ? {} : { signal }) })
@@ -152,6 +184,36 @@ export class S3BlobStore implements BlobStore, FileObjectStore {
152
184
 
153
185
  const PRESIGNED_READ_SECONDS = 60
154
186
 
187
+ /**
188
+ * The client for `connection`, built once per set of credentials `provider` hands out: a store over fixed credentials
189
+ * keeps one client, one over the container endpoint gets a new client when the endpoint rotates them.
190
+ */
191
+ export function storageClients(
192
+ connection: StorageConnection,
193
+ provider: CredentialProvider,
194
+ make: (options: S3ClientOptions) => Bun.S3Client = (options) => new Bun.S3Client(options),
195
+ ): S3ClientSource {
196
+ let built: { readonly credentials: StorageCredentials; readonly client: Bun.S3Client } | undefined
197
+ return async () => {
198
+ const credentials = await provider.current()
199
+ if (built?.credentials !== credentials) {
200
+ built = {
201
+ credentials,
202
+ client: make({
203
+ bucket: connection.bucket,
204
+ accessKeyId: credentials.accessKeyId,
205
+ secretAccessKey: credentials.secretAccessKey,
206
+ ...(credentials.sessionToken === undefined ? {} : { sessionToken: credentials.sessionToken }),
207
+ ...(connection.endpoint === undefined ? {} : { endpoint: connection.endpoint }),
208
+ region: connection.region,
209
+ virtualHostedStyle: connection.addressing === 'virtual',
210
+ }),
211
+ }
212
+ }
213
+ return built.client
214
+ }
215
+ }
216
+
155
217
  /** One HEAD; a missing key is `null`, any other failure propagates. */
156
218
  async function statOrNull(file: Bun.S3File): Promise<Bun.S3Stats | null> {
157
219
  try {
package/src/index.ts CHANGED
@@ -34,7 +34,14 @@ export {
34
34
  export type { ApplicationDatabaseRoles } from './application-postgres-roles'
35
35
  export { applicationDatabaseSchema } from './application-schema'
36
36
  export { FileSystemAssetServer, type FileSystemAssetServerOptions } from './asset-server-fs'
37
- export { S3BlobStore, type S3BlobStoreOptions } from './blob-s3'
37
+ export {
38
+ S3BlobStore,
39
+ type S3BlobStoreOpenOptions,
40
+ type S3BlobStoreOptions,
41
+ type S3ClientOptions,
42
+ type S3ClientSource,
43
+ storageClients,
44
+ } from './blob-s3'
38
45
  export {
39
46
  CONNECTION_CAPACITY_MESSAGE,
40
47
  ConnectionCapacityError,
@@ -77,4 +84,20 @@ export {
77
84
  type PostgresServiceMigrationsConfig,
78
85
  } from './service-postgres-migrations'
79
86
  export { PostgresDatabase, PostgresStatement, type SqlBindValue } from './sql-postgres'
87
+ export {
88
+ CONTAINER_CREDENTIALS_ORIGIN,
89
+ type ContainerCredentialOptions,
90
+ containerCredentials,
91
+ CREDENTIAL_REFRESH_BEFORE_MS,
92
+ CREDENTIAL_RETRY_MS,
93
+ type CredentialProvider,
94
+ credentialProvider,
95
+ parseStorageConnection,
96
+ type StorageConnection,
97
+ StorageConnectionError,
98
+ type StorageConnectionOptions,
99
+ storageConnectionProblems,
100
+ type StorageCredentials,
101
+ type StorageCredentialSource,
102
+ } from './storage-connection'
80
103
  export { type BackgroundTasks, type BackgroundTasksOptions, createBackgroundTasks } from './wait-until'
@@ -0,0 +1,302 @@
1
+ // One parser of an object-storage connection (N5 in docs/ideas/cloud-providers.md), which Control's run logs,
2
+ // Operations' payloads and an application's files read under their own variable prefix: the bucket, the endpoint, the
3
+ // region, the addressing and where the credentials come from. Today's variables keep their meaning; `_ADDRESSING` and
4
+ // `_CREDENTIALS` are new and optional. A container cloud's task holds no long-lived key: with `_CREDENTIALS=container`
5
+ // the store reads short-lived ones from the ECS container credentials endpoint and refreshes them before they expire.
6
+ // Messages name variables, never a value: a key or an endpoint may be a credential.
7
+
8
+ /** Where a store's credentials come from. */
9
+ export type StorageCredentialSource =
10
+ | { readonly kind: 'static'; readonly accessKeyId: string; readonly secretAccessKey: string }
11
+ /** The ECS container credentials endpoint, at the path the container's environment names. */
12
+ | { readonly kind: 'container'; readonly relativeUri: string }
13
+
14
+ export interface StorageConnection {
15
+ readonly bucket: string
16
+ /** Absent: the provider's default endpoint for the region (AWS S3). */
17
+ readonly endpoint?: string
18
+ readonly region: string
19
+ /** `virtual` addresses `https://<bucket>.<host>`; `path` (the default, as before) `https://<host>/<bucket>`. */
20
+ readonly addressing: 'path' | 'virtual'
21
+ readonly credentials: StorageCredentialSource
22
+ }
23
+
24
+ export interface StorageConnectionOptions {
25
+ /** The region a connection that names none signs for: what the caller signed for before the variable. */
26
+ readonly defaultRegion: string
27
+ /** Whether a static connection must name its endpoint (an application's always did). */
28
+ readonly endpoint: 'required' | 'optional'
29
+ /** The container's own environment, which holds the credentials endpoint's path; the process's by default. */
30
+ readonly environment?: Readonly<Record<string, string | undefined>>
31
+ }
32
+
33
+ /** A connection the variables cannot describe; `problems` name variables only. */
34
+ export class StorageConnectionError extends Error {
35
+ override readonly name = 'StorageConnectionError'
36
+ constructor(readonly problems: readonly string[]) {
37
+ super(`the object storage is not configured: ${problems.join('; ')}`)
38
+ }
39
+ }
40
+
41
+ /** Whether `value` is a `StorageConnectionError`, read structurally: a caller in another package may hold another copy. */
42
+ export function storageConnectionProblems(value: unknown): readonly string[] | null {
43
+ if (!(value instanceof Error) || value.name !== 'StorageConnectionError') return null
44
+ const problems: unknown = Reflect.get(value, 'problems')
45
+ return Array.isArray(problems) && problems.every((problem) => typeof problem === 'string') ? problems : null
46
+ }
47
+
48
+ /** A region name as S3-compatible stores spell them: `eu-central-1`, `auto`. */
49
+ const REGION = /^[a-z0-9][a-z0-9-]{0,31}$/
50
+ /** The path ECS writes: an absolute path, nothing that could name another host or climb out of it. */
51
+ const RELATIVE_URI = /^\/[A-Za-z0-9._~/-]{1,512}$/
52
+ const CONTAINER_URI_VARIABLE = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'
53
+
54
+ /**
55
+ * The connection the variables under `prefix` (`FABRIKA_APP_STORAGE`) describe, or `undefined` when none of them is
56
+ * set. `<prefix>_BUCKET`, `_ENDPOINT`, `_REGION`, `_ACCESS_KEY_ID` and `_SECRET_ACCESS_KEY` keep their meaning;
57
+ * `_ADDRESSING` is `path` or `virtual`, `_CREDENTIALS` is `static` (the key pair, the default) or `container`, which
58
+ * takes no key pair.
59
+ */
60
+ export function parseStorageConnection(
61
+ variables: Readonly<Record<string, string | undefined>>,
62
+ prefix: string,
63
+ options: StorageConnectionOptions,
64
+ ): StorageConnection | undefined {
65
+ const name = (suffix: string): string => `${prefix}_${suffix}`
66
+ const value = (suffix: string): string => variables[name(suffix)]?.trim() ?? ''
67
+ const suffixes = ['BUCKET', 'ENDPOINT', 'REGION', 'ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'ADDRESSING', 'CREDENTIALS']
68
+ if (suffixes.every((suffix) => value(suffix) === '')) {
69
+ return undefined
70
+ }
71
+ const problems: string[] = []
72
+ const region = value('REGION')
73
+ if (region !== '' && !REGION.test(region)) {
74
+ problems.push(`${name('REGION')} is not a region name (lowercase letters, digits and hyphens)`)
75
+ }
76
+ const addressing = value('ADDRESSING')
77
+ if (addressing !== '' && addressing !== 'path' && addressing !== 'virtual') {
78
+ problems.push(`${name('ADDRESSING')} is 'path' or 'virtual'`)
79
+ }
80
+ const mode = value('CREDENTIALS')
81
+ if (mode !== '' && mode !== 'static' && mode !== 'container') {
82
+ problems.push(`${name('CREDENTIALS')} is 'static' or 'container'`)
83
+ }
84
+ const bucket = value('BUCKET')
85
+ if (bucket === '') {
86
+ problems.push(`${name('BUCKET')} is not set`)
87
+ }
88
+ const endpoint = value('ENDPOINT')
89
+ if (endpoint !== '' && !isEndpoint(endpoint)) {
90
+ problems.push(`${name('ENDPOINT')} is not an http(s) URL without credentials, a query or a fragment`)
91
+ }
92
+ let credentials: StorageCredentialSource | undefined
93
+ if (mode === 'container') {
94
+ for (const suffix of ['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY']) {
95
+ if (value(suffix) !== '') problems.push(`${name(suffix)} is set, but ${name('CREDENTIALS')} is 'container'`)
96
+ }
97
+ const relativeUri = (options.environment ?? process.env)[CONTAINER_URI_VARIABLE]?.trim() ?? ''
98
+ if (!RELATIVE_URI.test(relativeUri) || relativeUri.includes('..') || relativeUri.startsWith('//')) {
99
+ problems.push(`${name('CREDENTIALS')} is 'container', but ${CONTAINER_URI_VARIABLE} is not a path the container credentials endpoint serves`)
100
+ } else {
101
+ credentials = { kind: 'container', relativeUri }
102
+ }
103
+ } else {
104
+ const missing = ['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', ...(options.endpoint === 'required' ? ['ENDPOINT'] : [])].filter((suffix) =>
105
+ value(suffix) === ''
106
+ )
107
+ for (const suffix of missing) {
108
+ problems.push(`${name(suffix)} is not set; the platform writes every ${prefix}_* variable together`)
109
+ }
110
+ if (missing.length === 0) {
111
+ credentials = { kind: 'static', accessKeyId: value('ACCESS_KEY_ID'), secretAccessKey: value('SECRET_ACCESS_KEY') }
112
+ }
113
+ }
114
+ if (problems.length > 0 || credentials === undefined) {
115
+ throw new StorageConnectionError(problems)
116
+ }
117
+ return {
118
+ bucket,
119
+ ...(endpoint === '' ? {} : { endpoint }),
120
+ region: region === '' ? options.defaultRegion : region,
121
+ addressing: addressing === 'virtual' ? 'virtual' : 'path',
122
+ credentials,
123
+ }
124
+ }
125
+
126
+ /**
127
+ * An endpoint the store may be handed as written: `http://` or `https://` spelled out (a URL parser would repair
128
+ * `https:host`, and the client would get the original), no credentials, no query, no fragment. A path stays allowed:
129
+ * the form of Zerops' `apiUrl`, which an application's variable references, is not recorded.
130
+ */
131
+ function isEndpoint(value: string): boolean {
132
+ if (!/^https?:\/\/[^/]/.test(value)) return false
133
+ try {
134
+ const url = new URL(value)
135
+ return url.username === '' && url.password === '' && url.search === '' && url.hash === '' && !value.includes('#') && !value.includes('?')
136
+ } catch {
137
+ return false
138
+ }
139
+ }
140
+
141
+ /** A set of credentials a store signs with; `expiresAt` (epoch ms) only for short-lived ones. */
142
+ export interface StorageCredentials {
143
+ readonly accessKeyId: string
144
+ readonly secretAccessKey: string
145
+ readonly sessionToken?: string
146
+ readonly expiresAt?: number
147
+ }
148
+
149
+ /** The credentials a store signs its next request with. */
150
+ export interface CredentialProvider {
151
+ current(): Promise<StorageCredentials>
152
+ }
153
+
154
+ export interface ContainerCredentialOptions {
155
+ /** The endpoint's origin; ECS serves it at this link-local address. Tests point it elsewhere. */
156
+ readonly origin?: string
157
+ readonly fetch?: (input: string, init: RequestInit) => Promise<Response>
158
+ readonly now?: () => number
159
+ }
160
+
161
+ /** ECS's container credentials endpoint. */
162
+ export const CONTAINER_CREDENTIALS_ORIGIN = 'http://169.254.170.2'
163
+ /** How long before their expiry a set of credentials is replaced; ECS rotates them well before. */
164
+ export const CREDENTIAL_REFRESH_BEFORE_MS = 5 * 60_000
165
+ /** How long after a failed or fruitless refresh the next one waits. */
166
+ export const CREDENTIAL_RETRY_MS = 30_000
167
+ const CREDENTIAL_FETCH_TIMEOUT_MS = 5_000
168
+ const MAX_CREDENTIAL_BYTES = 16 * 1024
169
+
170
+ /**
171
+ * Short-lived credentials from the ECS container credentials endpoint. The first request waits for the first set; while
172
+ * the held set is valid every request gets it at once, and within `CREDENTIAL_REFRESH_BEFORE_MS` of its expiry one
173
+ * refresh runs in the background. A refresh that fails, or answers a set that expires no later than the held one, waits
174
+ * `CREDENTIAL_RETRY_MS` before the next; an answer already expired is a failure. Only a request without a valid set
175
+ * waits for a fetch, and within the retry wait it fails at once instead. A failure is logged once until a refresh
176
+ * succeeds. The answer decides what a request is signed with, so no redirect is followed. Nothing logs a key, the token
177
+ * or the endpoint's path.
178
+ */
179
+ export function containerCredentials(relativeUri: string, options: ContainerCredentialOptions = {}): CredentialProvider {
180
+ const fetcher = options.fetch ?? ((input, init) => fetch(input, init))
181
+ const now = options.now ?? Date.now
182
+ const url = `${options.origin ?? CONTAINER_CREDENTIALS_ORIGIN}${relativeUri}`
183
+ let held: StorageCredentials | undefined
184
+ let refreshing: Promise<void> | undefined
185
+ let retryAt = 0
186
+ let failing = false
187
+ const valid = (set: StorageCredentials | undefined, time: number): set is StorageCredentials =>
188
+ set !== undefined && (set.expiresAt === undefined || time < set.expiresAt)
189
+ const fetchSet = async (): Promise<StorageCredentials> => {
190
+ const response = await fetcher(url, { redirect: 'manual', signal: AbortSignal.timeout(CREDENTIAL_FETCH_TIMEOUT_MS) })
191
+ if (!response.ok) {
192
+ await response.body?.cancel()
193
+ throw new Error(`the container credentials endpoint answered ${response.status}`)
194
+ }
195
+ const text = await boundedText(response)
196
+ const parsed = text === null ? null : parseContainerCredentials(text)
197
+ if (parsed === null) {
198
+ throw new Error('the container credentials endpoint answered no credentials')
199
+ }
200
+ return parsed
201
+ }
202
+ const refresh = (): Promise<void> => {
203
+ refreshing ??= fetchSet()
204
+ .then((fresh) => {
205
+ const time = now()
206
+ if (!valid(fresh, time)) throw new Error('the container credentials endpoint answered an expired set')
207
+ if (held?.expiresAt !== undefined && fresh.expiresAt !== undefined && fresh.expiresAt <= held.expiresAt) {
208
+ // No longer than the held set: keep it, and do not ask again at once.
209
+ retryAt = time + CREDENTIAL_RETRY_MS
210
+ return
211
+ }
212
+ held = fresh
213
+ failing = false
214
+ // A set that is already near its end is used, and the next refresh still waits.
215
+ retryAt = fresh.expiresAt !== undefined && time >= fresh.expiresAt - CREDENTIAL_REFRESH_BEFORE_MS ? time + CREDENTIAL_RETRY_MS : 0
216
+ })
217
+ .catch(() => {
218
+ // A driver or parse error is not forwarded: nothing of the endpoint's answer reaches a log.
219
+ if (!failing) console.error('fabrika: the container credentials could not be refreshed')
220
+ failing = true
221
+ retryAt = now() + CREDENTIAL_RETRY_MS
222
+ })
223
+ .finally(() => {
224
+ refreshing = undefined
225
+ })
226
+ return refreshing
227
+ }
228
+ return {
229
+ async current(): Promise<StorageCredentials> {
230
+ const time = now()
231
+ if (valid(held, time)) {
232
+ if (held.expiresAt !== undefined && time >= held.expiresAt - CREDENTIAL_REFRESH_BEFORE_MS && time >= retryAt) void refresh()
233
+ return held
234
+ }
235
+ if (refreshing === undefined && time < retryAt) {
236
+ throw new Error('the container credentials could not be read')
237
+ }
238
+ await refresh()
239
+ if (valid(held, now())) return held
240
+ throw new Error('the container credentials could not be read')
241
+ },
242
+ }
243
+ }
244
+
245
+ /** The answer's text, read until `MAX_CREDENTIAL_BYTES` and no further: `null` past it. */
246
+ async function boundedText(response: Response): Promise<string | null> {
247
+ const declared = Number(response.headers.get('Content-Length') ?? '0')
248
+ if (declared > MAX_CREDENTIAL_BYTES || response.body === null) {
249
+ await response.body?.cancel()
250
+ return response.body === null ? '' : null
251
+ }
252
+ const reader = response.body.getReader()
253
+ const chunks: Uint8Array[] = []
254
+ let size = 0
255
+ for (;;) {
256
+ const { done, value } = await reader.read()
257
+ if (done) break
258
+ size += value.byteLength
259
+ if (size > MAX_CREDENTIAL_BYTES) {
260
+ await reader.cancel()
261
+ return null
262
+ }
263
+ chunks.push(value)
264
+ }
265
+ const bytes = new Uint8Array(size)
266
+ let offset = 0
267
+ for (const chunk of chunks) {
268
+ bytes.set(chunk, offset)
269
+ offset += chunk.byteLength
270
+ }
271
+ return new TextDecoder().decode(bytes)
272
+ }
273
+
274
+ /** The endpoint's answer, strictly: `AccessKeyId`, `SecretAccessKey`, `Token` and an ISO `Expiration`. */
275
+ function parseContainerCredentials(text: string): StorageCredentials | null {
276
+ let body: unknown
277
+ try {
278
+ body = JSON.parse(text)
279
+ } catch {
280
+ return null
281
+ }
282
+ if (typeof body !== 'object' || body === null) return null
283
+ const field = (key: string): unknown => Reflect.get(body, key)
284
+ const accessKeyId = field('AccessKeyId')
285
+ const secretAccessKey = field('SecretAccessKey')
286
+ const token = field('Token')
287
+ const expiration = field('Expiration')
288
+ if (typeof accessKeyId !== 'string' || accessKeyId === '' || typeof secretAccessKey !== 'string' || secretAccessKey === '') return null
289
+ if (typeof token !== 'string' || token === '' || typeof expiration !== 'string') return null
290
+ const expiresAt = Date.parse(expiration)
291
+ if (!Number.isFinite(expiresAt)) return null
292
+ return { accessKeyId, secretAccessKey, sessionToken: token, expiresAt }
293
+ }
294
+
295
+ /** The credentials a connection names: its key pair as given, or the container endpoint's. */
296
+ export function credentialProvider(source: StorageCredentialSource, options: ContainerCredentialOptions = {}): CredentialProvider {
297
+ if (source.kind === 'container') {
298
+ return containerCredentials(source.relativeUri, options)
299
+ }
300
+ const fixed: StorageCredentials = { accessKeyId: source.accessKeyId, secretAccessKey: source.secretAccessKey }
301
+ return { current: () => Promise.resolve(fixed) }
302
+ }
@@ -1,4 +1,5 @@
1
1
  import { type BlobStore, type FileObjectStore, type ObjectMetadata, type ObjectWriteOptions, type StoredObject } from '@fabrika/platform';
2
+ import { type ContainerCredentialOptions, type CredentialProvider, type StorageConnection } from './storage-connection';
2
3
  /** Connection details for an S3-compatible bucket. `endpoint` is what makes it R2, MinIO, or AWS. */
3
4
  export interface S3BlobStoreOptions {
4
5
  bucket: string;
@@ -18,10 +19,22 @@ interface BlobBody {
18
19
  body: ReadableStream;
19
20
  text(): Promise<string>;
20
21
  }
22
+ /** The client a store's next request goes through: one fixed client, or one rebuilt when its credentials rotate. */
23
+ export type S3ClientSource = () => Promise<Bun.S3Client>;
24
+ /** The options of one client, as `Bun.S3Client` takes them. */
25
+ export type S3ClientOptions = ConstructorParameters<typeof Bun.S3Client>[0];
26
+ export interface S3BlobStoreOpenOptions extends ContainerCredentialOptions {
27
+ /** Builds a client; `new Bun.S3Client` by default. Tests record what each client was built with. */
28
+ readonly client?: (options: S3ClientOptions) => Bun.S3Client;
29
+ }
21
30
  export declare class S3BlobStore implements BlobStore, FileObjectStore {
22
31
  #private;
23
- private readonly client;
24
- constructor(client: Bun.S3Client);
32
+ constructor(client: Bun.S3Client | S3ClientSource);
33
+ /**
34
+ * A store over a parsed connection (`parseStorageConnection`): its region and addressing, and credentials that are
35
+ * either fixed or the container endpoint's, refreshed before they expire. Never logs them.
36
+ */
37
+ static open(connection: StorageConnection, options?: S3BlobStoreOpenOptions): S3BlobStore;
25
38
  /** Build a store from plain connection options. Never logs them. */
26
39
  static connect(options: S3BlobStoreOptions): S3BlobStore;
27
40
  put(key: string, value: string | ArrayBuffer | ReadableStream): Promise<void>;
@@ -31,4 +44,9 @@ export declare class S3BlobStore implements BlobStore, FileObjectStore {
31
44
  read(key: string, signal?: AbortSignal): Promise<StoredObject | null>;
32
45
  readVersion(key: string, version: string, signal?: AbortSignal): Promise<StoredObject | null>;
33
46
  }
47
+ /**
48
+ * The client for `connection`, built once per set of credentials `provider` hands out: a store over fixed credentials
49
+ * keeps one client, one over the container endpoint gets a new client when the endpoint rotates them.
50
+ */
51
+ export declare function storageClients(connection: StorageConnection, provider: CredentialProvider, make?: (options: S3ClientOptions) => Bun.S3Client): S3ClientSource;
34
52
  export {};
@@ -2,7 +2,7 @@ export { APPLICATION_MIGRATION_BUNDLE, APPLICATION_MIGRATION_LEDGER, application
2
2
  export type { ApplicationDatabaseRoles } from './application-postgres-roles';
3
3
  export { applicationDatabaseSchema } from './application-schema';
4
4
  export { FileSystemAssetServer, type FileSystemAssetServerOptions } from './asset-server-fs';
5
- export { S3BlobStore, type S3BlobStoreOptions } from './blob-s3';
5
+ export { S3BlobStore, type S3BlobStoreOpenOptions, type S3BlobStoreOptions, type S3ClientOptions, type S3ClientSource, storageClients, } from './blob-s3';
6
6
  export { CONNECTION_CAPACITY_MESSAGE, ConnectionCapacityError, type ConnectionCapacityWait, DEFAULT_CONNECTION_WAIT_MS, isConnectionCapacityError, TOO_MANY_CONNECTIONS, withConnectionCapacity, } from './connection-capacity';
7
7
  export { databaseCodeQuery } from './database-code';
8
8
  export { decodeJob, type Job, PostgresJobConsumer, type PostgresJobConsumerOptions, PostgresJobQueue, type PostgresJobQueueOptions, } from './job-queue-postgres';
@@ -11,4 +11,5 @@ export { rewritePlaceholders, type RewrittenSql } from './placeholders';
11
11
  export { applyPostgresMigrations, definePostgresMigrationPlan, migrationChecksum, platformNodePostgresMigrationBundle, type PostgresApplicationMigrationSettings, type PostgresMigration, type PostgresMigrationBundle, PostgresMigrationError, postgresMigrationFilenames, postgresMigrationIdentity, type PostgresMigrationPlan, readPostgresMigrationBundle, type ReadPostgresMigrationBundleOptions, } from './postgres-migrations';
12
12
  export { definePostgresServiceMigrations, postgresMigrationResultMessage, type PostgresServiceMigrations, type PostgresServiceMigrationsConfig, } from './service-postgres-migrations';
13
13
  export { PostgresDatabase, PostgresStatement, type SqlBindValue } from './sql-postgres';
14
+ export { CONTAINER_CREDENTIALS_ORIGIN, type ContainerCredentialOptions, containerCredentials, CREDENTIAL_REFRESH_BEFORE_MS, CREDENTIAL_RETRY_MS, type CredentialProvider, credentialProvider, parseStorageConnection, type StorageConnection, StorageConnectionError, type StorageConnectionOptions, storageConnectionProblems, type StorageCredentials, type StorageCredentialSource, } from './storage-connection';
14
15
  export { type BackgroundTasks, type BackgroundTasksOptions, createBackgroundTasks } from './wait-until';
@@ -0,0 +1,78 @@
1
+ /** Where a store's credentials come from. */
2
+ export type StorageCredentialSource = {
3
+ readonly kind: 'static';
4
+ readonly accessKeyId: string;
5
+ readonly secretAccessKey: string;
6
+ }
7
+ /** The ECS container credentials endpoint, at the path the container's environment names. */
8
+ | {
9
+ readonly kind: 'container';
10
+ readonly relativeUri: string;
11
+ };
12
+ export interface StorageConnection {
13
+ readonly bucket: string;
14
+ /** Absent: the provider's default endpoint for the region (AWS S3). */
15
+ readonly endpoint?: string;
16
+ readonly region: string;
17
+ /** `virtual` addresses `https://<bucket>.<host>`; `path` (the default, as before) `https://<host>/<bucket>`. */
18
+ readonly addressing: 'path' | 'virtual';
19
+ readonly credentials: StorageCredentialSource;
20
+ }
21
+ export interface StorageConnectionOptions {
22
+ /** The region a connection that names none signs for: what the caller signed for before the variable. */
23
+ readonly defaultRegion: string;
24
+ /** Whether a static connection must name its endpoint (an application's always did). */
25
+ readonly endpoint: 'required' | 'optional';
26
+ /** The container's own environment, which holds the credentials endpoint's path; the process's by default. */
27
+ readonly environment?: Readonly<Record<string, string | undefined>>;
28
+ }
29
+ /** A connection the variables cannot describe; `problems` name variables only. */
30
+ export declare class StorageConnectionError extends Error {
31
+ readonly problems: readonly string[];
32
+ readonly name = "StorageConnectionError";
33
+ constructor(problems: readonly string[]);
34
+ }
35
+ /** Whether `value` is a `StorageConnectionError`, read structurally: a caller in another package may hold another copy. */
36
+ export declare function storageConnectionProblems(value: unknown): readonly string[] | null;
37
+ /**
38
+ * The connection the variables under `prefix` (`FABRIKA_APP_STORAGE`) describe, or `undefined` when none of them is
39
+ * set. `<prefix>_BUCKET`, `_ENDPOINT`, `_REGION`, `_ACCESS_KEY_ID` and `_SECRET_ACCESS_KEY` keep their meaning;
40
+ * `_ADDRESSING` is `path` or `virtual`, `_CREDENTIALS` is `static` (the key pair, the default) or `container`, which
41
+ * takes no key pair.
42
+ */
43
+ export declare function parseStorageConnection(variables: Readonly<Record<string, string | undefined>>, prefix: string, options: StorageConnectionOptions): StorageConnection | undefined;
44
+ /** A set of credentials a store signs with; `expiresAt` (epoch ms) only for short-lived ones. */
45
+ export interface StorageCredentials {
46
+ readonly accessKeyId: string;
47
+ readonly secretAccessKey: string;
48
+ readonly sessionToken?: string;
49
+ readonly expiresAt?: number;
50
+ }
51
+ /** The credentials a store signs its next request with. */
52
+ export interface CredentialProvider {
53
+ current(): Promise<StorageCredentials>;
54
+ }
55
+ export interface ContainerCredentialOptions {
56
+ /** The endpoint's origin; ECS serves it at this link-local address. Tests point it elsewhere. */
57
+ readonly origin?: string;
58
+ readonly fetch?: (input: string, init: RequestInit) => Promise<Response>;
59
+ readonly now?: () => number;
60
+ }
61
+ /** ECS's container credentials endpoint. */
62
+ export declare const CONTAINER_CREDENTIALS_ORIGIN = "http://169.254.170.2";
63
+ /** How long before their expiry a set of credentials is replaced; ECS rotates them well before. */
64
+ export declare const CREDENTIAL_REFRESH_BEFORE_MS: number;
65
+ /** How long after a failed or fruitless refresh the next one waits. */
66
+ export declare const CREDENTIAL_RETRY_MS = 30000;
67
+ /**
68
+ * Short-lived credentials from the ECS container credentials endpoint. The first request waits for the first set; while
69
+ * the held set is valid every request gets it at once, and within `CREDENTIAL_REFRESH_BEFORE_MS` of its expiry one
70
+ * refresh runs in the background. A refresh that fails, or answers a set that expires no later than the held one, waits
71
+ * `CREDENTIAL_RETRY_MS` before the next; an answer already expired is a failure. Only a request without a valid set
72
+ * waits for a fetch, and within the retry wait it fails at once instead. A failure is logged once until a refresh
73
+ * succeeds. The answer decides what a request is signed with, so no redirect is followed. Nothing logs a key, the token
74
+ * or the endpoint's path.
75
+ */
76
+ export declare function containerCredentials(relativeUri: string, options?: ContainerCredentialOptions): CredentialProvider;
77
+ /** The credentials a connection names: its key pair as given, or the container endpoint's. */
78
+ export declare function credentialProvider(source: StorageCredentialSource, options?: ContainerCredentialOptions): CredentialProvider;