@fabrika/provider-contract 0.9.0-dev.2 → 0.9.0-dev.20

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/control.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { AppSchema, ContractArtifact } from '@fabrika/auth-core'
1
+ import type { ApplicationObjects, AppSchema, ContractArtifact, ManagedEnvironment } from '@fabrika/auth-core'
2
+ import type { InstallationBrand } from '@fabrika/proxy-core/brand'
2
3
  import type { JsonValue, ProviderEnvelope } from './json'
3
4
 
4
5
  /** Events whose persistence and presentation belong to the control plane. */
@@ -15,8 +16,11 @@ export interface ProviderRunEvents {
15
16
  boundary(): Promise<void>
16
17
  }
17
18
 
18
- /** Complete platform-owned runtime state. A null value removes the key from persistent targets. */
19
- export type ProviderManagedEnvironment = Readonly<Record<string, string | null>>
19
+ /**
20
+ * Complete platform-owned runtime state, parsed by Control (`parseManagedEnvironment`). A provider writes each entry as
21
+ * a secret when it is a `credential`, removes one whose value is null, and removes the stale ones `staleManagedVariables` names.
22
+ */
23
+ export type ProviderManagedEnvironment = ManagedEnvironment
20
24
 
21
25
  /** Provider-neutral coordinates for obtaining one app revision. */
22
26
  export interface ProviderSource {
@@ -41,8 +45,7 @@ export interface ProviderDeploymentNamespace {
41
45
  readonly target: ProviderEnvelope
42
46
  }
43
47
 
44
- /** A framework release as npm publishes it; the only form one may take before it reaches a generated build command. */
45
- export const FRAMEWORK_RELEASE_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
48
+ export { FRAMEWORK_RELEASE_PATTERN } from '@fabrika/auth-core'
46
49
 
47
50
  /**
48
51
  * The access Control approved for one application environment (ADR-0050): the contract the proxy enforces and the
@@ -64,6 +67,12 @@ export interface ProviderApprovedAccess {
64
67
  * the framework minor it pins (ADR-0062). Its build checks with that release.
65
68
  */
66
69
  readonly checker: string
70
+ /**
71
+ * The `@fabrika/app` release the application's `bun.lock` pins (`FRAMEWORK_RELEASE_PATTERN`), which a release gate
72
+ * reads: `checker` is this platform's patch of that minor, newer than a prerelease pin. Absent in an access Control
73
+ * approved before it recorded the pin.
74
+ */
75
+ readonly framework?: string
67
76
  }
68
77
 
69
78
  /**
@@ -87,12 +96,18 @@ export interface ProviderEnvironment {
87
96
  * application's proxy manifest entry as `crossOrigins`.
88
97
  */
89
98
  readonly crossOrigins?: readonly string[]
99
+ /**
100
+ * The origin of the environment's active Operations ingest DSN, never the DSN: a contract application's proxy admits
101
+ * it in `connect-src`. Control sets it on a deploy; absent while the environment has no active ingest.
102
+ */
103
+ readonly operationsOrigin?: string
90
104
  readonly namespace?: ProviderDeploymentNamespace
91
105
  readonly target: ProviderEnvelope
92
106
  readonly artifact: ProviderEnvelope
93
107
  /**
94
108
  * The environment's approved contract, from Control's `approvedSnapshot`. Absent when nothing is approved: then a
95
109
  * provider publishes no endpoint table and reconciles no IAM schema, whatever the artifact claims (ADR-0050).
110
+ * Control refuses a non-dry deploy without it.
96
111
  */
97
112
  readonly access?: ProviderApprovedAccess
98
113
  }
