@fabrika/auth-core 0.8.2 → 0.9.0-cloudflare.2

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 (44) hide show
  1. package/package.json +4 -3
  2. package/src/contract-canonical.ts +2 -1
  3. package/src/contract.ts +11 -3
  4. package/src/dev-environment.ts +45 -0
  5. package/src/framework-release.ts +2 -0
  6. package/src/framework-variables.ts +20 -2
  7. package/src/index.ts +6 -0
  8. package/src/managed-environment.ts +140 -0
  9. package/src/ops.ts +497 -0
  10. package/src/public-egress.ts +166 -0
  11. package/src/terminal.ts +105 -0
  12. package/src/token.ts +65 -5
  13. package/src/types.ts +4 -1
  14. package/types/src/app-environment.d.ts +24 -0
  15. package/types/src/canonical-path.d.ts +20 -0
  16. package/types/src/contract-canonical.d.ts +19 -0
  17. package/types/src/contract.d.ts +802 -0
  18. package/types/src/dev-environment.d.ts +37 -0
  19. package/types/src/device.d.ts +144 -0
  20. package/types/src/endpoint-digest.d.ts +58 -0
  21. package/types/src/endpoints.d.ts +65 -0
  22. package/types/src/environment.d.ts +58 -0
  23. package/types/src/framework-release.d.ts +2 -0
  24. package/types/src/framework-variables.d.ts +91 -0
  25. package/types/src/index.d.ts +29 -0
  26. package/types/src/installation-endpoint.d.ts +46 -0
  27. package/types/src/json.d.ts +13 -0
  28. package/types/src/locale.d.ts +14 -0
  29. package/types/src/mail.d.ts +67 -0
  30. package/types/src/managed-environment.d.ts +32 -0
  31. package/types/src/membership.d.ts +318 -0
  32. package/types/src/oauth.d.ts +7 -0
  33. package/types/src/ops.d.ts +181 -0
  34. package/types/src/path-segment.d.ts +5 -0
  35. package/types/src/permissions.d.ts +50 -0
  36. package/types/src/public-egress.d.ts +31 -0
  37. package/types/src/requirement.d.ts +24 -0
  38. package/types/src/rpc.d.ts +283 -0
  39. package/types/src/sha256.d.ts +2 -0
  40. package/types/src/terminal.d.ts +72 -0
  41. package/types/src/token.d.ts +240 -0
  42. package/types/src/types.d.ts +196 -0
  43. package/types/src/wire.d.ts +65 -0
  44. package/types/src/workloads.d.ts +25 -0
