@fabrika/proxy-core 0.9.0-dev.1 → 0.9.0-dev.11

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/src/manifest.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  ANY_ORIGIN_KINDS,
3
3
  APP_ENVIRONMENT_SEPARATOR,
4
+ type BodyAdmission,
4
5
  type Caller,
5
6
  compileEndpointTable,
6
7
  type ContractArtifact,
@@ -17,10 +18,16 @@ import {
17
18
  type InstallationEndpointTable,
18
19
  isDigest,
19
20
  MAX_CACHE_AGE_SECONDS,
21
+ OPS_CONTENT_TYPE,
22
+ OPS_METHOD,
23
+ OPS_PREFIX,
24
+ OPS_ROW_ID,
25
+ OPS_ROW_PATH,
20
26
  parseAppEnvironmentId,
21
27
  requirementDigest,
22
28
  } from '@fabrika/auth-core'
23
29
  import { z } from 'zod'
30
+ import { type InstallationBrand, installationBrandSchema } from './brand'
24
31
  import { type CspOrigins, cspOrigins, isCrossOrigin, isPolicyOrigin, MAX_CROSS_ORIGINS, MAX_CSP_ORIGINS, WORKER_BLOB_SOURCE } from './headers'
25
32
  import { type OAuthProtectedResource, oauthProtectedResourceSchema, oauthScopesSchema } from './oauth-resource'
26
33
 
@@ -56,12 +63,22 @@ export interface ContractProxyApp extends ProxyAppBase {
56
63
  * endpoints"), from Control's registry, never from the contract; absent when it lists none.
57
64
  */
58
65
  crossOrigins?: string[]
66
+ /** The IAM app id `<app>@<env>` a dev sandbox entry (`dev:<app>:<workspace>`) mints for; absent on every other entry. */
67
+ audience?: string
68
+ /** The `Host` the proxy sends upstream in place of the client's; absent, the client's passes. */
69
+ upstreamHost?: string
70
+ }
71
+
72
+ /** The IAM app id an entry's tokens are minted for and verified against: its `audience`, or else its id. */
73
+ export function audienceOf(entry: Pick<ContractProxyApp, 'id' | 'audience'>): string {
74
+ return entry.audience ?? entry.id
59
75
  }
60
76
 
61
77
  /**
62
78
  * An installation service protected by an endpoint table (ADR-0022 "Installation entries"). Only trusted platform
63
79
  * composition writes `installation: true`; its rows may use the forms no application may declare, and its hop keeps
64
- * `Authorization`, sets no proxy secret and leaves the service's answers untouched.
80
+ * `Authorization`, sets no proxy secret (IAM's session-owner route excepted, for attribution only) and leaves the
81
+ * service's answers untouched.
65
82
  */
66
83
  export interface InstallationProxyApp extends ProxyAppBase {
67
84
  installation: true
@@ -92,8 +109,8 @@ interface ProxyEndpointExtras {
92
109
  delegation: EndpointDelegation | null
93
110
  }
94
111
 
95
- /** An endpoint row as the proxy applies it: the rules without the schemas, plus the digest and the delegation. */
96
- export type ProxyEndpointRow =
112
+ /** A row a contract declares, as the proxy applies it: the rules without the schemas, plus the digest and the delegation. */
113
+ export type DeclaredProxyEndpointRow =
97
114
  | (
98
115
  & Pick<CredentialedEndpoint, 'id' | 'kind' | 'method' | 'path' | 'callers' | 'requirement' | 'admission' | 'crossOrigin' | 'response'>
99
116
  & ProxyEndpointExtras
@@ -109,6 +126,42 @@ export type ProxyEndpointRow =
109
126
  }
110
127
  )
111
128
 
