@fabrika/auth-core 0.8.2 → 0.9.0-cloudflare.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 (42) hide show
  1. package/package.json +4 -3
  2. package/src/contract-canonical.ts +1 -0
  3. package/src/contract.ts +6 -0
  4. package/src/dev-environment.ts +45 -0
  5. package/src/framework-release.ts +2 -0
  6. package/src/framework-variables.ts +14 -2
  7. package/src/index.ts +5 -0
  8. package/src/managed-environment.ts +136 -0
  9. package/src/ops.ts +497 -0
  10. package/src/terminal.ts +105 -0
  11. package/src/token.ts +65 -5
  12. package/src/types.ts +4 -1
  13. package/types/src/app-environment.d.ts +24 -0
  14. package/types/src/canonical-path.d.ts +20 -0
  15. package/types/src/contract-canonical.d.ts +19 -0
  16. package/types/src/contract.d.ts +800 -0
  17. package/types/src/dev-environment.d.ts +37 -0
  18. package/types/src/device.d.ts +144 -0
  19. package/types/src/endpoint-digest.d.ts +58 -0
  20. package/types/src/endpoints.d.ts +65 -0
  21. package/types/src/environment.d.ts +58 -0
  22. package/types/src/framework-release.d.ts +2 -0
  23. package/types/src/framework-variables.d.ts +86 -0
  24. package/types/src/index.d.ts +28 -0
  25. package/types/src/installation-endpoint.d.ts +46 -0
  26. package/types/src/json.d.ts +13 -0
  27. package/types/src/locale.d.ts +14 -0
  28. package/types/src/mail.d.ts +67 -0
  29. package/types/src/managed-environment.d.ts +32 -0
  30. package/types/src/membership.d.ts +318 -0
  31. package/types/src/oauth.d.ts +7 -0
  32. package/types/src/ops.d.ts +181 -0
  33. package/types/src/path-segment.d.ts +5 -0
  34. package/types/src/permissions.d.ts +50 -0
  35. package/types/src/requirement.d.ts +24 -0
  36. package/types/src/rpc.d.ts +283 -0
  37. package/types/src/sha256.d.ts +2 -0
  38. package/types/src/terminal.d.ts +72 -0
  39. package/types/src/token.d.ts +240 -0
  40. package/types/src/types.d.ts +196 -0
  41. package/types/src/wire.d.ts +65 -0
  42. 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,105 @@