@@ -146,13 +161,31 @@ export interface ProviderDeployInput {
146
161
  /** Platform-owned runtime configuration, separate from operator-managed application vars. */
147
162
  readonly managedEnvironment: ProviderManagedEnvironment
148
163
  /**
149
- * Every origin IAM may hand this app a session at (ADR-0022). App-wide, not per-environment:
150
- * IAM's registry is keyed by app id, so the set is assembled from every environment of the app.
151
- * Absent when the app has no public origin at all, which leaves IAM's registry untouched.
164
+ * The object that serves the environment's ordinary traffic and the objects its ops channel reaches, as Control records
165
+ * them (ADR-0070 §9). A provider whose application runs in no object ignores it; absent, the provider's defaults.
166
+ */
167
+ readonly applicationObjects?: ApplicationObjects
168
+ /**
169
+ * Present when the deploy brings migration files with a `dataLoss` statement of any kind, which may change stored data, and that the version running does not hold
170
+ * (ADR-0050): the provider backs up the application's database, and waits until the backup is stored, before any
171
+ * version that can run them starts. A backup that fails or does not finish fails the run with nothing deployed.
172
+ * Control hands it only to a provider without `dataOperations`, whose migration phase backs up itself (ADR-0070 §8),
173
+ * and never to a dry run or a dev bootstrap.
152
174
  */
153
- readonly returnOrigins?: readonly string[]
175
+ readonly backupBeforeMigrations?: { readonly migrations: readonly string[] }
154
176
  readonly dryRun: boolean
155
177
  readonly sourceBinding?: ProviderSourceBinding
178
+ /**
179
+ * Present on a dev bootstrap: the provider deploys into this workspace's sandbox, which `devSandboxes.ensure` created
180
+ * before the run, and serves it at `origin`. Absent on every other deploy.
181
+ */
182
+ readonly devSandbox?: {
183
+ readonly workspaceId: string
184
+ readonly sandboxId: string
185
+ readonly origin: string
186
+ /** See `ProviderDevSandboxInput.sandboxKey`. */
187
+ readonly sandboxKey: string
188
+ }
156
189
  /** Optional short-lived, run-scoped Operations artifact destination. */
157
190
  readonly artifactUpload?: {
158
191
  readonly url: string
@@ -167,7 +200,10 @@ export interface ProviderDeployInput {
167
200
  readonly events: ProviderRunEvents
168
201
  }
169
202
 
170
- /** A terminal provider operation result. */
203
+ /**
204
+ * A terminal provider operation result. `succeeded` means the version is live: Control then writes the environment's
205
+ * approved IAM schema itself (ADR-0011), so a provider never calls IAM for an application.
206
+ */
171
207
  export interface ProviderTerminalOutcome {
172
208
  readonly state: 'succeeded' | 'failed'
173
209
  readonly exitCode?: number
@@ -230,14 +266,10 @@ export interface ProviderRunReference {
230
266
 
231
267
  export interface ProviderCancelInput extends ProviderRunReference {
232
268
  readonly signal: AbortSignal
233
- /** See `ProviderDeployInput.returnOrigins`; a cancel that settles an activated deploy projects the same set. */
234
- readonly returnOrigins?: readonly string[]
235
269
  }
236
270
 
237
271
  export interface ProviderReconcileInput extends ProviderRunReference {
238
272
  readonly signal: AbortSignal
239
- /** See `ProviderDeployInput.returnOrigins`; a provider that settles a deploy here projects the same set. */
240
- readonly returnOrigins?: readonly string[]
241
273
  /** Append a line to the run's log. */
242
274
  log?(line: string): Promise<void>
243
275
  }
@@ -331,6 +363,34 @@ export interface ProviderNamespaceMember {
331
363
  readonly operationsOrigin?: string
332
364
  /** See `ProviderEnvironment.access`: the proxy table of a contract application comes only from here. */
333
365
  readonly access?: ProviderApprovedAccess
366
+ /**
367
+ * Present for a dev member, which is routed ONLY through these entries (none while it has no sandbox), never through
368
+ * its own `domain` and `access`.
369
+ */
370
+ readonly devSandboxes?: readonly ProviderNamespaceDevSandbox[]
371
+ }
372
+
373
+ /** One workspace sandbox of a `dev` member, which the namespace proxy routes as its own entry. */
374
+ export interface ProviderNamespaceDevSandbox {
375
+ readonly workspaceId: string
376
+ /** The public host the proxy answers the workspace on (`<workspaceId>.<domain>`). */
377
+ readonly host: string
378
+ /** See `ProviderDevSandbox.upstreamHost`. */
379
+ readonly upstreamHost: string
380
+ /** See `ProviderNamespaceMember.proxySecret`: sealed per workspace. */
381
+ readonly proxySecret?: string
382
+ /** The access of the workspace's own published bootstrap run. */
383
+ readonly access: ProviderApprovedAccess
384
+ }
385
+
386
+ /** What decides the hosts a namespace entry point routes one member on: `ProviderNamespaceMember` without its secrets. */
387
+ export interface ProviderNamespaceMemberRouting {
388
+ readonly appId: string
389
+ readonly env: string
390
+ readonly domain?: string
391
+ readonly artifact: ProviderEnvelope
392
+ readonly access?: ProviderApprovedAccess
393
+ readonly devSandboxes?: readonly Pick<ProviderNamespaceDevSandbox, 'workspaceId' | 'host'>[]
334
394
  }
335
395
 
336
396
  /** One idempotent namespace lifecycle invocation. */
@@ -338,6 +398,16 @@ export interface ProviderNamespaceMutationInput {
338
398
  readonly namespace: ProviderDeploymentNamespace
339
399
  /** Every app environment assigned to the namespace, read under its lease. */
340
400
  readonly members: readonly ProviderNamespaceMember[]
401
+ /**
402
+ * The installation's client logo for the pages the namespace's proxy answers with (ADR-0066), read from IAM for this
403
+ * mutation; absent or null shows the fabrika mark. A provider passes it only to a proxy that can parse it.
404
+ */
405
+ readonly brand?: InstallationBrand | null
406
+ /**
407
+ * Present when a member is a `dev` environment: the namespace's sandbox host is provisioned with it as its API key, and
408
+ * see `ProviderDevSandboxInput.sandboxKey`. Absent, the provider provisions no sandbox host.
409
+ */
410
+ readonly sandboxKey?: string
341
411
  readonly signal: AbortSignal
342
412
  readonly events: ProviderNamespaceEvents
343
413
  }
@@ -366,6 +436,18 @@ export const PROVIDER_NAMESPACE_IMMUTABLE = 'namespaceImmutable'
366
436
  */
367
437
  export const PROVIDER_NAMESPACE_UPDATE_UNCONFIRMED = 'namespaceUpdateUnconfirmed'
368
438
 
439
+ /**
440
+ * The `code` of a `ProviderNamespaceError` a `devSandboxes` call throws when the namespace's sandbox host has no room
441
+ * to create or wake one more sandbox. Nothing changed; it succeeds once another sandbox is parked or removed.
442
+ */
443
+ export const PROVIDER_DEV_CAPACITY = 'devCapacity'
444
+
445
+ /**
446
+ * The `code` of a `ProviderNamespaceError` a `devSandboxes` call throws when the namespace has no sandbox host yet.
447
+ * Nothing changed; it succeeds once a namespace mutation handed the sandbox host key has created the host.
448
+ */
449
+ export const PROVIDER_DEV_HOST_PENDING = 'devHostPending'
450
+
369
451
  /** One provider-described change, safe to audit: names and values only, never a credential. */
370
452
  export interface ProviderNamespaceChange {
371
453
  readonly field: string
@@ -470,6 +552,19 @@ export interface ProviderNamespaceOperator {
470
552
  present(namespace: ProviderDeploymentNamespace): ProviderNamespacePresentation
471
553
  }
472
554
 
555
+ /** The app-owned claims of one namespace whose resources Control is asked to confirm gone. */
556
+ export interface ProviderClaimedResourcesInput {
557
+ readonly namespace: ProviderDeploymentNamespace
558
+ readonly resourceKeys: readonly string[]
559
+ readonly signal: AbortSignal
560
+ }
561
+
562
+ /** What the provider observed for one claimed resource. */
563
+ export interface ProviderClaimedResource {
564
+ readonly resourceKey: string
565
+ readonly exists: boolean
566
+ }
567
+
473
568
  /** Optional placement lifecycle owned by providers that use deployment namespaces. */
474
569
  export interface ProviderNamespaceCapabilities {
475
570
  normalize(namespace: ProviderDeploymentNamespace): ProviderDeploymentNamespace
@@ -486,24 +581,85 @@ export interface ProviderNamespaceCapabilities {
486
581
  reconcile(input: ProviderNamespaceMutationInput): Promise<ProviderDeploymentNamespace>
487
582
  /** Absent means the namespace has no entry point that follows its members. */
488
583
  republish?(input: ProviderNamespaceRepublishInput): Promise<ProviderNamespaceRepublishResult>
584
+ /**
585
+ * The hosts the namespace's entry point routes this member on, lower-cased, by the rule its compiler applies; none for
586
+ * a member it does not route. Throws for a member it cannot route. Absent means no member is routed by host.
587
+ */
588
+ memberHosts?(member: ProviderNamespaceMemberRouting): readonly string[]
589
+ /**
590
+ * Read-only: whether each claimed resource still exists, one answer per key. Throws when it cannot tell, so Control
591
+ * releases a claim only over a resource the provider confirmed gone. Absent means no claim can be released.
592
+ */
593
+ claimedResources?(input: ProviderClaimedResourcesInput): Promise<readonly ProviderClaimedResource[]>
489
594
  /** Absent means the provider changes no namespace in place. */
490
595
  readonly updates?: ProviderNamespaceUpdates
491
596
  readonly operator?: ProviderNamespaceOperator
492
597
  }
493
598
 
494
- /** One call on the service of a `dev` environment, between its bootstrap runs. */
495
- export interface ProviderDevEnvironmentInput {
599
+ export interface ProviderAuthoring {
600
+ /** The file NAMES (no `/`) that configure the provider's deploy; a workspace changes none of them, at any depth. */
601
+ readonly protectedFiles: readonly string[]
602
+ }
603
+
604
+ /** The provider's handle on one workspace sandbox, which Control persists; stable for the workspace's life. */
605
+ export interface ProviderDevSandboxRef {
606
+ readonly sandboxId: string
607
+ }
608
+
609
+ /** One running workspace sandbox of a `dev` environment. */
610
+ export interface ProviderDevSandbox {
611
+ readonly sandboxId: string
612
+ /** The base image the sandbox was created from. */
613
+ readonly baseDigest: string
614
+ /** The Host the namespace proxy sends to reach the sandbox's application port (e.g. `3000-<id>.<box domain>`). */
615
+ readonly upstreamHost: string
616
+ }
617
+
618
+ /** Create a workspace's sandbox, or return the one it already has. */
619
+ export interface ProviderDevSandboxEnsureInput {
496
620
  readonly environment: ProviderEnvironment
621
+ readonly workspaceId: string
622
+ /** See `ProviderDevSandboxInput.sandboxKey`. */
623
+ readonly sandboxKey: string
624
+ readonly signal: AbortSignal
625
+ }
626
+
627
+ /** One lifecycle call on an existing workspace sandbox. */
628
+ export interface ProviderDevSandboxInput {
629
+ readonly environment: ProviderEnvironment
630
+ readonly sandbox: ProviderDevSandboxRef
631
+ /** The bearer of the namespace's sandbox host API, composed by Control from its vault for this call; never persisted or logged. */
632
+ readonly sandboxKey: string
633
+ readonly signal: AbortSignal
634
+ }
635
+
636
+ /** Remove a workspace's sandbox; with no recorded `sandbox`, the one an unrecorded `ensure` may have created. */
637
+ export interface ProviderDevSandboxRemoveInput {
638
+ readonly environment: ProviderEnvironment
639
+ readonly workspaceId: string
640
+ readonly sandbox: ProviderDevSandboxRef | null
641
+ /** See `ProviderDevSandboxInput.sandboxKey`. */
642
+ readonly sandboxKey: string
497
643
  readonly signal: AbortSignal
498
644
  }
499
645
 
500
646
  /**
501
- * The service of a `dev` environment outside a run (ADR-0049): Control stops it after an idle period and starts it on
502
- * the next commit. Files the launcher wrote survive both.
647
+ * The per-workspace sandboxes of a `dev` environment outside a run. Every call is idempotent: `ensure` creates at most
648
+ * one sandbox per `workspaceId` and returns it running, `park` and `wake` converge on their state, and `remove` treats a
649
+ * sandbox already gone as removed. A full sandbox host throws `PROVIDER_DEV_CAPACITY`, a namespace without one yet
650
+ * `PROVIDER_DEV_HOST_PENDING`; `remove` there is a no-op, since no sandbox can exist.
503
651
  */
504
- export interface ProviderDevEnvironments {
505
- stop(input: ProviderDevEnvironmentInput): Promise<void>
506
- start(input: ProviderDevEnvironmentInput): Promise<void>
652
+ export interface ProviderDevSandboxes {
653
+ /**
654
+ * Mutation-free check that the environment's placement can serve a workspace sandbox. Control calls it before it
655
+ * records one, because a recorded sandbox reaches every later republish of the namespace. A refusal is a
656
+ * `ProviderNamespaceError` that is not retryable, whose one-line message the author may read; any other throw is a failure.
657
+ */
658
+ admit(input: { readonly environment: ProviderEnvironment }): void
659
+ ensure(input: ProviderDevSandboxEnsureInput): Promise<ProviderDevSandbox>
660
+ park(input: ProviderDevSandboxInput): Promise<void>
661
+ wake(input: ProviderDevSandboxInput): Promise<void>
662
+ remove(input: ProviderDevSandboxRemoveInput): Promise<void>
507
663
  }
508
664
 
509
665
  /**
@@ -527,8 +683,29 @@ export interface ControlProvider {
527
683
  reconcile?(input: ProviderReconcileInput): Promise<ProviderReconcileOutcome>
528
684
  readonly secrets?: ProviderManagedSecrets
529
685
  readonly namespaces?: ProviderNamespaceCapabilities
686
+ /** MCP authoring (ADR-0049): an environment of this provider can be an authoring target. Absent means none can. */
687
+ readonly authoring?: ProviderAuthoring
688
+ /**
689
+ * Every application environment gets `FABRIKA_PROXY_SECRET`, with or without a namespace proxy: the provider's own
690
+ * hop to the application carries it (Cloudflare's Worker to its Durable Object, ADR-0065). Absent means only a
691
+ * namespace proxy's environments get one.
692
+ */
693
+ readonly applicationHopSecret?: true
530
694
  /** Absent means the provider runs no `dev` environment, and Control refuses one. */
531
- readonly devEnvironments?: ProviderDevEnvironments
695
+ readonly devSandboxes?: ProviderDevSandboxes
696
+ /**
697
+ * Whether an environment at this approved access is served the ops channel through which Control reaches its object
698
+ * (ADR-0069), so its deploy gets `FABRIKA_OPS_KEY_DIGESTS`. The release gate is the provider's, so core keeps no
699
+ * release logic. Absent means no environment of this provider is.
700
+ */
701
+ opsChannel?(access: ProviderApprovedAccess): boolean
702
+ /**
703
+ * Whether the object at this approved access, served the ops channel, also holds the maintenance barrier (`state`,
704
+ * `migrate`) and serves Control's data operations: the daily backups, a deploy's migration phase and the side restore
705
+ * (ADR-0069 §3, ADR-0070). A release can serve the channel without them. Absent means no environment of this
706
+ * provider is.
707
+ */
708
+ dataOperations?(access: ProviderApprovedAccess): boolean
532
709
  /** Absent means the provider deploys public sources only. */
533
710
  readonly source?: ProviderSourceCapabilities
534
711
  /**
@@ -547,4 +724,9 @@ export interface ControlProvider {
547
724
  * access snapshot there (ADR-0050). Absent means the repository root.
548
725
  */
549
726
  applicationRoot?(source: ProviderSource): string | null
727
+ /**
728
+ * The database an application of this provider runs its migrations on, which Control classifies them for: SQLite in
729
+ * the application's Durable Object on Cloudflare (ADR-0065). Absent means Postgres.
730
+ */
731
+ readonly applicationDialect?: 'postgres' | 'sqlite'
550
732
  }
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './authoring'
2
2
  export * from './control'
3
3
  export * from './json'
4
+ export * from './plain-credentials'
4
5
  export * from './schema'
5
6
  export * from './steps'
@@ -0,0 +1,278 @@
1
+ // Whether a value about to sit somewhere readable looks like a credential.
2
+ //
3
+ // A plain variable is read by everyone who may read the configuration it lives in: on Zerops every member of the
4
+ // project, on Control everyone who manages the application. A credential belongs where nobody reads it back (a
5
+ // sensitive service variable, an application secret). The check is a heuristic over the NAME and the VALUE, and it
6
+ // errs towards refusing, so each place that runs it has an explicit opt-out for a value it got wrong.
7
+ //
8
+ // Nothing here returns, logs or embeds the value: a finding names only why it matched.
9
+
10
+ /** Why a name and value look like a credential. `because` completes "… looks like a credential: <because>". */
11
+ export interface PlainCredentialFinding {
12
+ readonly basis: 'name' | 'value'
13
+ readonly because: string
14
+ }
15
+
16
+ /** Words in a variable name that mark a credential on their own; `BASIC` followed by `AUTH` does too. */
17
+ const CREDENTIAL_WORDS: ReadonlySet<string> = new Set([
18
+ 'TOKEN',
19
+ 'SECRET',
20
+ 'PASSWORD',
21
+ 'PASSWD',
22
+ 'PASS',
23
+ 'PASSPHRASE',
24
+ 'PWD',
25
+ 'CREDENTIAL',
26
+ 'CREDENTIALS',
27
+ 'APIKEY',
28
+ 'PRIVATEKEY',
29
+ 'BASICAUTH',
30
+ 'HTPASSWD',
31
+ ])
32
+
33
+ /** Words that make `KEY` (or `KEYS`) something other than a credential: `KEY_ID`, `PUBLIC_KEY`, `SITE_KEY`, `CACHE_KEY`. */
34
+ // Not `PRIMARY`: some providers call a secret a primary key (an account's primary access key).
35
+ const NON_CREDENTIAL_KEY_WORDS: ReadonlySet<string> = new Set([
36
+ 'ID',
37
+ 'IDS',
38
+ 'PUBLIC',
39
+ 'PUBLISHABLE',
40
+ 'SITE',
41
+ 'CACHE',
42
+ 'PARTITION',
43
+ 'SORT',
44
+ 'FOREIGN',
45
+ ])
46
+
47
+ /** The words beside `KEY` that make its value public, not merely not a credential. */
48
+ const PUBLIC_KEY_WORDS: ReadonlySet<string> = new Set(['PUBLIC', 'PUBLISHABLE', 'SITE'])
49
+
50
+ /**
51
+ * A last word that makes the name describe a credential rather than hold one: `TOKEN_URL`, `PASSWORD_MIN_LENGTH`,
52
+ * `SECRET_NAME`, `API_KEY_HEADER`.
53
+ */
54
+ const DESCRIPTOR_WORDS: ReadonlySet<string> = new Set([
55
+ 'URL',
56
+ 'URI',
57
+ 'ENDPOINT',
58
+ 'HOST',
59
+ 'ORIGIN',
60
+ 'PATH',
61
+ 'FILE',
62
+ 'DIR',
63
+ 'ID',
64
+ 'IDS',
65
+ 'NAME',
66
+ 'NAMES',
67
+ 'HEADER',
68
+ 'PARAM',
69
+ 'TTL',
70
+ 'LIFETIME',
71
+ 'EXPIRY',
72
+ 'EXPIRES',
73
+ 'LENGTH',
74
+ 'SIZE',
75
+ 'ALGORITHM',
76
+ 'ISSUER',
77
+ 'AUDIENCE',
78
+ 'MODE',
79
+ 'ENABLED',
80
+ 'REQUIRED',
81
+ 'PREFIX',
82
+ 'POLICY',
83
+ 'TYPE',
84
+ 'VERSION',
85
+ 'COUNT',
86
+ 'LIMIT',
87
+ 'TIMEOUT',
88
+ 'REALM',
89
+ ])
90
+
91
+ /** `FABRIKA_EMAIL_POSTMARK_SERVER_TOKEN`, `apiKey`, `basic-auth.password` → upper-case words. */
92
+ const nameWords = (name: string): readonly string[] =>
93
+ name
94
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
95
+ .toUpperCase()
96
+ .split(/[^A-Z0-9]+/)
97
+ .filter((word) => word !== '')
98
+
99
+ /** Whether the `KEY` at `index` is an id, a public key or a cache key: a word beside it says so. */
100
+ const nonCredentialKey = (words: readonly string[], index: number): boolean => {
101
+ const before = words[index - 1]
102
+ const after = words[index + 1]
103
+ return (before !== undefined && NON_CREDENTIAL_KEY_WORDS.has(before)) || (after !== undefined && NON_CREDENTIAL_KEY_WORDS.has(after))
104
+ }
105
+
106
+ /** The word of a credential name that matched, or null. */
107
+ const credentialWordIn = (words: readonly string[]): string | null => {
108
+ const last = words.at(-1)
109
+ if (last === undefined || DESCRIPTOR_WORDS.has(last)) return null
110
+ for (const [index, word] of words.entries()) {
111
+ if (CREDENTIAL_WORDS.has(word)) return word
112
+ if (word === 'BASIC' && words[index + 1] === 'AUTH') return 'BASIC_AUTH'
113
+ if ((word === 'KEY' || word === 'KEYS') && !nonCredentialKey(words, index)) return word
114
+ }
115
+ return null
116
+ }
117
+
118
+ /**
119
+ * Whether the name says its value is public: a publishable, site or public key, or an id, in a name with no credential
120
+ * word. Such a value is often long and random (`pk_live_…`, a reCAPTCHA site key, a VAPID public key), so the
121
+ * random-string rule does not apply to it. A name that also says `SECRET` (`SECRET_KEY_ID`) is not public.
122
+ */
123
+ const namesAPublicValue = (words: readonly string[]): boolean => {
124
+ if (words.some((word, index) => CREDENTIAL_WORDS.has(word) || (word === 'BASIC' && words[index + 1] === 'AUTH'))) return false
125
+ const publicKey = words.some((word, index) =>
126
+ (word === 'KEY' || word === 'KEYS')
127
+ && [words[index - 1], words[index + 1]].some((beside) => beside !== undefined && PUBLIC_KEY_WORDS.has(beside))
128
+ )
129
+ return publicKey || words.at(-1) === 'ID' || words.at(-1) === 'IDS'
130
+ }
131
+
132
+ /**
133
+ * A Zerops or shell reference (`${db_password}`) names a value held elsewhere, so it is not one here. Removing them
134
+ * leaves the literal part of a value; a value that is only references holds no literal at all.
135
+ */
136
+ const withoutReferences = (value: string): string => value.replace(/\$\{[^}]*\}/g, '')
137
+
138
+ /** Prefixes that issuers put on their tokens. */
139
+ const TOKEN_PREFIXES: readonly (readonly [RegExp, string])[] = [
140
+ [/^px_[A-Za-z0-9_-]{8,}/, 'a Fabrika key'],
141
+ [/^(ghp|gho|ghs|ghu|ghr)_[A-Za-z0-9]{20,}/, 'a GitHub token'],
142
+ [/^github_pat_[A-Za-z0-9_]{20,}/, 'a GitHub token'],
143
+ [/^glpat-[A-Za-z0-9_-]{16,}/, 'a GitLab token'],
144
+ [/^(sk|rk)_(live|test)_[A-Za-z0-9]{16,}/, 'a Stripe key'],
145
+ [/^whsec_[A-Za-z0-9+/=]{16,}/, 'a webhook signing secret'],
146
+ [/^xox[abposr]-[A-Za-z0-9-]{10,}/, 'a Slack token'],
147
+ [/^sk-[A-Za-z0-9_-]{20,}/, 'an API secret key'],
148
+ [/^AKIA[0-9A-Z]{16}$/, 'an AWS access key'],
149
+ [/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/, 'a signed JSON Web Token'],
150
+ ]
151
+
152
+ /** Shannon entropy in bits per character. */
153
+ const entropy = (text: string): number => {
154
+ const counts = new Map<string, number>()
155
+ for (const character of text) counts.set(character, (counts.get(character) ?? 0) + 1)
156
+ let bits = 0
157
+ for (const count of counts.values()) {
158
+ const share = count / text.length
159
+ bits -= share * Math.log2(share)
160
+ }
161
+ return bits
162
+ }
163
+
164
+ /** The share of `text` that matches `pattern`, a single-character class. */
165
+ const share = (text: string, pattern: RegExp): number => (text.match(pattern)?.length ?? 0) / text.length
166
+
167
+ /**
168
+ * A random-looking single word: at least 24 characters of a token alphabet, at least a fifth of them upper case and a
169
+ * fifth lower case, and at least 4 bits of entropy per character. A camel-case name has far fewer capitals than a
170
+ * random string. Hexadecimal (a digest, a UUID) has one letter case and at most 4 bits, so it never matches: a hex
171
+ * credential is caught by its name or not at all.
172
+ */
173
+ const looksRandom = (text: string): boolean =>
174
+ text.length >= 24
175
+ && /^[A-Za-z0-9+/=_-]+$/.test(text)
176
+ && share(text, /[A-Z]/g) >= 0.2
177
+ && share(text, /[a-z]/g) >= 0.2
178
+ && entropy(text) >= 4
179
+
180
+ /**
181
+ * The literal part of a value: references removed, and an Authorization scheme left standing alone by that removal
182
+ * (`Bearer ${token}`) dropped with them.
183
+ */
184
+ const literalOf = (value: string): string => withoutReferences(value).trim().replace(/^(Basic|Bearer|Token)$/i, '')
185
+
186
+ /**
187
+ * A setting's value, unwrapped from how a response header is written in `zerops.yaml` (`"'true' always"`): surrounding
188
+ * quotes and nginx's trailing `always` removed.
189
+ */
190
+ const settingOf = (literal: string): string => {
191
+ let text = literal.replace(/\s+always$/i, '').trim()
192
+ for (let round = 0; round < 2; round++) text = text.replace(/^(['"])(.*)\1$/, '$2').trim()
193
+ return text
194
+ }
195
+
196
+ /** A boolean is never a credential, whatever the name says (`Access-Control-Allow-Credentials: true`). */
197
+ const isBoolean = (setting: string): boolean => /^(true|false|yes|no|on|off)$/i.test(setting)
198
+
199
+ /**
200
+ * A short integer, a decimal or a duration: what a setting that only describes a credential holds (`TOKEN_EXPIRES_IN`,
201
+ * `KEY_ROTATION_DAYS`). It counts only when a word after the credential word names a quantity: `DB_PASSWORD=1234` and
202
+ * `DB_PASSWORD_PROD=1234` are a PIN, and an integer of six digits or more counts anywhere.
203
+ */
204
+ const isQuantity = (setting: string): boolean => /^(\d{1,5}|\d+\.\d+|\d+(ms|s|m|h|d))$/i.test(setting)
205
+
206
+ /** Words that make a name after its credential word a quantity: `TOKEN_EXPIRES_IN`, `KEY_ROTATION_DAYS`, `PASS_RATE`. */
207
+ const QUANTITY_WORDS: ReadonlySet<string> = new Set([
208
+ 'EXPIRES',
209
+ 'EXPIRY',
210
+ 'IN',
211
+ 'AGE',
212
+ 'LIFE',
213
+ 'LIFETIME',
214
+ 'TTL',
215
+ 'ROTATION',
216
+ 'DAYS',
217
+ 'HOURS',
218
+ 'MINUTES',
219
+ 'SECONDS',
220
+ 'INTERVAL',
221
+ 'PERIOD',
222
+ 'WINDOW',
223
+ 'RATE',
224
+ 'THRESHOLD',
225
+ 'RATIO',
226
+ 'MIN',
227
+ 'MAX',
228
+ 'LENGTH',
229
+ 'SIZE',
230
+ 'COUNT',
231
+ 'LIMIT',
232
+ 'RETRIES',
233
+ 'ATTEMPTS',
234
+ 'TIMEOUT',
235
+ ])
236
+
237
+ /** Whether a word after the credential word that matched names a quantity. */
238
+ const describesAQuantity = (words: readonly string[], word: string): boolean => {
239
+ const at = words.indexOf(word === 'BASIC_AUTH' ? 'AUTH' : word)
240
+ return at !== -1 && words.slice(at + 1).some((after) => QUANTITY_WORDS.has(after))
241
+ }
242
+
243
+ /** What the VALUE alone says, or null. Never echoes it. */
244
+ const valueFinding = (literal: string, publicValue: boolean): string | null => {
245
+ if (literal === '') return null
246
+ if (/-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(literal)) return 'it holds a private key'
247
+ if (/^(Basic|Bearer|Token)\s+\S{8,}$/i.test(literal)) return 'it is an Authorization header value'
248
+ // `scheme://user:password@host`: a password in the URL's userinfo. A reference in the password was removed above.
249
+ if (/^[a-z][a-z0-9+.-]*:\/\/[^/@:\s]*:[^/@\s]+@/i.test(literal)) return 'its URL carries a password'
250
+ for (const [pattern, kind] of TOKEN_PREFIXES) {
251
+ if (pattern.test(literal)) return `it reads like ${kind}`
252
+ }
253
+ if (!publicValue && looksRandom(literal)) return 'it is a long random string'
254
+ return null
255
+ }
256
+
257
+ /**
258
+ * Whether a plain `name = value` looks like a credential, and why; null when it does not.
259
+ *
260
+ * The name matches on a credential word (`TOKEN`, `SECRET`, `PASSWORD`, `PASS`, `BASIC_AUTH`, a `KEY` or `KEYS` that is
261
+ * not an id, a public key or a cache key), unless its last word makes it describe one (`TOKEN_URL`,
262
+ * `PASSWORD_MIN_LENGTH`). A name match needs a literal that could be a credential: an empty value, one made only of
263
+ * references or a boolean is not, nor a short number or duration under a name that says it is a quantity. The value matches on its own: a private key, an
264
+ * Authorization header, a URL with a password, an issuer's token prefix, or a long random string unless the name says
265
+ * the value is public (a publishable or site key, an id).
266
+ */
267
+ export function plainCredentialFinding(name: string, value: string): PlainCredentialFinding | null {
268
+ const words = nameWords(name)
269
+ const literal = literalOf(value)
270
+ const word = credentialWordIn(words)
271
+ const setting = settingOf(literal)
272
+ const describes = isBoolean(setting) || (word !== null && isQuantity(setting) && describesAQuantity(words, word))
273
+ if (word !== null && literal !== '' && !describes) {
274
+ return { basis: 'name', because: `its name contains \`${word}\`` }
275
+ }
276
+ const because = valueFinding(literal, namesAPublicValue(words))
277
+ return because === null ? null : { basis: 'value', because }
278
+ }
@@ -0,0 +1,46 @@
1
+ import type { ProviderDeploymentNamespace, ProviderNamespacePlan } from './control';
2
+ /** The runtime a contract application's generated entry is written for (`@fabrika/app/build`'s `EntryRuntime`). */
3
+ export type AppEntryRuntime = 'bun' | 'cloudflare';
4
+ /** What a namespace command asks of Control. The `fabrika` command holds the Control origin, the credential and the transport. */
5
+ export interface NamespaceControl {
6
+ create(namespace: ProviderDeploymentNamespace): Promise<unknown>;
7
+ adopt(namespace: ProviderDeploymentNamespace): Promise<unknown>;
8
+ reconcile(namespaceId: string): Promise<unknown>;
9
+ }
10
+ /** A plan, or the namespace Control answered with; the `fabrika` command validates and prints either. */
11
+ export type NamespaceCommandResult = {
12
+ readonly plan: ProviderNamespacePlan;
13
+ } | {
14
+ readonly namespace: unknown;
15
+ };
16
+ export interface NamespaceCommandContext {
17
+ readonly source: Readonly<Record<string, string | undefined>>;
18
+ /** Reads the Control origin and credential, and throws when either is missing: call it after every other input is checked. */
19
+ control(): NamespaceControl;
20
+ }
21
+ export interface NamespaceCli {
22
+ readonly usage: string;
23
+ /** `argv` is the command's own arguments, without the router's `--provider` and `--json`. */
24
+ run(subcommand: string, argv: readonly string[], context: NamespaceCommandContext): Promise<NamespaceCommandResult>;
25
+ }
26
+ export interface AppCli {
27
+ readonly provider: string;
28
+ readonly entryRuntime: AppEntryRuntime;
29
+ /** `fabrika app build`, after the command wrote a contract application's entry; `contract` says whether it did. */
30
+ build?(argv: readonly string[], context: {
31
+ readonly contract: boolean;
32
+ }): Promise<void>;
33
+ deploy?(argv: readonly string[]): Promise<void>;
34
+ /** The text `fabrika app register` hands Control: the application's manifest for one environment. */
35
+ registrationManifest?(options: {
36
+ readonly config: string;
37
+ readonly env: string;
38
+ }): Promise<string>;
39
+ readonly namespaces?: NamespaceCli;
40
+ }
41
+ export interface AppCliModule {
42
+ readonly appCli: AppCli;
43
+ }
44
+ export declare const isAppCli: (value: unknown) => value is AppCli;
45
+ /** `specifier` names the module in the error, so an operator knows which package to upgrade. */
46
+ export declare const appCliFromModule: (value: unknown, expectedProvider: string, specifier: string) => AppCli;