129
+ /** An endpoint row of an application table: a declared row, or the ops row that only platform composition adds. */
130
+ export type ProxyEndpointRow = DeclaredProxyEndpointRow | OpsProxyEndpointRow
131
+
132
+ /**
133
+ * The canonical ops row (ADR-0069): Control's channel to an environment's object, which platform composition adds to an
134
+ * application's table for a framework release that serves it. The parser admits only `opsProxyRow()`, field for field.
135
+ */
136
+ export interface OpsProxyEndpointRow {
137
+ id: string
138
+ kind: 'protocol'
139
+ method: typeof OPS_METHOD
140
+ path: string
141
+ callers: []
142
+ requirement: null
143
+ admission: BodyAdmission
144
+ delegation: null
145
+ digest: string
146
+ }
147
+
148
+ /** The ops row's body limit: every ops request is a small JSON object. */
149
+ export const OPS_ROW_MAX_BYTES = 64 * 1024
150
+
151
+ /** The ops row, digested like every row; the provider composes it and the framework checks `X-Fabrika-Endpoint` against it. */
152
+ export function opsProxyRow(): OpsProxyEndpointRow {
153
+ const rules = {
154
+ kind: 'protocol',
155
+ method: OPS_METHOD,
156
+ path: OPS_ROW_PATH,
157
+ callers: [],
158
+ requirement: null,
159
+ admission: { contentTypes: [OPS_CONTENT_TYPE], maxBytes: OPS_ROW_MAX_BYTES },
160
+ delegation: null,
161
+ } satisfies Omit<OpsProxyEndpointRow, 'id' | 'digest'>
162
+ return { id: OPS_ROW_ID, ...rules, digest: requirementDigest({ ...rules, oauth: null }) }
163
+ }
164
+
112
165
  /** An installation row as the proxy applies it: the row with its digest and no delegation. */
113
166
  export type InstallationProxyEndpointRow = InstallationEndpointRow & { digest: string; delegation: null }
114
167
 
@@ -117,6 +170,11 @@ export type ManifestEndpointRow = ProxyEndpointRow | InstallationProxyEndpointRo
117
170
 
118
171
  export interface ProxyManifest {
119
172
  apps: ProxyApp[]
173
+ /**
174
+ * The installation's client logo for the pages the proxy answers with (ADR-0066). Absent, a page draws the fabrika
175
+ * mark. A producer sends it only to a proxy whose source parses it: an older parser refuses the key.
176
+ */
177
+ brand?: InstallationBrand
120
178
  }
121
179
 
122
180
  const HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/
@@ -126,6 +184,48 @@ export function isProxyHost(host: string): boolean {
126
184
  return host.length > 0 && host.length <= 253 && host.split('.').every((label) => label.length <= 63 && HOST_LABEL.test(label))
127
185
  }
128
186
 