package/src/ops.ts ADDED
@@ -0,0 +1,497 @@
1
+ // The ops wire (ADR-0069): the one platform-composed row through which Control reaches an application environment's
2
+ // object on Cloudflare, the requests it sends there and the answers the object gives. Control and the framework both
3
+ // import it, so the two sides parse one shape. Every parser is strict: an unknown key, a missing field or a wrong type
4
+ // refuses the whole value.
5
+
6
+ import { isDigest } from './endpoint-digest'
7
+ import { FRAMEWORK_RELEASE_PATTERN } from './framework-release'
8
+ import { prop } from './json'
9
+ import { sha256Hex } from './sha256'
10
+ import { WORKLOAD_NAME } from './workloads'
11
+
12
+ /** Every ops request's path lies under this prefix, on the environment's own domain. */
13
+ export const OPS_PREFIX = '/__fabrika/ops/'
14
+
15
+ /**
16
+ * The fixed id of the composed row. An authored endpoint id starts with a letter, so no contract can take it. The row's
17
+ * digest is not a constant: proxy-core computes it where every row is digested, from these fields.
18
+ */
19
+ export const OPS_ROW_ID = '__fabrika.ops'
20
+
21
+ /** The composed row's path. */
22
+ export const OPS_ROW_PATH = `${OPS_PREFIX}*`
23
+
24
+ /** The composed row's method. */
25
+ export const OPS_METHOD = 'POST'
26
+
27
+ /** The one content type the composed row admits. */
28
+ export const OPS_CONTENT_TYPE = 'application/json'
29
+
30
+ /** The operations the object serves, each at `opsPath(operation)`. */
31
+ export const OPS_OPERATIONS = ['inspect', 'state', 'migrate'] as const
32
+
33
+ export type OpsOperation = (typeof OPS_OPERATIONS)[number]
34
+
35
+ export function opsPath(operation: OpsOperation): string {
36
+ return `${OPS_PREFIX}${operation}`
37
+ }
38
+
39
+ /** The operation a request path names, or `null` for any other path, which gets `opsRefusal()`. */
40
+ export function parseOpsOperation(path: string): OpsOperation | null {
41
+ return OPS_OPERATIONS.find((operation) => opsPath(operation) === path) ?? null
42
+ }
43
+
44
+ /**
45
+ * The one answer inside the prefix to a missing or wrong key, a wrong endpoint header, an unknown operation and a
46
+ * refused object name: the same status, no body and no headers, so none of them tells the caller which it was.
47
+ */
48
+ export const OPS_REFUSAL_STATUS = 404
49
+
50
+ export function opsRefusal(): Response {
51
+ return new Response(null, { status: OPS_REFUSAL_STATUS })
52
+ }
53
+
54
+ /** Ops key digests: `sha256:<64 hex>` of each key, joined by `,`; one, or two while a rotation reconciles. */
55
+ export type OpsKeyDigests = readonly [string] | readonly [string, string]
56
+
57
+ /** The digest of an ops key, the only form the object holds (`FABRIKA_OPS_KEY_DIGESTS`). */
58
+ export function opsKeyDigest(key: string): string {
59
+ return `sha256:${sha256Hex(key)}`
60
+ }
61
+
62
+ /** The value of `FABRIKA_OPS_KEY_DIGESTS`, or `null` unless it holds one or two distinct digests. */
63
+ export function parseOpsKeyDigests(value: string): OpsKeyDigests | null {
64
+ const [first, second, ...rest] = value.split(',')
65
+ if (first === undefined || !isDigest(first) || rest.length > 0) return null
66
+ if (second === undefined) return [first]
67
+ return isDigest(second) && second !== first ? [first, second] : null
68
+ }
69
+
70
+ /** The value Control writes into `FABRIKA_OPS_KEY_DIGESTS`; throws on a list `parseOpsKeyDigests` would refuse. */
71
+ export function formatOpsKeyDigests(digests: OpsKeyDigests): string {
72
+ const value = digests.join(',')
73
+ if (parseOpsKeyDigests(value) === null) throw new Error('ops key digests must be one or two distinct sha256 digests')
74
+ return value
75
+ }
76
+
77
+ /** The object of ordinary traffic without `FABRIKA_APPLICATION_OBJECT`, and the only one an ops request may name then. */
78
+ export const DEFAULT_APPLICATION_OBJECT = 'application'
79
+
80
+ /** The most names `FABRIKA_APPLICATION_OBJECTS` holds. */
81
+ export const MAX_APPLICATION_OBJECTS = 16
82
+
83
+ /** An object name: lowercase, at most 63 characters, safe as one segment of an R2 key. */
84
+ const APPLICATION_OBJECT_NAME = /^[a-z][a-z0-9-]{0,62}$/
85
+
86
+ export function parseApplicationObjectName(value: unknown): string | null {
87
+ return typeof value === 'string' && APPLICATION_OBJECT_NAME.test(value) ? value : null
88
+ }
89
+
90
+ /** The object of ordinary traffic, and the objects an ops request may name, which include it. */
91
+ export interface ApplicationObjects {
92
+ readonly object: string
93
+ readonly objects: readonly string[]
94
+ }
95
+
96
+ /**
97
+ * `FABRIKA_APPLICATION_OBJECT` and `FABRIKA_APPLICATION_OBJECTS` (distinct names joined by `,`, 1 to 16, holding the
98
+ * first), or `null`. Without either the object is `application`; a deploy writes both, so one alone is refused.
99
+ */
100
+ export function parseApplicationObjects(object: string | undefined, objects: string | undefined): ApplicationObjects | null {
101
+ if (object === undefined && objects === undefined) return { object: DEFAULT_APPLICATION_OBJECT, objects: [DEFAULT_APPLICATION_OBJECT] }
102
+ if (object === undefined || objects === undefined || parseApplicationObjectName(object) === null) return null
103
+ const names = objects.split(',')
104
+ const valid = names.length <= MAX_APPLICATION_OBJECTS && names.every((name) => parseApplicationObjectName(name) !== null)
105
+ return valid && new Set(names).size === names.length && names.includes(object) ? { object, objects: names } : null
106
+ }
107
+
108
+ /** The R2 key, in the environment's bucket, of the maintenance state of `object`. */
109
+ export function OPS_STATE_KEY(object: string): string {
110
+ if (parseApplicationObjectName(object) === null) throw new Error('an ops state key needs a valid object name')
111
+ return `__fabrika/ops/${object}.json`
112
+ }
113
+
114
+ /** The maintenance modes, from the most permissive. */
115
+ export const OPS_MODES = ['open', 'read-only', 'closed', 'inspect'] as const
116
+
117
+ export type OpsMode = (typeof OPS_MODES)[number]
118
+
119
+ /** A table's row count is capped here: a full count bills every row read. A count at the cap means at least the cap. */
120
+ export const OPS_ROW_COUNT_CAP = 100_000
121
+
122
+ /** `POST /__fabrika/ops/inspect`: the projection, or with `content` the content-bearing view (`data.content.read`). */
123
+ export interface OpsInspectRequest {
124
+ readonly object: string
125
+ readonly content: boolean
126
+ }
127
+
128
+ /** `POST /__fabrika/ops/state`: a maintenance transition under a generation Control allocated. */
129
+ export interface OpsStateRequest {
130
+ readonly object: string
131
+ readonly generation: number
132
+ readonly mode: OpsMode
133
+ }
134
+
135
+ /** Sent once the state is published and the drain is over; `stillRunning` counts what ran past the drain's bound. */
136
+ export interface OpsStateAck {
137
+ readonly generation: number
138
+ readonly mode: OpsMode
139
+ readonly stillRunning: number
140
+ }
141
+
142
+ /** `POST /__fabrika/ops/migrate`: run the pending migrations under the published generation. */
143
+ export interface OpsMigrateRequest {
144
+ readonly object: string
145
+ readonly generation: number
146
+ }
147
+
148
+ /** The state a transition is judged against: the object's current generation and mode, `null` before the first. */
149
+ export interface OpsPublishedState {
150
+ readonly generation: number
151
+ readonly mode: OpsMode
152
+ }
153
+
154
+ /**
155
+ * Whether a transition is stale: a lower generation, or the same with another mode. The same generation and mode is a
156
+ * retry, which the object replays.
157
+ */
158
+ export function opsTransitionRefused(current: OpsPublishedState | null, request: OpsPublishedState): boolean {
159
+ if (current === null) return false
160
+ return request.generation < current.generation || (request.generation === current.generation && request.mode !== current.mode)
161
+ }
162
+
163
+ /** The status of a stale refusal. It is answered only after authentication, so it may say what is published. */
164
+ export const OPS_STALE_STATUS = 409
165
+
166
+ /** The body of a stale refusal of a transition or a migration. */
167
+ export interface OpsStaleRefusal {
168
+ readonly refused: 'stale_generation'
169
+ readonly published: OpsPublishedState | null
170
+ }
171
+
172
+ /** One row of the object's migration ledger. */
173
+ export interface OpsMigration {
174
+ readonly bundle: string
175
+ readonly name: string
176
+ readonly checksum: string
177
+ readonly appliedAt: string
178
+ }
179
+
180
+ /** Sent once the migrations ran and the application booted, with the new ledger. */
181
+ export interface OpsMigrateAck {
182
+ readonly generation: number
183
+ readonly migrations: readonly OpsMigration[]
184
+ }
185
+
186
+ export interface OpsMaintenance {
187
+ readonly mode: OpsMode
188
+ /** `null` while no transition was ever published: the object is `open`. */
189
+ readonly generation: number | null
190
+ /** Whether R2 holds this state; `false` while its put is pending. */
191
+ readonly published: boolean
192
+ }
193
+
194
+ export interface OpsTableCount {
195
+ readonly name: string
196
+ /** At most `OPS_ROW_COUNT_CAP`. */
197
+ readonly rows: number
198
+ }
199
+
200
+ export interface OpsDatabase {
201
+ readonly sizeBytes: number
202
+ readonly tables: readonly OpsTableCount[]
203
+ }
204
+
205
+ export interface OpsScheduler {
206
+ /** The current alarm, or `null` when none is set. */
207
+ readonly alarm: string | null
208
+ }
209
+
210
+ /** A job's last run and its outcome. */
211
+ export interface OpsJob {
212
+ readonly job: string
213
+ readonly lastStatus: 'succeeded' | 'failed' | null
214
+ readonly lastStartedAt: string | null
215
+ readonly lastFinishedAt: string | null
216
+ readonly lastDurationMs: number | null
217
+ }
218
+
219
+ export type OpsFileStatus = 'pending' | 'quarantined' | 'live' | 'rejected'
220
+
221
+ export interface OpsFileCount {
222
+ readonly kind: string
223
+ readonly status: OpsFileStatus
224
+ readonly count: number
225
+ }
226
+
227
+ /** A delivery is `claimed` while it holds a lease, `completed` once its handler's transaction cleared it. */
228
+ export interface OpsWebhookCount {
229
+ readonly webhook: string
230
+ readonly state: 'claimed' | 'completed'
231
+ readonly count: number
232
+ }
233
+
234
+ export interface OpsBootFailure {
235
+ readonly at: string
236
+ }
237
+
238
+ /** The boot failure with the application's error text, which is content. */
239
+ export interface OpsBootFailureContent extends OpsBootFailure {
240
+ readonly message: string
241
+ readonly stack: string | null
242
+ }
243
+
244
+ /**
245
+ * The allowlisted projection (`data.read`): counts, sizes, timestamps, the identifiers the platform or the contract
246
+ * names, and status codes. Every timestamp is ISO 8601 in UTC with milliseconds.
247
+ */
248
+ export interface OpsView {
249
+ readonly release: string
250
+ readonly maintenance: OpsMaintenance
251
+ readonly database: OpsDatabase
252
+ readonly migrations: readonly OpsMigration[]
253
+ readonly scheduler: OpsScheduler
254
+ readonly jobs: readonly OpsJob[]
255
+ readonly files: readonly OpsFileCount[]
256
+ readonly webhooks: readonly OpsWebhookCount[]
257
+ readonly bootFailure: OpsBootFailure | null
258
+ }
259
+
260
+ /** The view a `data.content.read` caller gets: the projection, with the application's error text. */
261
+ export interface OpsContentView extends Omit<OpsView, 'bootFailure'> {
262
+ readonly bootFailure: OpsBootFailureContent | null
263
+ }
264
+
265
+ // A request's `object` is only well-formed here; the handler refuses a name its list does not hold with `opsRefusal()`.
266
+ export function parseOpsInspectRequest(body: unknown): OpsInspectRequest | null {
267
+ const object = parseApplicationObjectName(prop(body, 'object'))
268
+ const content = prop(body, 'content')
269
+ return exactKeys(body, ['object', 'content']) && object !== null && typeof content === 'boolean' ? { object, content } : null
270
+ }
271
+
272
+ export function parseOpsStateRequest(body: unknown): OpsStateRequest | null {
273
+ if (!exactKeys(body, ['object', 'generation', 'mode'])) return null
274
+ const object = parseApplicationObjectName(prop(body, 'object'))
275
+ const generation = readGeneration(prop(body, 'generation'))
276
+ const mode = readMode(prop(body, 'mode'))
277
+ return object === null || generation === null || mode === null ? null : { object, generation, mode }
278
+ }
279
+
280
+ export function parseOpsStateAck(body: unknown): OpsStateAck | null {
281
+ if (!exactKeys(body, ['generation', 'mode', 'stillRunning'])) return null
282
+ const generation = readGeneration(prop(body, 'generation'))
283
+ const mode = readMode(prop(body, 'mode'))
284
+ const stillRunning = readCount(prop(body, 'stillRunning'))
285
+ return generation === null || mode === null || stillRunning === null ? null : { generation, mode, stillRunning }
286
+ }
287
+
288
+ export function parseOpsMigrateRequest(body: unknown): OpsMigrateRequest | null {
289
+ const object = parseApplicationObjectName(prop(body, 'object'))
290
+ const generation = readGeneration(prop(body, 'generation'))
291
+ return exactKeys(body, ['object', 'generation']) && object !== null && generation !== null ? { object, generation } : null
292
+ }
293
+
294
+ export function parseOpsStaleRefusal(body: unknown): OpsStaleRefusal | null {
295
+ if (!exactKeys(body, ['refused', 'published']) || prop(body, 'refused') !== 'stale_generation') return null
296
+ const raw = prop(body, 'published')
297
+ if (raw === null) return { refused: 'stale_generation', published: null }
298
+ if (!exactKeys(raw, ['generation', 'mode'])) return null
299
+ const generation = readGeneration(prop(raw, 'generation'))
300
+ const mode = readMode(prop(raw, 'mode'))
301
+ return generation === null || mode === null ? null : { refused: 'stale_generation', published: { generation, mode } }
302
+ }
303
+
304
+ export function parseOpsMigrateAck(body: unknown): OpsMigrateAck | null {
305
+ if (!exactKeys(body, ['generation', 'migrations'])) return null
306
+ const generation = readGeneration(prop(body, 'generation'))
307
+ const migrations = readList(prop(body, 'migrations'), readMigration)
308
+ return generation === null || migrations === null ? null : { generation, migrations }
309
+ }
310
+
311
+ export function parseOpsView(body: unknown): OpsView | null {
312
+ const failure = prop(body, 'bootFailure')
313
+ const bootFailure = failure === null ? null : readBootFailure(failure)
314
+ if (bootFailure === undefined) return null
315
+ const view = readViewFields(body)
316
+ return view === null ? null : { ...view, bootFailure }
317
+ }
318
+
319
+ export function parseOpsContentView(body: unknown): OpsContentView | null {
320
+ const failure = prop(body, 'bootFailure')
321
+ const bootFailure = failure === null ? null : readBootFailureContent(failure)
322
+ if (bootFailure === undefined) return null
323
+ const view = readViewFields(body)
324
+ return view === null ? null : { ...view, bootFailure }
325
+ }
326
+
327
+ const VIEW_KEYS = ['release', 'maintenance', 'database', 'migrations', 'scheduler', 'jobs', 'files', 'webhooks', 'bootFailure']
328
+ const FILE_STATUSES: readonly OpsFileStatus[] = ['pending', 'quarantined', 'live', 'rejected']
329
+ const WEBHOOK_STATES = ['claimed', 'completed'] as const
330
+ const JOB_STATUSES = ['succeeded', 'failed'] as const
331
+ /** The form `Date.prototype.toISOString` and SQLite's `%Y-%m-%dT%H:%M:%fZ` both write. */
332
+ const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
333
+ /** `@fabrika/db`'s `isPlainIdentifier`: the only table names the data layer admits. */
334
+ const TABLE_NAME = /^[a-z_][a-z0-9_]{0,62}$/
335
+ /** The contract build's authored-name rule (`@fabrika/app/contract`), which a file kind follows. */
336
+ const CONTRACT_NAME = /^[A-Za-z][A-Za-z0-9_]*$/
337
+ /** `@fabrika/db`'s SQLite migration runner: a bundle name, a migration file name and a file's SHA-256 hex. */
338
+ const MIGRATION_BUNDLE = /^[a-z][a-z0-9-]*$/
339
+ const MIGRATION_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.sql$/
340
+ const MIGRATION_CHECKSUM = /^[0-9a-f]{64}$/
341
+
342
+ /** Every field of the view but the boot failure, whose form differs between the two views. */
343
+ function readViewFields(body: unknown): Omit<OpsView, 'bootFailure'> | null {
344
+ if (!exactKeys(body, VIEW_KEYS)) return null
345
+ const release = prop(body, 'release')
346
+ const maintenance = readMaintenance(prop(body, 'maintenance'))
347
+ const database = readDatabase(prop(body, 'database'))
348
+ const migrations = readList(prop(body, 'migrations'), readMigration)
349
+ const scheduler = readScheduler(prop(body, 'scheduler'))
350
+ const jobs = readList(prop(body, 'jobs'), readJob)
351
+ const files = readList(prop(body, 'files'), readFileCount)
352
+ const webhooks = readList(prop(body, 'webhooks'), readWebhookCount)
353
+ if (
354
+ typeof release !== 'string' || !FRAMEWORK_RELEASE_PATTERN.test(release) || maintenance === null || database === null || migrations === null
355
+ || scheduler === null || jobs === null || files === null || webhooks === null
356
+ ) {
357
+ return null
358
+ }
359
+ return { release, maintenance, database, migrations, scheduler, jobs, files, webhooks }
360
+ }
361
+
362
+ function readMaintenance(value: unknown): OpsMaintenance | null {
363
+ if (!exactKeys(value, ['mode', 'generation', 'published'])) return null
364
+ const mode = readMode(prop(value, 'mode'))
365
+ const rawGeneration = prop(value, 'generation')
366
+ const generation = rawGeneration === null ? null : readGeneration(rawGeneration)
367
+ const published = prop(value, 'published')
368
+ if (mode === null || (rawGeneration !== null && generation === null) || typeof published !== 'boolean') return null
369
+ return { mode, generation, published }
370
+ }
371
+
372
+ function readDatabase(value: unknown): OpsDatabase | null {
373
+ if (!exactKeys(value, ['sizeBytes', 'tables'])) return null
374
+ const sizeBytes = readCount(prop(value, 'sizeBytes'))
375
+ const tables = readList(prop(value, 'tables'), readTableCount)
376
+ return sizeBytes === null || tables === null ? null : { sizeBytes, tables }
377
+ }
378
+
379
+ function readTableCount(value: unknown): OpsTableCount | null {
380
+ if (!exactKeys(value, ['name', 'rows'])) return null
381
+ const name = readMatch(prop(value, 'name'), TABLE_NAME)
382
+ const rows = readCount(prop(value, 'rows'))
383
+ return name === null || rows === null || rows > OPS_ROW_COUNT_CAP ? null : { name, rows }
384
+ }
385
+
386
+ function readMigration(value: unknown): OpsMigration | null {
387
+ if (!exactKeys(value, ['bundle', 'name', 'checksum', 'appliedAt'])) return null
388
+ const bundle = readMatch(prop(value, 'bundle'), MIGRATION_BUNDLE)
389
+ const name = readMatch(prop(value, 'name'), MIGRATION_NAME)
390
+ const checksum = readMatch(prop(value, 'checksum'), MIGRATION_CHECKSUM)
391
+ const appliedAt = readTimestamp(prop(value, 'appliedAt'))
392
+ return bundle === null || name === null || checksum === null || appliedAt === null ? null : { bundle, name, checksum, appliedAt }
393
+ }
394
+
395
+ function readScheduler(value: unknown): OpsScheduler | null {
396
+ if (!exactKeys(value, ['alarm'])) return null
397
+ const raw = prop(value, 'alarm')
398
+ const alarm = raw === null ? null : readTimestamp(raw)
399
+ return raw !== null && alarm === null ? null : { alarm }
400
+ }
401
+
402
+ function readJob(value: unknown): OpsJob | null {
403
+ if (!exactKeys(value, ['job', 'lastStatus', 'lastStartedAt', 'lastFinishedAt', 'lastDurationMs'])) return null
404
+ const job = readMatch(prop(value, 'job'), WORKLOAD_NAME)
405
+ const lastStatus = readNullable(prop(value, 'lastStatus'), (status) => readEnum(status, JOB_STATUSES))
406
+ const lastStartedAt = readNullable(prop(value, 'lastStartedAt'), readTimestamp)
407
+ const lastFinishedAt = readNullable(prop(value, 'lastFinishedAt'), readTimestamp)
408
+ const lastDurationMs = readNullable(prop(value, 'lastDurationMs'), readCount)
409
+ if (job === null || lastStatus === undefined || lastStartedAt === undefined || lastFinishedAt === undefined || lastDurationMs === undefined) {
410
+ return null
411
+ }
412
+ return { job, lastStatus, lastStartedAt, lastFinishedAt, lastDurationMs }
413
+ }
414
+
415
+ function readFileCount(value: unknown): OpsFileCount | null {
416
+ if (!exactKeys(value, ['kind', 'status', 'count'])) return null
417
+ const kind = readMatch(prop(value, 'kind'), CONTRACT_NAME)
418
+ const status = readEnum(prop(value, 'status'), FILE_STATUSES)
419
+ const count = readCount(prop(value, 'count'))
420
+ return kind === null || status === null || count === null ? null : { kind, status, count }
421
+ }
422
+
423
+ function readWebhookCount(value: unknown): OpsWebhookCount | null {
424
+ if (!exactKeys(value, ['webhook', 'state', 'count'])) return null
425
+ const webhook = readMatch(prop(value, 'webhook'), WORKLOAD_NAME)
426
+ const state = readEnum(prop(value, 'state'), WEBHOOK_STATES)
427
+ const count = readCount(prop(value, 'count'))
428
+ return webhook === null || state === null || count === null ? null : { webhook, state, count }
429
+ }
430
+
431
+ /** `undefined` for a value that is no boot failure; the caller reads `null` as none before calling. */
432
+ function readBootFailure(value: unknown): OpsBootFailure | undefined {
433
+ const at = readTimestamp(prop(value, 'at'))
434
+ return exactKeys(value, ['at']) && at !== null ? { at } : undefined
435
+ }
436
+
437
+ function readBootFailureContent(value: unknown): OpsBootFailureContent | undefined {
438
+ if (!exactKeys(value, ['at', 'message', 'stack'])) return undefined
439
+ const at = readTimestamp(prop(value, 'at'))
440
+ const message = prop(value, 'message')
441
+ const stack = prop(value, 'stack')
442
+ if (at === null || typeof message !== 'string' || (stack !== null && typeof stack !== 'string')) return undefined
443
+ return { at, message, stack }
444
+ }
445
+
446
+ /** Whether `value` is a plain object holding exactly `keys`: no key missing, none unknown. */
447
+ function exactKeys(value: unknown, keys: readonly string[]): boolean {
448
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
449
+ const own = Object.keys(value)
450
+ return own.length === keys.length && keys.every((key) => Object.hasOwn(value, key))
451
+ }
452
+
453
+ function readList<T>(value: unknown, read: (item: unknown) => T | null): readonly T[] | null {
454
+ if (!Array.isArray(value)) return null
455
+ const items: T[] = []
456
+ for (const item of value) {
457
+ const parsed = read(item)
458
+ if (parsed === null) return null
459
+ items.push(parsed)
460
+ }
461
+ return items
462
+ }
463
+
464
+ /** `null` stays `null`; anything else is read, and `undefined` marks a value `read` refused. */
465
+ function readNullable<T>(value: unknown, read: (value: unknown) => T | null): T | null | undefined {
466
+ if (value === null) return null
467
+ return read(value) ?? undefined
468
+ }
469
+
470
+ function readEnum<T extends string>(value: unknown, members: readonly T[]): T | null {
471
+ return members.find((member) => member === value) ?? null
472
+ }
473
+
474
+ function readMode(value: unknown): OpsMode | null {
475
+ return readEnum(value, OPS_MODES)
476
+ }
477
+
478
+ /** A generation Control allocated: a positive safe integer. */
479
+ function readGeneration(value: unknown): number | null {
480
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : null
481
+ }
482
+
483
+ function readCount(value: unknown): number | null {
484
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null
485
+ }
486
+
487
+ /** An identifier the platform or the contract names, in its owner's format: free text never fits one. */
488
+ function readMatch(value: unknown, pattern: RegExp): string | null {
489
+ return typeof value === 'string' && pattern.test(value) ? value : null
490
+ }
491
+
492
+ /** `Date` rolls an impossible date over (`02-31` to `03-03`), so the instant must print back as the same text. */
493
+ function readTimestamp(value: unknown): string | null {
494
+ if (typeof value !== 'string' || !TIMESTAMP.test(value)) return null
495
+ const instant = new Date(value)
496
+ return !Number.isNaN(instant.getTime()) && instant.toISOString() === value ? value : null
497
+ }
@@ -0,0 +1,166 @@
1
+ // `egress: 'public'`: a cron job that calls the websites its operators name (a crawler, an auditor, a link checker)
2
+ // reaches any public host over HTTPS or HTTP, and never the installation or a private network (ADR-0070). These are the
3
+ // rules a URL alone decides, which the runtime guard and the checker share. The guard adds the installation's own hosts
4
+ // and, where the runtime exposes name resolution, the addresses a name resolves to.
5
+
6
+ /** The declared form of public egress: every public host, over HTTPS or HTTP, on its default port. */
7
+ export const PUBLIC_EGRESS = 'public'
8
+
9
+ export type PublicEgress = typeof PUBLIC_EGRESS
10
+
11
+ /** What a site declares in `egress`: its exact HTTPS origins, sorted, or every public host (a cron job only). */
12
+ export type DeclaredEgress = readonly string[] | PublicEgress
13
+
14
+ /**
15
+ * The name suffixes public egress refuses, each with every name under it: local and special-use names (RFC 6761,
16
+ * RFC 6762, RFC 8375, RFC 9476), the names private networks conventionally use (`.internal` holds Google's metadata
17
+ * host and Control's own `operations.internal`), and the platform subdomains an installation is served on beside its
18
+ * own domains: Cloudflare's `workers.dev`, where its Workers have their default routes, and Zerops' `zerops.app`, where
19
+ * its proxies, Control and IAM have their subdomains (a namespace proxy's `proxy-…-8080.<region>.zerops.app`), with the
20
+ * `zerops` suffix of a Zerops project's private network. Control knows no list of those subdomains, so every one is
21
+ * refused, another installation's too.
22
+ */
23
+ export const PUBLIC_EGRESS_REFUSED_SUFFIXES = [
24
+ 'localhost',
25
+ 'local',
26
+ 'internal',
27
+ 'intranet',
28
+ 'lan',
29
+ 'home',
30
+ 'corp',
31
+ 'private',
32
+ 'arpa',
33
+ 'test',
34
+ 'invalid',
35
+ 'example',
36
+ 'onion',
37
+ 'alt',
38
+ 'zerops',
39
+ 'zerops.app',
40
+ 'workers.dev',
41
+ ] as const
42
+
43
+ /** A host name without its trailing dots, lowercased: the form every comparison here uses. */
44
+ export function normalizedHost(hostname: string): string {
45
+ return hostname.toLowerCase().replace(/\.+$/, '')
46
+ }
47
+
48
+ const IPV4 = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
49
+
50
+ /**
51
+ * Why public egress refuses `url`, or `null` when the URL alone admits it: a scheme other than `https:` and `http:`, a
52
+ * port other than the scheme's default, an IP literal, a name of one label, a name under a refused suffix, or one of
53
+ * `refusedHosts` (normalized names). A host it admits may still resolve to a private address, which only a runtime that
54
+ * resolves names refuses.
55
+ */
56
+ export function publicEgressRefusal(url: URL, refusedHosts: ReadonlySet<string> = new Set()): string | null {
57
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return `${url.protocol} is not https: or http:`
58
+ if (url.port !== '') return `port ${url.port} is not the default port of ${url.protocol}`
59
+ const host = normalizedHost(url.hostname)
60
+ if (host.startsWith('[') || IPV4.test(host)) return `${host} is an IP address, not a public host name`
61
+ if (!host.includes('.')) return `${host} is a name of one label, as an internal service or a local machine has`
62
+ if (host.split('.').some((label) => label === '')) return `${host} has an empty label`
63
+ const suffix = PUBLIC_EGRESS_REFUSED_SUFFIXES.find((refused) => host === refused || host.endsWith(`.${refused}`))
64
+ if (suffix !== undefined) return `${host} is under .${suffix}, which names no public website`
65
+ if (refusedHosts.has(host)) return `${host} is a host of this installation`
66
+ return null
67
+ }
68
+
69
+ /**
70
+ * Whether `address` (an IPv4 or IPv6 address, as a resolver answers it) is a public unicast address: not private,
71
+ * loopback, link-local (which holds the cloud metadata address 169.254.169.254), shared, multicast, reserved,
72
+ * documentation, or an IPv6 form that embeds or tunnels an IPv4 address it cannot vouch for. A text that is no address
73
+ * is not public.
74
+ */
75
+ export function isPublicAddress(address: string): boolean {
76
+ const v4 = ipv4Octets(address)
77
+ if (v4 !== null) return isPublicIpv4(v4)
78
+ const words = ipv6Words(address)
79
+ if (words === null) return false
80
+ const [w0 = 0, w1 = 0, w2 = 0, w3 = 0, w4 = 0, w5 = 0, w6 = 0, w7 = 0] = words
81
+ // ::ffff:a.b.c.d, an IPv4 address in IPv6 form, is that IPv4 address.
82
+ if (w0 === 0 && w1 === 0 && w2 === 0 && w3 === 0 && w4 === 0 && w5 === 0xffff) {
83
+ return isPublicIpv4([w6 >> 8, w6 & 0xff, w7 >> 8, w7 & 0xff])
84
+ }
85
+ // Only global unicast (2000::/3) is public; every other block is local, multicast, reserved or a translation prefix.
86
+ if ((w0 & 0xe000) !== 0x2000) return false
87
+ // 2001::/32 Teredo, 2001:10::/28 ORCHID, 2001:20::/28 ORCHIDv2, 2001:db8::/32 documentation, 2002::/16 6to4.
88
+ if (w0 === 0x2001 && (w1 === 0 || (w1 & 0xfff0) === 0x10 || (w1 & 0xfff0) === 0x20 || w1 === 0x0db8)) return false
89
+ if (w0 === 0x2002) return false
90
+ // 3fff::/20 documentation (RFC 9637).
91
+ if (w0 === 0x3fff && (w1 & 0xf000) === 0) return false
92
+ return true
93
+ }
94
+
95
+ /** The non-public IPv4 blocks, each as its network (a 32-bit number) and its prefix length. */
96
+ const IPV4_REFUSED: readonly (readonly [number, number])[] = [
97
+ [0x00000000, 8], // 0.0.0.0/8 this network
98
+ [0x0a000000, 8], // 10.0.0.0/8 private
99
+ [0x64400000, 10], // 100.64.0.0/10 shared address space
100
+ [0x7f000000, 8], // 127.0.0.0/8 loopback
101
+ [0xa9fe0000, 16], // 169.254.0.0/16 link-local, the cloud metadata address
102
+ [0xac100000, 12], // 172.16.0.0/12 private
103
+ [0xc0000000, 24], // 192.0.0.0/24 IETF protocol assignments
104
+ [0xc0000200, 24], // 192.0.2.0/24 documentation
105
+ [0xc0586300, 24], // 192.88.99.0/24 6to4 relay anycast
106
+ [0xc0a80000, 16], // 192.168.0.0/16 private
107
+ [0xc6120000, 15], // 198.18.0.0/15 benchmarking
108
+ [0xc6336400, 24], // 198.51.100.0/24 documentation
109
+ [0xcb007100, 24], // 203.0.113.0/24 documentation
110
+ [0xe0000000, 4], // 224.0.0.0/4 multicast
111
+ [0xf0000000, 4], // 240.0.0.0/4 reserved, broadcast
112
+ ]
113
+
114
+ function isPublicIpv4(octets: readonly number[]): boolean {
115
+ const [a = 0, b = 0, c = 0, d = 0] = octets
116
+ const value = ((a << 24) >>> 0) + (b << 16) + (c << 8) + d
117
+ return !IPV4_REFUSED.some(([network, prefix]) => {
118
+ const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0
119
+ return ((value & mask) >>> 0) === network
120
+ })
121
+ }
122
+
123
+ function ipv4Octets(text: string): number[] | null {
124
+ if (!IPV4.test(text)) return null
125
+ const octets = text.split('.').map((part) => Number.parseInt(part, 10))
126
+ return octets.every((octet) => octet >= 0 && octet <= 255) ? octets : null
127
+ }
128
+
129
+ const HEX_WORD = /^[0-9a-f]{1,4}$/i
130
+
131
+ /** The eight 16-bit words of an IPv6 address (brackets and a zone allowed, an embedded IPv4 tail too), or `null`. */
132
+ function ipv6Words(text: string): number[] | null {
133
+ let rest = text.startsWith('[') && text.endsWith(']') ? text.slice(1, -1) : text
134
+ const zone = rest.indexOf('%')
135
+ if (zone !== -1) rest = rest.slice(0, zone)
136
+ if (!rest.includes(':')) return null
137
+ const tailAt = rest.lastIndexOf(':')
138
+ const tail = ipv4Octets(rest.slice(tailAt + 1))
139
+ const embedded: number[] = []
140
+ if (tail !== null) {
141
+ const [a = 0, b = 0, c = 0, d = 0] = tail
142
+ embedded.push((a << 8) | b, (c << 8) | d)
143
+ rest = rest.slice(0, tailAt + 1) + '0'
144
+ }
145
+ const halves = rest.split('::')
146
+ if (halves.length > 2) return null
147
+ const parse = (half: string | undefined): number[] | null => {
148
+ if (half === undefined || half === '') return []
149
+ const parts = half.split(':')
150
+ if (!parts.every((part) => HEX_WORD.test(part))) return null
151
+ return parts.map((part) => Number.parseInt(part, 16))
152
+ }
153
+ const head = parse(halves[0])
154
+ const back = parse(halves[1])
155
+ if (head === null || back === null) return null
156
+ if (tail !== null) {
157
+ // The placeholder word stands for the two words of the IPv4 tail.
158
+ const last = halves.length === 2 ? back : head
159
+ last.pop()
160
+ last.push(...embedded)
161
+ }
162
+ const missing = 8 - head.length - back.length
163
+ if (halves.length === 1) return missing === 0 ? head : null
164
+ if (missing < 1) return null
165
+ return [...head, ...Array.from({ length: missing }, () => 0), ...back]
166
+ }