1
+ // What an application declares and calls to sign a person in on an enrolled terminal (ADR-0067): its identification
2
+ // page, and the identification operations a handler asks IAM for. IAM takes the asserting application from the
3
+ // verified transport, never from the input: over `/membership/*` the application's membership transport key pins it, and
4
+ // over a Workers binding the `props` the deployer wrote on the application's `IAM` binding pin it. The credential must
5
+ // also verify for that application, but its audience alone proves nothing.
6
+
7
+ import { isCanonicalPath } from './canonical-path'
8
+ import type { MembershipCaller } from './membership'
9
+
10
+ /** The terminal declaration of a contract: the page on the application's own origin that identifies a person. */
11
+ export interface TerminalArtifact {
12
+ readonly identify: string
13
+ }
14
+
15
+ /** The longest identification path a contract declares. */
16
+ export const MAX_TERMINAL_IDENTIFY_PATH_LENGTH = 200
17
+
18
+ /** The query parameter IAM appends to the identification page: the identification's id. */
19
+ export const IDENTIFICATION_QUERY_PARAMETER = 'identification'
20
+
21
+ /** The path prefix the platform owns on every application host. */
22
+ const PLATFORM_PATH = '/__fabrika'
23
+
24
+ /**
25
+ * Why `path` is not an identification page, or `null`: an absolute, canonical path on the application's own origin,
26
+ * with no query or fragment (IAM appends its own) and outside the platform's `/__fabrika`.
27
+ */
28
+ export function terminalIdentifyProblem(path: string): string | null {
29
+ if (path.length === 0 || path.length > MAX_TERMINAL_IDENTIFY_PATH_LENGTH) {
30
+ return `is 1 to ${MAX_TERMINAL_IDENTIFY_PATH_LENGTH} characters`
31
+ }
32
+ if (!path.startsWith('/') || path.startsWith('//')) {
33
+ return "is not an absolute path on the application's own origin (write it as '/identify')"
34
+ }
35
+ if (/[?#\s\p{Cc}]/u.test(path)) {
36
+ return 'carries a query, a fragment, whitespace or a control character; IAM appends the query itself'
37
+ }
38
+ if (!isCanonicalPath(path)) {
39
+ return 'is not a canonical path: no empty, `.` or `..` segment, no `\\` and no encoded separator'
40
+ }
41
+ if (path === PLATFORM_PATH || path.startsWith(`${PLATFORM_PATH}/`)) {
42
+ return `lies under ${PLATFORM_PATH}, which the platform owns`
43
+ }
44
+ return null
45
+ }
46
+
47
+ /** Every identification operation carries the caller's verified credential: a public procedure's workload token. */
48
+ export type TerminalCaller = MembershipCaller
49
+
50
+ /**
51
+ * Why IAM refused. `not_found` is an identification that is unknown, expired, consumed, cancelled, of another
52
+ * application, or whose terminal no longer lists the application: alike, so an id reveals nothing. `invalid_principal`
53
+ * is a principal that cannot sign in on a terminal: unknown, disabled, not a person, or external (ADR-0051).
54
+ */
55
+ export type TerminalFailure = {
56
+ ok: false
57
+ reason: 'missing_token' | 'invalid_token' | 'not_allowed' | 'not_found' | 'invalid_principal'
58
+ }
59
+
60
+ export type TerminalFailureReason = TerminalFailure['reason']
61
+
62
+ /** The terminal an identification was opened on, as the token's `terminal` claim names it. */
63
+ export interface IdentificationTerminal {
64
+ id: string
65
+ label: string
66
+ }
67
+
68
+ /** Read an open identification: the id is the `identification` query parameter of the identification page. */
69
+ export interface InspectIdentificationInput extends TerminalCaller {
70
+ id: string
71
+ }
72
+
73
+ /** `expiresAt` is unix seconds. The application keys its throttle of guesses on `terminal.id`. */
74
+ export type InspectIdentificationResult = { ok: true; terminal: IdentificationTerminal; expiresAt: number } | TerminalFailure
75
+
76
+ /**
77
+ * The application's word that `principalId` stands at the identification's terminal. IAM consumes the identification
78
+ * (single use), signs the person in under the terminal's ceiling, and answers the URL the browser goes to next: IAM's
79
+ * completion of the identification, which issues the handoff code only to the terminal's own browser. The application
80
+ * never holds a code.
81
+ */
82
+ export interface AssertIdentityInput extends TerminalCaller {
83
+ id: string
84
+ principalId: string
85
+ }
86
+
87
+ export type AssertIdentityResult = { ok: true; completionUrl: string } | TerminalFailure
88
+
89
+ /** End an identification the person abandoned. Repeating it, or cancelling a consumed one, answers `not_found`. */
90
+ export interface CancelIdentificationInput extends TerminalCaller {
91
+ id: string
92
+ }
93
+
94
+ export type CancelIdentificationResult = { ok: true } | TerminalFailure
95
+
96
+ /**
97
+ * The identification operations IAM serves an application: on the membership transport (`/membership/<method>`) and
98
+ * on its application entrypoint. A SEPARATE interface from `IamMembershipRpc`, so a transport that predates terminals
99
+ * still satisfies that one.
100
+ */
101
+ export interface IamTerminalRpc {
102
+ inspectIdentification(input: InspectIdentificationInput): Promise<InspectIdentificationResult>
103
+ assertIdentity(input: AssertIdentityInput): Promise<AssertIdentityResult>
104
+ cancelIdentification(input: CancelIdentificationInput): Promise<CancelIdentificationResult>
105
+ }