187
+ const DEV_SANDBOX_ID_PREFIX = 'dev'
188
+ /** The contract's application id rule (`CONTRACT_APP_ID_PATTERN` of `@fabrika/app`), which this module cannot import. */
189
+ const DEV_SANDBOX_APP_ID = /^[a-z0-9][a-z0-9-]*$/
190
+ const DEV_SANDBOX_WORKSPACE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
191
+
192
+ export interface DevSandboxEntryId {
193
+ readonly appId: string
194
+ readonly workspaceId: string
195
+ }
196
+
197
+ /** The entry id of one workspace's dev sandbox, `dev:<appId>:<workspaceId>`. Throws on a part that would not parse back. */
198
+ export function devSandboxEntryId(appId: string, workspaceId: string): string {
199
+ const id = `${DEV_SANDBOX_ID_PREFIX}:${appId}:${workspaceId}`
200
+ if (parseDevSandboxEntryId(id) === null) throw new Error('a dev sandbox entry id needs a contract application id and a workspace UUID')
201
+ return id
202
+ }
203
+
204
+ /** The parts of `dev:<appId>:<workspaceId>`, or null for any other string. */
205
+ export function parseDevSandboxEntryId(id: string): DevSandboxEntryId | null {
206
+ const parts = id.split(':')
207
+ if (parts.length !== 3) return null
208
+ const [prefix = '', appId = '', workspaceId = ''] = parts
209
+ return prefix === DEV_SANDBOX_ID_PREFIX && DEV_SANDBOX_APP_ID.test(appId) && DEV_SANDBOX_WORKSPACE_ID.test(workspaceId)
210
+ ? { appId, workspaceId }
211
+ : null
212
+ }
213
+
214
+ /**
215
+ * A dev sandbox entry names its application's audience, and only it does: the id itself is no IAM app id. An `@` id is
216
+ * already its own audience, and a plain id is a platform audience.
217
+ */
218
+ function checkAudience(app: Pick<ContractProxyApp, 'id' | 'audience'>, ctx: z.RefinementCtx): void {
219
+ const sandbox = parseDevSandboxEntryId(app.id)
220
+ if (sandbox === null) {
221
+ if (app.audience !== undefined) ctx.addIssue({ code: 'custom', path: ['audience'], message: 'only a dev sandbox entry names an audience' })
222
+ return
223
+ }
224
+ if (app.audience === undefined || parseAppEnvironmentId(app.audience)?.app !== sandbox.appId) {
225
+ ctx.addIssue({ code: 'custom', path: ['audience'], message: "a dev sandbox entry's audience is its application's environment" })
226
+ }
227
+ }
228
+
129
229
  /** An id that holds `@` must be a whole `<app>@<env>`; a malformed one would mint for an app IAM never registered. */
130
230
  const proxyAppIdSchema = z.string().min(1).refine((id) => !id.includes(APP_ENVIRONMENT_SEPARATOR) || parseAppEnvironmentId(id) !== null)
131
231
 
@@ -189,7 +289,10 @@ const endpointRuleFields = {
189
289
  admission: admissionSchema.nullable(),
190
290
  digest: z.string().refine(isDigest),
191
291
  }
192
- /** One row of a contract app's endpoint table; it refuses a digest that does not describe the row's rules. */
292
+ /**
293
+ * One row a contract declares, of a contract app's endpoint table; it refuses a digest that does not describe the row's
294
+ * rules. It never admits the ops row, which only `contractProxyAppSchema` reads.
295
+ */
193
296
  export const proxyEndpointRowSchema = z.union([
194
297
  z.object({
195
298
  ...endpointRuleFields,
@@ -237,13 +340,28 @@ export const proxyEndpointRowSchema = z.union([
237
340
  (row) => row.digest === requirementDigest(row),
238
341
  'endpoint digest does not match its rules',
239
342
  ) satisfies z.ZodType<
240
- ProxyEndpointRow,
343
+ DeclaredProxyEndpointRow,
241
344
  z.ZodTypeDef,
242
345
  unknown
243
346
  >
244
347
 
348
+ const OPS_ROW = opsProxyRow()
349
+
350
+ /** The ops row exactly as `opsProxyRow()` builds it: every field a literal, its digest included. */
351
+ const opsProxyEndpointRowSchema = z.object({
352
+ id: z.literal(OPS_ROW_ID),
353
+ kind: z.literal('protocol'),
354
+ method: z.literal(OPS_METHOD),
355
+ path: z.literal(OPS_ROW_PATH),
356
+ callers: z.tuple([]),
357
+ requirement: z.null(),
358
+ admission: z.object({ contentTypes: z.tuple([z.literal(OPS_CONTENT_TYPE)]), maxBytes: z.literal(OPS_ROW_MAX_BYTES) }).strict(),
359
+ delegation: z.null(),
360
+ digest: z.literal(OPS_ROW.digest),
361
+ }).strict() satisfies z.ZodType<OpsProxyEndpointRow, z.ZodTypeDef, unknown>
362
+
245
363
  /** Only an RPC procedure, a public procedure and a form open to another origin, and only the anonymous two to any (ADR-0022). */
246
- function crossOriginAllowed(kind: ProxyEndpointRow['kind'], form: CrossOriginForm | undefined): boolean {
364
+ function crossOriginAllowed(kind: DeclaredProxyEndpointRow['kind'], form: CrossOriginForm | undefined): boolean {
247
365
  return form === undefined || (CROSS_ORIGIN_KINDS.includes(kind) && (form !== 'any' || ANY_ORIGIN_KINDS.includes(kind)))
248
366
  }
249
367
 
@@ -275,14 +393,21 @@ const cspOriginsSchema = z.object({
275
393
  export const contractProxyAppSchema = z.object({
276
394
  ...proxyAppFields,
277
395
  scheme: proxyAppScheme,
278
- endpoints: z.array(proxyEndpointRowSchema),
396
+ endpoints: z.array(z.union([proxyEndpointRowSchema, opsProxyEndpointRowSchema])),
279
397
  reservedPrefixes: z.array(z.string()),
280
398
  snapshot: z.string().refine(isDigest),
281
399
  csp: cspOriginsSchema,
282
400
  operationsOrigin: z.string().refine((value) => isPolicyOrigin(value, ['https:', 'http:'])).optional(),
283
401
  crossOrigins: z.array(z.string().refine(isCrossOrigin)).nonempty().max(MAX_CROSS_ORIGINS).optional(),
402
+ audience: z.string().refine((value) => parseAppEnvironmentId(value) !== null).optional(),
403
+ upstreamHost: z.string().refine(isProxyHost).optional(),
284
404
  }).strict().superRefine((app, ctx) => {
405
+ checkAudience(app, ctx)
285
406
  checkCrossOrigins(app, ctx)
407
+ // Only the ops row lies under the ops prefix: another row there would be an application route at a platform path.
408
+ if (app.endpoints.some((row) => row.path.startsWith(OPS_PREFIX) && row.kind !== 'protocol')) {
409
+ ctx.addIssue({ code: 'custom', message: 'only the ops row serves the ops prefix' })
410
+ }
286
411
  checkEndpointTable(app, ctx)
287
412
  }) satisfies z.ZodType<ContractProxyApp, z.ZodTypeDef, unknown>
288
413
 
@@ -373,9 +498,14 @@ export const proxyAppSchema = z.union([contractProxyAppSchema, installationProxy
373
498
  * The manifest form of a compiled contract: every endpoint's rules with their digest and delegation, the reserved
374
499
  * prefixes, the contract digest and the named CSP origins. Producers call this; they never assemble rows by hand.
375
500
  * `digest` is the one the application's own release computes; Control passes it for an artifact it upcast from an
376
- * older release's (ADR-0062).
501
+ * older release's (ADR-0062). `ops` adds the ops row, which only platform composition asks for and the artifact never
502
+ * carries.
377
503
  */
378
- export function contractProxyTable(artifact: ContractArtifact, digest: string = contractDigest(artifact)): ContractProxyTable {
504
+ export function contractProxyTable(
505
+ artifact: ContractArtifact,
506
+ digest: string = contractDigest(artifact),
507
+ options: { readonly ops?: boolean } = {},
508
+ ): ContractProxyTable {
379
509
  return {
380
510
  endpoints: artifact.endpoints.map((row): ProxyEndpointRow => {
381
511
  const rules = {
@@ -400,13 +530,73 @@ export function contractProxyTable(artifact: ContractArtifact, digest: string =
400
530
  delegation: endpointDelegation(artifact, row),
401
531
  }
402
532
  return { ...credentialed, digest: requirementDigest(credentialed) }
403
- }),
533
+ }).concat(options.ops === true ? [opsProxyRow()] : []),
404
534
  reservedPrefixes: [...artifact.reservedPrefixes],
405
535
  snapshot: digest,
406
536
  csp: cspOrigins(artifact.csp),
407
537
  }
408
538
  }
409
539
 
540
+ /** Where and how a producer serves one contract application. */
541
+ export interface ContractEntryPlacement {
542
+ readonly id: string
543
+ readonly hosts: readonly string[]
544
+ readonly upstream: string
545
+ readonly scheme: 'http' | 'https'
546
+ /** The approved contract's table, from `contractProxyTable`. */
547
+ readonly table: ContractProxyTable
548
+ readonly operationsOrigin?: string
549
+ /** The environment's list from Control's registry; an empty one is omitted. */
550
+ readonly crossOrigins?: readonly string[]
551
+ /** A dev sandbox entry's `<app>@<env>`; see `ContractProxyApp.audience`. */
552
+ readonly audience?: string
553
+ readonly upstreamHost?: string
554
+ }
555
+
556
+ /**
557
+ * What the proxy of one older platform release parses of an application's manifest entry: a row, and the entry's CSP
558
+ * directives, each by that release's own parser (ADR-0062); and whether it serves the sign-out (ADR-0067 §5).
559
+ */
560
+ export interface OlderProxyReader {
561
+ readonly row: (row: ProxyEndpointRow) => boolean
562
+ readonly csp: (csp: CspOrigins) => boolean
563
+ readonly signsOut: boolean
564
+ }
565
+
566
+ /**
567
+ * The proxies of the older releases a pin may run whose parsers Control holds. A pin's release is not recorded, so what
568
+ * any of them reads is what the pin may read.
569
+ */
570
+ export type OlderProxyReaders = readonly [OlderProxyReader, ...OlderProxyReader[]]
571
+
572
+ /**
573
+ * A contract application's manifest entry: the one form every producer builds. Refused when the proxy's own parser
574
+ * would refuse it, naming the fields and never their values, because an origin with userinfo may carry a key.
575
+ */
576
+ export function contractProxyEntry(placement: ContractEntryPlacement): ContractProxyApp {
577
+ const { table, operationsOrigin, crossOrigins = [], audience, upstreamHost } = placement
578
+ const entry: ContractProxyApp = {
579
+ id: placement.id,
580
+ hosts: [...placement.hosts],
581
+ upstream: placement.upstream,
582
+ scheme: placement.scheme,
583
+ endpoints: table.endpoints,
584
+ reservedPrefixes: table.reservedPrefixes,
585
+ snapshot: table.snapshot,
586
+ csp: table.csp,
587
+ ...(operationsOrigin === undefined ? {} : { operationsOrigin }),
588
+ ...(crossOrigins.length === 0 ? {} : { crossOrigins: [...crossOrigins] }),
589
+ ...(audience === undefined ? {} : { audience }),
590
+ ...(upstreamHost === undefined ? {} : { upstreamHost }),
591
+ }
592
+ const parsed = contractProxyAppSchema.safeParse(entry)
593
+ if (!parsed.success) {
594
+ const fields = new Set(parsed.error.issues.map((issue) => issue.path.length === 0 ? issue.message : issue.path.join('.')))
595
+ throw new Error(`proxy entry \`${placement.id}\` is one the proxy manifest refuses (${[...fields].join('; ')})`)
596
+ }
597
+ return entry
598
+ }
599
+
410
600
  /** What a producer adds to an installation service's placement: the output of `serviceProxyTable`. */
411
601
  export type InstallationProxyTable = Pick<InstallationProxyApp, 'installation' | 'endpoints' | 'reservedPrefixes'>
412
602
 
@@ -440,6 +630,7 @@ export function findDuplicateProxyHost(apps: readonly Pick<ProxyApp, 'hosts'>[])
440
630
 
441
631
  export const proxyManifestSchema = z.object({
442
632
  apps: z.array(proxyAppSchema),
633
+ brand: installationBrandSchema.optional(),
443
634
  }).strict().superRefine(({ apps }, ctx) => {
444
635
  if (new Set(apps.map((app) => app.id)).size !== apps.length) ctx.addIssue({ code: 'custom', message: 'duplicate proxy app id' })
445
636
  if (findDuplicateProxyHost(apps) !== null) ctx.addIssue({ code: 'custom', message: 'duplicate proxy host' })