@fabrika/installation-init 0.9.0-dev.3 → 0.9.0-dev.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/installation-init",
3
- "version": "0.9.0-dev.3",
3
+ "version": "0.9.0-dev.5",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -28,8 +28,10 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "zod": "^3.25.76",
31
- "@fabrika/app": "0.9.0-dev.3",
32
- "@fabrika/email": "0.9.0-dev.3",
33
- "@fabrika/iam-contract": "0.9.0-dev.3"
31
+ "@fabrika/app": "0.9.0-dev.5",
32
+ "@fabrika/auth-core": "0.9.0-dev.5",
33
+ "@fabrika/email": "0.9.0-dev.5",
34
+ "@fabrika/iam-contract": "0.9.0-dev.5",
35
+ "@fabrika/proxy-core": "0.9.0-dev.5"
34
36
  }
35
37
  }
package/src/index.ts CHANGED
@@ -22,7 +22,9 @@ export {
22
22
  } from './environment'
23
23
  export { ghRepoExists, hasGhCli } from './gh'
24
24
  export { action, detail, fail, info, ok, step, url, warn } from './log'
25
+ export { type IamOAuthConfig, type McpClient, parseMcpClientsJson, platformIamOAuthConfig } from './mcp'
25
26
  export { type CommandEnv, describeArgument, readEnv, readFlag, requiredSetting, setting, shellWord } from './options'
27
+ export { assertPinnedTag } from './pin'
26
28
  export { confirm } from './prompt'
27
29
  export {
28
30
  branchProtectionCommand,
@@ -36,6 +38,21 @@ export {
36
38
  type ProtectionOutcome,
37
39
  protectSidecarBranch,
38
40
  } from './protection'
41
+ export {
42
+ type PlatformHosts,
43
+ type PlatformOAuthResourceTemplate,
44
+ type PlatformOAuthScopeGrant,
45
+ platformOrigin,
46
+ type PlatformProxyApp,
47
+ platformProxyAppFor,
48
+ type PlatformProxyComposition,
49
+ type PlatformProxyManifest,
50
+ type PlatformProxyManifestTemplate,
51
+ type PlatformProxyPlacement,
52
+ type PlatformProxyService,
53
+ platformServiceTableDigest,
54
+ resolvePlatformProxyManifest,
55
+ } from './proxy-manifest'
39
56
  export {
40
57
  INITIAL_SCAFFOLD_COMMIT_MESSAGE,
41
58
  REFRESH_SCAFFOLD_COMMIT_MESSAGE,
@@ -44,4 +61,20 @@ export {
44
61
  type SidecarScaffoldInput,
45
62
  type SidecarScaffoldResult,
46
63
  } from './scaffold'
64
+ export { generateInstallationSecrets, generateSigningKeys, generateVaultKey, type InstallationSecrets, randomPxKey, randomSecret } from './secrets'
65
+ export { checkedSecretsFilePath, renderSecretsFile, SECRETS_FILE_FLAG, SECRETS_FILE_VARIABLE, writeSecretsFile } from './secrets-file'
66
+ export {
67
+ deployedServiceEnvironment,
68
+ type DeployedServiceInput,
69
+ deriveIamProxySecret,
70
+ IAM_OAUTH_CONFIG_VARIABLE,
71
+ INSTALLATION_SECRET_VARIABLES,
72
+ installationServiceEnvironment,
73
+ type InstallationServiceInput,
74
+ type PlatformData,
75
+ type PlatformPlacementInput,
76
+ type PlatformService,
77
+ type PlatformServiceEnvironment,
78
+ type PlatformStorage,
79
+ } from './service-environment'
47
80
  export { attempt, capture, probe, run, type ShellAttempt, type ShellStep } from './shell'
package/src/log.ts CHANGED
@@ -76,6 +76,6 @@ export function url(value: string): string {
76
76
 
77
77
  /** Strip ANSI escape codes so box-drawing can measure the VISIBLE width of a line. */
78
78
  function stripAnsi(value: string): string {
79
- // biome-ignore lint/suspicious/noControlCharactersInRegex: matching ANSI escape sequences by design.
79
+ // oxlint-disable-next-line no-control-regex -- matching ANSI escape sequences by design.
80
80
  return value.replace(/\x1b\[[0-9;]*m/g, '')
81
81
  }
package/src/mcp.ts ADDED
@@ -0,0 +1,102 @@
1
+ // MCP authoring, opt-in per installation (ADR-0049).
2
+ //
3
+ // The operator names the MCP clients it trusts; everything else is derived. One input turns on BOTH
4
+ // halves, so they cannot disagree: the console's `oauth` row with its registered resource in the proxy
5
+ // manifest, and IAM's `FABRIKA_IAM_OAUTH_CONFIG`, which issues tokens for exactly that resource.
6
+
7
+ import { type OAuthManagedClient, type OAuthResourceDto, parseOAuthManagedClient } from '@fabrika/iam-contract'
8
+ import { platformOAuthResourceUris, type PlatformProxyComposition, type PlatformProxyManifestTemplate } from './proxy-manifest'
9
+
10
+ /** One operator-registered MCP client: its CIMD identity, plus where IAM fetches it when that differs. */
11
+ export interface McpClient extends OAuthManagedClient {
12
+ readonly metadataUrl?: string
13
+ }
14
+
15
+ /** The document IAM parses from `FABRIKA_IAM_OAUTH_CONFIG`. */
16
+ export interface IamOAuthConfig {
17
+ readonly clients: readonly McpClient[]
18
+ readonly resources: readonly OAuthResourceDto[]
19
+ }
20
+
21
+ const CLIENT_KEYS = ['provider', 'clientId', 'redirectUris', 'metadataUrl']
22
+ /** IAM's own ceiling: it refuses to boot with more. */
23
+ const MAX_CLIENTS = 16
24
+
25
+ const isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
26
+
27
+ const isHttpsUrl = (value: string): boolean => {
28
+ try {
29
+ const url = new URL(value)
30
+ return url.protocol === 'https:' && url.username === '' && url.password === '' && url.hash === ''
31
+ } catch {
32
+ return false
33
+ }
34
+ }
35
+
36
+ const parseClient = (value: unknown, index: number): McpClient => {
37
+ const client = parseOAuthManagedClient(value)
38
+ if (client === null || !isObject(value) || !Object.keys(value).every((key) => CLIENT_KEYS.includes(key))) {
39
+ throw new Error(`MCP client ${index} must be { provider: 'claude' | 'chatgpt', clientId: <https URL>, redirectUris: [...], metadataUrl? }`)
40
+ }
41
+ const metadataUrl = value['metadataUrl']
42
+ if (metadataUrl === undefined) {
43
+ return client
44
+ }
45
+ if (typeof metadataUrl !== 'string' || !isHttpsUrl(metadataUrl)) {
46
+ throw new Error(`MCP client ${index}: metadataUrl must be an https URL`)
47
+ }
48
+ return { ...client, metadataUrl }
49
+ }
50
+
51
+ /**
52
+ * Parse the operator's MCP client list — a JSON array. Anything malformed, an empty list or a repeated
53
+ * client id is refused here, before a deploy writes a value IAM would refuse to boot with.
54
+ */
55
+ export const parseMcpClientsJson = (raw: string): readonly McpClient[] => {
56
+ let value: unknown
57
+ try {
58
+ value = JSON.parse(raw)
59
+ } catch {
60
+ throw new Error('the MCP client list is not valid JSON')
61
+ }
62
+ if (!Array.isArray(value) || value.length === 0) {
63
+ throw new Error('the MCP client list must be a non-empty JSON array')
64
+ }
65
+ if (value.length > MAX_CLIENTS) {
66
+ throw new Error(`the MCP client list names more than ${MAX_CLIENTS} clients, which IAM refuses`)
67
+ }
68
+ const clients = value.map(parseClient)
69
+ const ids = new Set(clients.map((client) => client.clientId))
70
+ if (ids.size !== clients.length) {
71
+ throw new Error('the MCP client list names one client id twice')
72
+ }
73
+ return clients
74
+ }
75
+
76
+ /** IAM's OAuth configuration for one placed installation: the clients, and one resource per app that serves one. */
77
+ export const platformIamOAuthConfig = (
78
+ template: PlatformProxyManifestTemplate,
79
+ composition: PlatformProxyComposition,
80
+ clients: readonly McpClient[],
81
+ ): IamOAuthConfig => {
82
+ const resources: OAuthResourceDto[] = []
83
+ for (const app of template.apps) {
84
+ if (app.oauthResource === undefined) {
85
+ continue
86
+ }
87
+ const { resource } = platformOAuthResourceUris(composition, composition.placement[app.service].hosts, app.oauthResource)
88
+ resources.push({
89
+ app: app.id,
90
+ resource,
91
+ defaultScopes: [...app.oauthResource.scopes],
92
+ scopeGrants: app.oauthResource.scopeGrants.map((grant) => ({
93
+ scope: grant.scope,
94
+ permissions: grant.actions.map((action) => ({ action })),
95
+ })),
96
+ })
97
+ }
98
+ if (resources.length === 0) {
99
+ throw new Error('the platform proxy manifest template declares no OAuth resource for MCP clients to reach')
100
+ }
101
+ return { clients, resources }
102
+ }
package/src/pin.ts ADDED
@@ -0,0 +1,26 @@
1
+ // The one rule about a sidecar's pin: it names a published TAG of `contember/fabrika-platform`, never a
2
+ // branch. A namespace proxy and an installation both build from tags, so a moving ref would make "which
3
+ // version is this installation running" unanswerable (ADR-0025).
4
+
5
+ /**
6
+ * A published release tag: `v` and a semantic version.
7
+ *
8
+ * The same shape `scripts/release.ts` accepts, restated rather than imported — that script is not a
9
+ * package and this check has to hold in a published tarball.
10
+ */
11
+ const TAG_PATTERN = /^v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/
12
+
13
+ /** The pinned ref, or an error naming what was found. A branch is refused, deliberately and loudly. */
14
+ export const assertPinnedTag = (ref: string): string => {
15
+ const trimmed = ref.trim()
16
+ if (trimmed === '') {
17
+ throw new Error('a published fabrika tag is required, for example v0.1.0')
18
+ }
19
+ if (!TAG_PATTERN.test(trimmed)) {
20
+ throw new Error(
21
+ `\`${trimmed}\` is not a published tag. A sidecar repository pins a TAG such as v0.1.0 and never a branch: `
22
+ + 'an installation that tracked a moving ref could not say which version it runs (ADR-0025)',
23
+ )
24
+ }
25
+ return trimmed
26
+ }
package/src/prompt.ts CHANGED
@@ -35,16 +35,16 @@ function stripTerminalCruft(value: string): string {
35
35
  return (
36
36
  value
37
37
  // Full OSC sequences: ESC ] … (BEL or ST). e.g. an OSC 10/11 dynamic-color response.
38
- // biome-ignore lint/suspicious/noControlCharactersInRegex: matching terminal escape bytes by design.
38
+ // oxlint-disable-next-line no-control-regex -- matching terminal escape bytes by design.
39
39
  .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
40
40
  // Bare OSC 10/11 color responses whose ESC introducer readline's keypress parser ate
41
41
  // (`1X;rgb:RRRR/GGGG/BBBB`, optional leading `]`). Never appears in a real entered value.
42
42
  .replace(/\]?1[0-9];rgb:[0-9a-fA-F]{1,4}(?:\/[0-9a-fA-F]{1,4}){2}/g, '')
43
43
  // CSI sequences (bracketed-paste markers, cursor-position responses ESC[N;MR, SGR, …).
44
- // biome-ignore lint/suspicious/noControlCharactersInRegex: matching terminal escape bytes by design.
44
+ // oxlint-disable-next-line no-control-regex -- matching terminal escape bytes by design.
45
45
  .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '')
46
46
  // Any stray C0/C1 control char + DEL.
47
- // biome-ignore lint/suspicious/noControlCharactersInRegex: matching terminal control bytes by design.
47
+ // oxlint-disable-next-line no-control-regex -- matching terminal control bytes by design.
48
48
  .replace(/[\x00-\x1f\x7f]/g, '')
49
49
  )
50
50
  }
@@ -0,0 +1,221 @@
1
+ // The proxy manifest a platform installation is configured with, split into the half that is the same
2
+ // on every installation and the half that is one account's.
3
+ //
4
+ // ── Why a template rather than a `ProxyManifest` with the hosts left out ──────────────────────────
5
+ //
6
+ // `parseProxyManifest` refuses an app that declares no hosts, and rightly — a host-less app is fronted
7
+ // by nothing and protects nothing. So the committed half cannot BE a manifest with empty hosts; it is a
8
+ // type of its own, and `resolvePlatformProxyManifest` is the one way to turn it into the document the
9
+ // proxy parses.
10
+ //
11
+ // ── The split ────────────────────────────────────────────────────────────────────────────────────
12
+ //
13
+ // template which apps exist, their ids, the private service each is dialed at, the public listener
14
+ // each answers on, and their service table. True of every installation of one provider, so the
15
+ // provider ships it GENERATED (Zerops: `provider-zerops/src/installation/generated/`) and reviewed in
16
+ // a diff.
17
+ // placement the hostnames and the browser-facing scheme. A generated cloud hostname names one
18
+ // account's project, and a production installation binds custom domains instead, so
19
+ // whoever is deploying supplies these.
20
+ //
21
+ // Nothing in this file imports the packages that OWN the tables. That is the point of the split:
22
+ // they live in the private service packages and reach a deployed installation as DATA, through the
23
+ // generated artifact, so the published deploy path never depends on a package it cannot resolve.
24
+
25
+ import { type InstallationEndpointTable, installationTableDigest } from '@fabrika/auth-core'
26
+ import {
27
+ type InstallationProxyApp,
28
+ isApplicationEntry,
29
+ type OAuthProtectedResource,
30
+ parseProxyManifest,
31
+ serviceProxyTable,
32
+ } from '@fabrika/proxy-core/manifest'
33
+
34
+ /** The platform services an installation's proxy fronts. Each name is a service hostname in the topology. */
35
+ export type PlatformProxyService = 'iam' | 'control' | 'operations'
36
+
37
+ /** The public hostname of each platform service, without a scheme and without a port. */
38
+ export type PlatformHosts = Readonly<Record<PlatformProxyService, string>>
39
+
40
+ /** `https://<host>` — the origin a browser, a token's `iss` and a return-origin registry all use. */
41
+ export const platformOrigin = (scheme: 'http' | 'https', host: string): string => `${scheme}://${host}`
42
+
43
+ /** What one OAuth scope lets a token do: the owning app's actions, resolved by IAM at the token endpoint. */
44
+ export interface PlatformOAuthScopeGrant {
45
+ readonly scope: string
46
+ readonly actions: readonly string[]
47
+ }
48
+
49
+ /**
50
+ * A path an app serves to OAuth clients, protected only on an installation that enables it.
51
+ *
52
+ * The resource URI is the app's public origin plus `path`, so the template holds the path and a deploy
53
+ * binds the origin. Copied from the owning service module by the generator, like `table`.
54
+ */
55
+ export interface PlatformOAuthResourceTemplate {
56
+ readonly path: string
57
+ readonly scopes: readonly string[]
58
+ readonly scopeGrants: readonly PlatformOAuthScopeGrant[]
59
+ }
60
+
61
+ /**
62
+ * One fronted app, in the form that is the same on every installation: protected by its service contract (ADR-0022
63
+ * "Installation entries"), copied in by the generator and never written by hand.
64
+ */
65
+ export interface PlatformProxyApp {
66
+ /** The IAM app id. It is the audience of every token the proxy mints for this app's host. */
67
+ readonly id: string
68
+ /** The topology service that answers for it. */
69
+ readonly service: PlatformProxyService
70
+ /**
71
+ * The proxy's public listener this app answers on.
72
+ *
73
+ * On a `zerops-subdomain` installation a port IS a hostname — Zerops mints one generated host per
74
+ * HTTP port — so this is the only installation-independent half of `hosts`. A custom-domain
75
+ * installation ignores it: every domain arrives on one listener and the `Host` header decides.
76
+ */
77
+ readonly port: number
78
+ /** Where the proxy dials it over the project's private network. */
79
+ readonly upstream: string
80
+ /** The service's rows; with an `oauthResource`, the table served when the composition names an authorization server. */
81
+ readonly table: InstallationEndpointTable
82
+ /** Present only on an app that can serve OAuth clients; off unless the composition names an authorization server. */
83
+ readonly oauthResource?: PlatformOAuthResourceTemplate
84
+ /**
85
+ * Present exactly with `oauthResource`: the service's table when it serves no OAuth client. The service picks the
86
+ * same one, by the digest the deploy writes beside it (`platformServiceTableDigest`).
87
+ */
88
+ readonly tableWithoutOAuth?: InstallationEndpointTable
89
+ }
90
+
91
+ /** Everything about an installation's manifest that does not depend on WHICH installation it is. */
92
+ export interface PlatformProxyManifestTemplate {
93
+ readonly apps: readonly PlatformProxyApp[]
94
+ }
95
+
96
+ /**
97
+ * The template's entry for one platform service.
98
+ *
99
+ * The app IDS live in the template, so a caller that needs one — the deploy's schema reconcile needs
100
+ * the console's — reads it from there rather than restating a literal that could drift from the
101
+ * document the proxy is actually configured with.
102
+ */
103
+ export const platformProxyAppFor = (
104
+ template: PlatformProxyManifestTemplate,
105
+ service: PlatformProxyService,
106
+ ): PlatformProxyApp => {
107
+ const app = template.apps.find((candidate) => candidate.service === service)
108
+ if (app === undefined) {
109
+ throw new Error(`the platform proxy manifest template fronts no \`${service}\` service`)
110
+ }
111
+ return app
112
+ }
113
+
114
+ /** Where one app answers in a particular composition. */
115
+ export interface PlatformProxyPlacement {
116
+ /** Public hostnames, without a port — `parseProxyManifest` refuses a `:port` suffix. */
117
+ readonly hosts: readonly string[]
118
+ /** Overrides the private dial address. The local composition runs IAM on a port of its own. */
119
+ readonly upstream?: string
120
+ }
121
+
122
+ /** One composition of the platform: a deployed installation, or the local Docker stack. */
123
+ export interface PlatformProxyComposition {
124
+ /** The scheme the BROWSER speaks to these apps — configuration, never a header (see `ProxyApp.scheme`). */
125
+ readonly scheme: 'http' | 'https'
126
+ readonly placement: Readonly<Record<PlatformProxyService, PlatformProxyPlacement>>
127
+ /**
128
+ * The public IAM origin that issues OAuth tokens. Present only when the installation enables MCP
129
+ * authoring; absent leaves every `oauthResource` unregistered and serves each service's table without OAuth.
130
+ */
131
+ readonly authorizationServer?: string
132
+ /** The port browsers reach every app on, when it is not the scheme's default. The local composition's is 18080. */
133
+ readonly publicPort?: number
134
+ }
135
+
136
+ /**
137
+ * The RFC 8707 resource URI and RFC 9728 metadata URL of an app's OAuth resource, bound to the app's
138
+ * FIRST host: the proxy refuses a resource on a host the app does not answer on.
139
+ */
140
+ export const platformOAuthResourceUris = (
141
+ composition: Pick<PlatformProxyComposition, 'scheme' | 'publicPort'>,
142
+ hosts: readonly string[],
143
+ template: PlatformOAuthResourceTemplate,
144
+ ): { readonly resource: string; readonly resourceMetadata: string } => {
145
+ const host = hosts[0]
146
+ if (host === undefined) {
147
+ throw new Error('an OAuth resource needs a host to stand on')
148
+ }
149
+ const origin = composition.publicPort === undefined
150
+ ? `${composition.scheme}://${host}`
151
+ : `${composition.scheme}://${host}:${composition.publicPort}`
152
+ return {
153
+ resource: `${origin}${template.path}`,
154
+ resourceMetadata: `${origin}/.well-known/oauth-protected-resource${template.path}`,
155
+ }
156
+ }
157
+
158
+ const registeredResource = (
159
+ hosts: readonly string[],
160
+ template: PlatformOAuthResourceTemplate,
161
+ composition: PlatformProxyComposition,
162
+ authorizationServer: string,
163
+ ): OAuthProtectedResource => ({
164
+ ...platformOAuthResourceUris(composition, hosts, template),
165
+ authorizationServers: [authorizationServer],
166
+ scopesSupported: [...template.scopes],
167
+ })
168
+
169
+ /** Only an installation that names an authorization server registers the resource and serves its OAuth rows. */
170
+ const resolvedApp = (app: PlatformProxyApp, composition: PlatformProxyComposition): InstallationProxyApp => {
171
+ const placement = composition.placement[app.service]
172
+ const hosts = [...placement.hosts]
173
+ const registered = app.oauthResource === undefined || composition.authorizationServer === undefined
174
+ ? undefined
175
+ : registeredResource(hosts, app.oauthResource, composition, composition.authorizationServer)
176
+ const table = registered === undefined ? (app.tableWithoutOAuth ?? app.table) : app.table
177
+ return {
178
+ id: app.id,
179
+ hosts,
180
+ upstream: placement.upstream ?? app.upstream,
181
+ scheme: composition.scheme,
182
+ ...serviceProxyTable(table, { oauth: registered !== undefined }),
183
+ ...(registered === undefined ? {} : { oauthResources: [registered] }),
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Bind a template to one composition and get the document the proxy actually parses.
189
+ *
190
+ * The result is returned THROUGH `parseProxyManifest`, so a duplicate id, a repeated host or a `:port`
191
+ * suffix is refused right here instead of at a deployed proxy's next build.
192
+ */
193
+ export const resolvePlatformProxyManifest = (
194
+ template: PlatformProxyManifestTemplate,
195
+ composition: PlatformProxyComposition,
196
+ ): PlatformProxyManifest => {
197
+ const manifest = parseProxyManifest({ apps: template.apps.map((app) => resolvedApp(app, composition)) })
198
+ // Every platform service is an installation entry, never an application.
199
+ const services = manifest?.apps.flatMap((app) => isApplicationEntry(app) ? [] : [app]) ?? []
200
+ if (manifest === null || services.length !== manifest.apps.length) {
201
+ throw new Error('the resolved platform proxy manifest is not one the proxy would accept')
202
+ }
203
+ return { apps: services }
204
+ }
205
+
206
+ /** The platform proxy's manifest: one installation entry per platform service. */
207
+ export interface PlatformProxyManifest {
208
+ apps: InstallationProxyApp[]
209
+ }
210
+
211
+ /**
212
+ * `FABRIKA_SERVICE_TABLE_DIGEST` for a service: the digest of the table this manifest publishes for it, which the
213
+ * service compares with its own and refuses to start under another.
214
+ */
215
+ export const platformServiceTableDigest = (manifest: PlatformProxyManifest, appId: string): string => {
216
+ const entry = manifest.apps.find((app) => app.id === appId)
217
+ if (entry === undefined) {
218
+ throw new Error(`the platform proxy manifest fronts no \`${appId}\``)
219
+ }
220
+ return installationTableDigest(entry)
221
+ }
@@ -0,0 +1,61 @@
1
+ // The operator's local copy of every credential a bring-up creates.
2
+ //
3
+ // A cloud that stores a credential write-only hands nothing back, so this file is the copy the command
4
+ // writes before the first credential is placed: a run that fails later loses nothing.
5
+
6
+ import { existsSync } from 'node:fs'
7
+ import { open } from 'node:fs/promises'
8
+ import { isAbsolute, relative, resolve } from 'node:path'
9
+
10
+ /** `--secrets-file`: where the local copy goes. A new file, outside the source checkout. */
11
+ export const SECRETS_FILE_FLAG = '--secrets-file'
12
+ export const SECRETS_FILE_VARIABLE = 'FABRIKA_PLATFORM_SECRETS_FILE'
13
+
14
+ /**
15
+ * Settle the path before anything is contacted.
16
+ *
17
+ * Refused when it exists, because overwriting one would destroy another installation's only copy, and
18
+ * when it is inside the source checkout, where it would dirty the checkout a deploy uploads and could be
19
+ * committed.
20
+ */
21
+ export const checkedSecretsFilePath = (path: string, sourceDir: string): string => {
22
+ const absolute = resolve(path)
23
+ const fromSource = relative(resolve(sourceDir), absolute)
24
+ if (fromSource === '' || (!fromSource.startsWith('..') && !isAbsolute(fromSource))) {
25
+ throw new Error(`${SECRETS_FILE_FLAG}=${path} is inside the source checkout — name a path outside it, so it is never uploaded or committed`)
26
+ }
27
+ if (existsSync(absolute)) {
28
+ throw new Error(`${SECRETS_FILE_FLAG}=${path} already exists — it may be another installation's only copy; name a new file`)
29
+ }
30
+ return absolute
31
+ }
32
+
33
+ /**
34
+ * The file's text: comment lines, then shell-sourceable assignments, named as the commands that read
35
+ * them name them. `header` is the provider's own lines, each written as a `#` comment.
36
+ */
37
+ export const renderSecretsFile = (header: readonly string[], assignments: readonly (readonly [string, string])[]): string => {
38
+ const lines = assignments.map(([name, value]) => {
39
+ // Single quotes keep every character literal; none of these values can contain one.
40
+ if (value.includes("'") || value.includes('\n')) {
41
+ throw new Error(`${name} cannot be written to the secrets file as one quoted line`)
42
+ }
43
+ return `${name}='${value}'`
44
+ })
45
+ return [
46
+ ...header.map((line) => `# ${line}`),
47
+ '# Load it in a subshell: ( set -a && . <this file> && set +a && fabrika … )',
48
+ ...lines,
49
+ '',
50
+ ].join('\n')
51
+ }
52
+
53
+ /** Create the file with mode 0600, failing rather than replacing one that appeared since the check. */
54
+ export const writeSecretsFile = async (path: string, text: string): Promise<void> => {
55
+ const file = await open(path, 'wx', 0o600)
56
+ try {
57
+ await file.writeFile(text)
58
+ } finally {
59
+ await file.close()
60
+ }
61
+ }
package/src/secrets.ts ADDED
@@ -0,0 +1,78 @@
1
+ // The credentials a platform installation is seeded with, and their shapes.
2
+ //
3
+ // The shapes are not free choices. Each one is what the consuming code already parses:
4
+ //
5
+ // • `FABRIKA_IAM_SIGNING_KEYS` is a JSON array of PRIVATE JWKs, index 0 the active signer
6
+ // (`@fabrika/iam`'s `Signer.fromPrivateJwks`). ES256 / P-256, RFC 7638 thumbprint `kid`.
7
+ // • A `px_` key is IAM's own credential spelling, and every shared secret must be at least 32
8
+ // characters or the service refuses to boot — 32 random bytes at base64url is 43.
9
+ // • The vault KEK is 32 RAW BYTES at base64, not base64url: `@fabrika/control` imports it as an
10
+ // AES key, and base64url is a different alphabet.
11
+ //
12
+ // Nothing here re-reads an existing value: whether a run generates or reuses one is the provider's flow.
13
+
14
+ import { createHash, generateKeyPairSync, randomBytes } from 'node:crypto'
15
+
16
+ /**
17
+ * A 256-bit secret in base64url, never starting with `-` or `_`.
18
+ *
19
+ * The re-roll is copied from `@fabrika/local-stack`'s `prepare.ts` and it is not superstition: a
20
+ * credential beginning with `-` reads as a FLAG to anything that later takes it on a command line, no
21
+ * matter how it is quoted. One rolled password beginning with `-` made `mc alias set` print its usage
22
+ * and loop forever. It costs nothing and removes a bug that appears about one install in sixteen.
23
+ */
24
+ export const randomSecret = (): string => {
25
+ for (;;) {
26
+ const value = randomBytes(32).toString('base64url')
27
+ if (!value.startsWith('-') && !value.startsWith('_')) {
28
+ return value
29
+ }
30
+ }
31
+ }
32
+
33
+ /** The `px_` prefix IAM's own credentials carry, so a key looks like what it is wherever it turns up. */
34
+ export const randomPxKey = (): string => `px_${randomSecret()}`
35
+
36
+ /** The control plane's vault KEK. base64, NOT base64url: the vault imports these bytes as an AES key. */
37
+ export const generateVaultKey = (): string => randomBytes(32).toString('base64')
38
+
39
+ /**
40
+ * One ES256 (EC P-256) private JWK with an RFC 7638 thumbprint `kid`, shaped exactly as IAM's
41
+ * `Signer.fromPrivateJwks` loads it.
42
+ */
43
+ const generateEs256Jwk = (): JsonWebKey & { kid: string; alg: string; use: string } => {
44
+ const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' })
45
+ const jwk = privateKey.export({ format: 'jwk' })
46
+ // RFC 7638 thumbprint over the canonical EC members, in lexicographic order (crv, kty, x, y).
47
+ const thumbprint = createHash('sha256').update(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y })).digest('base64url')
48
+ return { ...jwk, kid: thumbprint, alg: 'ES256', use: 'sig' }
49
+ }
50
+
51
+ /** IAM's token-signing material: a JSON array with one ES256 private JWK, index 0 the active signer. */
52
+ export const generateSigningKeys = (): string => JSON.stringify([generateEs256Jwk()])
53
+
54
+ /** Everything a container installation is seeded with. Several of these are shared by more than one service. */
55
+ export interface InstallationSecrets {
56
+ /** IAM's token-signing material: a JSON array of ES256 private JWKs, index 0 active. */
57
+ readonly signingKeys: string
58
+ /** Authenticates IAM's management `/rpc/*` surface. Held by IAM, control and Operations. */
59
+ readonly rpcKey: string
60
+ /** Authenticates IAM's `/auth/mint/*` surface, which the proxy calls on the cold path. */
61
+ readonly proxyKey: string
62
+ /** The `px_` admin bearer IAM admits as a synthetic global admin. `platform init` and `admin` take it. */
63
+ readonly provisioningKey: string
64
+ /** The catalog credential control and Operations share. No `px_` prefix — it is not an IAM credential. */
65
+ readonly operationsSyncKey: string
66
+ /** The control plane's vault KEK: 32 raw bytes at base64. Its loss is unrecoverable by design. */
67
+ readonly vaultKey: string
68
+ }
69
+
70
+ /** Roll one installation's secrets. Pure entropy in, no I/O, nothing persisted. */
71
+ export const generateInstallationSecrets = (): InstallationSecrets => ({
72
+ signingKeys: generateSigningKeys(),
73
+ rpcKey: randomPxKey(),
74
+ proxyKey: randomPxKey(),
75
+ provisioningKey: randomPxKey(),
76
+ operationsSyncKey: randomSecret(),
77
+ vaultKey: generateVaultKey(),
78
+ })
@@ -0,0 +1,206 @@
1
+ // The environment fabrika's four platform services read, as one installation's values.
2
+ //
3
+ // The variable NAMES are the services' own (`@fabrika/iam`'s `node/runtime.ts`, Control's and Operations'
4
+ // configuration, the proxy's `readProxyEnv`), so they are the same on every cloud. What a provider supplies
5
+ // is where a service's data lives — a DSN or the cloud's reference to one — and where the proxy dials IAM
6
+ // privately; it adds the variables of its own cloud beside these and writes the result.
7
+ //
8
+ // IAM's Bun runtime reads `ISSUER` and `ENVIRONMENT` UNPREFIXED and everything else with the
9
+ // `FABRIKA_IAM_` prefix. Both spellings below are the ones it actually reads.
10
+
11
+ import { FABRIKA_SERVICE_TABLE_DIGEST, IAM_PROXY_SECRET_VARIABLE } from '@fabrika/auth-core'
12
+ import { createHmac } from 'node:crypto'
13
+ import type { InstallationEmail } from './email'
14
+ import type { IamOAuthConfig } from './mcp'
15
+ import { type PlatformHosts, platformOrigin } from './proxy-manifest'
16
+ import type { InstallationSecrets } from './secrets'
17
+
18
+ /** The four services an installation configures. Each is a service of the platform's own topology. */
19
+ export type PlatformService = 'iam' | 'operations' | 'control' | 'proxy'
20
+
21
+ /** Each service's variables, in the order they are written. */
22
+ export type PlatformServiceEnvironment = Readonly<Record<PlatformService, ReadonlyMap<string, string>>>
23
+
24
+ /** IAM's OAuth configuration for MCP clients (ADR-0049): written only when the installation enables MCP authoring. */
25
+ export const IAM_OAUTH_CONFIG_VARIABLE = 'FABRIKA_IAM_OAUTH_CONFIG'
26
+
27
+ /** An object store's coordinates, in the provider's own spelling (values or references to them). */
28
+ export interface PlatformStorage {
29
+ readonly bucket: string
30
+ readonly accessKeyId: string
31
+ readonly secretAccessKey: string
32
+ readonly endpoint: string
33
+ }
34
+
35
+ /** Where each service's data lives. */
36
+ export interface PlatformData {
37
+ readonly iamDatabase: string
38
+ readonly controlDatabase: string
39
+ readonly operationsDatabase: string
40
+ /** Control's run logs. */
41
+ readonly runLogs: PlatformStorage
42
+ /** Operations' artifacts and source maps. */
43
+ readonly operationsBlobs: PlatformStorage
44
+ }
45
+
46
+ /** Where the installation answers. Both the bring-up and every deploy derive their variables from these. */
47
+ export interface PlatformPlacementInput {
48
+ readonly environment: string
49
+ readonly scheme: 'http' | 'https'
50
+ readonly hosts: PlatformHosts
51
+ /** The private address the platform proxy dials IAM at, which owns the session (`host:port`). */
52
+ readonly iamUpstream: string
53
+ }
54
+
55
+ /** What `installationServiceEnvironment` needs. Everything in it is settled before the first write. */
56
+ export interface InstallationServiceInput extends PlatformPlacementInput {
57
+ readonly secrets: InstallationSecrets
58
+ readonly data: PlatformData
59
+ /** IAM sends its own mail with it, and Control hands it to applications whose job declares `mailer: 'installation'`. */
60
+ readonly email: InstallationEmail
61
+ }
62
+
63
+ /** Compared byte-for-byte against a token's `iss`, so it is the PUBLIC issuer, never the private upstream. */
64
+ const proxySessionOwner = (input: PlatformPlacementInput): string =>
65
+ JSON.stringify({ issuer: platformOrigin(input.scheme, input.hosts.iam), upstream: input.iamUpstream })
66
+
67
+ /**
68
+ * EVERY fabrika variable a bring-up places, per service.
69
+ *
70
+ * The proxy manifest is deliberately absent: the deploy owns it, in the same run as the code it
71
+ * describes (ADR-0027).
72
+ */
73
+ export const installationServiceEnvironment = (input: InstallationServiceInput): PlatformServiceEnvironment => {
74
+ const { secrets, data } = input
75
+ const iamOrigin = platformOrigin(input.scheme, input.hosts.iam)
76
+ const operationsOrigin = platformOrigin(input.scheme, input.hosts.operations)
77
+ const email = input.email.kind === 'none' ? [] : [...input.email.variables]
78
+ return {
79
+ iam: new Map([
80
+ ['FABRIKA_IAM_DATABASE_URL', data.iamDatabase],
81
+ ['ENVIRONMENT', input.environment],
82
+ ['ISSUER', iamOrigin],
83
+ // Password only, by decision: OIDC needs an identity provider the operator has not been
84
+ // asked for. Both are STATED because IAM's own defaults are the other way round — OIDC on,
85
+ // password off — and it refuses to boot with neither.
86
+ ['FABRIKA_IAM_OIDC_ENABLED', 'false'],
87
+ ['FABRIKA_IAM_PASSWORD_ENABLED', 'true'],
88
+ ['FABRIKA_IAM_SIGNING_KEYS', secrets.signingKeys],
89
+ ['FABRIKA_IAM_RPC_KEY', secrets.rpcKey],
90
+ ['FABRIKA_IAM_PROXY_KEY', secrets.proxyKey],
91
+ ['FABRIKA_IAM_PROVISIONING_KEY', secrets.provisioningKey],
92
+ ...email,
93
+ ]),
94
+ operations: new Map([
95
+ ['FABRIKA_OPERATIONS_DATABASE_URL', data.operationsDatabase],
96
+ ['FABRIKA_OPERATIONS_BLOB_BUCKET', data.operationsBlobs.bucket],
97
+ ['FABRIKA_OPERATIONS_BLOB_ACCESS_KEY_ID', data.operationsBlobs.accessKeyId],
98
+ ['FABRIKA_OPERATIONS_BLOB_SECRET_ACCESS_KEY', data.operationsBlobs.secretAccessKey],
99
+ ['FABRIKA_OPERATIONS_BLOB_ENDPOINT', data.operationsBlobs.endpoint],
100
+ ['FABRIKA_OPERATIONS_PUBLIC_HOST', input.hosts.operations],
101
+ ['ENVIRONMENT', input.environment],
102
+ ['FABRIKA_IAM_ISSUER', iamOrigin],
103
+ ['OPERATIONS_SYNC_KEY', secrets.operationsSyncKey],
104
+ ['FABRIKA_IAM_RPC_KEY', secrets.rpcKey],
105
+ ]),
106
+ control: new Map([
107
+ ['FABRIKA_CONTROL_DATABASE_URL', data.controlDatabase],
108
+ ['ENVIRONMENT', input.environment],
109
+ // A bare HOST, not an origin: `controlPublicOrigin` accepts either.
110
+ ['FABRIKA_CONTROL_DOMAIN', input.hosts.control],
111
+ ['FABRIKA_IAM_ISSUER', iamOrigin],
112
+ ['OPERATIONS_ARTIFACT_ORIGIN', operationsOrigin],
113
+ ['FABRIKA_CONTROL_RUN_LOGS_BUCKET', data.runLogs.bucket],
114
+ ['FABRIKA_CONTROL_RUN_LOGS_ACCESS_KEY_ID', data.runLogs.accessKeyId],
115
+ ['FABRIKA_CONTROL_RUN_LOGS_SECRET_ACCESS_KEY', data.runLogs.secretAccessKey],
116
+ ['FABRIKA_CONTROL_RUN_LOGS_ENDPOINT', data.runLogs.endpoint],
117
+ ['FABRIKA_IAM_RPC_KEY', secrets.rpcKey],
118
+ ['OPERATIONS_SYNC_KEY', secrets.operationsSyncKey],
119
+ ['FABRIKA_CONTROL_VAULT_KEY', secrets.vaultKey],
120
+ ['FABRIKA_IAM_PROVISIONING_KEY', secrets.provisioningKey],
121
+ ...email,
122
+ ]),
123
+ proxy: new Map([
124
+ ['ENVIRONMENT', input.environment],
125
+ ['FABRIKA_IAM_ISSUER', iamOrigin],
126
+ ['FABRIKA_IAM_KEY', secrets.proxyKey],
127
+ ['FABRIKA_PROXY_SESSION_OWNER_JSON', proxySessionOwner(input)],
128
+ ]),
129
+ }
130
+ }
131
+
132
+ /**
133
+ * The fabrika variables whose VALUE a bring-up generates, per service.
134
+ *
135
+ * Their presence on a live service is what "this project already holds an installation" means, and they
136
+ * are written as credentials. A provider adds the names of its own that carry a generated value.
137
+ */
138
+ export const INSTALLATION_SECRET_VARIABLES: Readonly<Record<PlatformService, readonly string[]>> = {
139
+ iam: ['FABRIKA_IAM_SIGNING_KEYS', 'FABRIKA_IAM_RPC_KEY', 'FABRIKA_IAM_PROXY_KEY', 'FABRIKA_IAM_PROVISIONING_KEY'],
140
+ operations: ['OPERATIONS_SYNC_KEY', 'FABRIKA_IAM_RPC_KEY'],
141
+ control: ['FABRIKA_IAM_RPC_KEY', 'OPERATIONS_SYNC_KEY', 'FABRIKA_CONTROL_VAULT_KEY', 'FABRIKA_IAM_PROVISIONING_KEY'],
142
+ proxy: ['FABRIKA_IAM_KEY'],
143
+ }
144
+
145
+ /**
146
+ * The secret the platform proxy sends IAM's route, so IAM honours the client address and request id only from the proxy
147
+ * (ADR-0022 rule 5). Derived from the provisioning key, which every deploy holds, so each deploy writes the same value
148
+ * and nothing stores or reads one back. Never from the proxy key: namespace proxies hold that one.
149
+ */
150
+ export const deriveIamProxySecret = (provisioningKey: string): string =>
151
+ createHmac('sha256', provisioningKey).update('fabrika-installation-proxy-secret:iam').digest('hex')
152
+
153
+ /** What a deploy derives the service environment from. */
154
+ export interface DeployedServiceInput extends PlatformPlacementInput {
155
+ /** `FABRIKA_IAM_PROVISIONING_KEY`, which the IAM proxy secret is derived from. */
156
+ readonly provisioningKey: string
157
+ /** The digest of the console table the deploy's manifest publishes (`platformServiceTableDigest`). */
158
+ readonly controlTableDigest: string
159
+ /** Present only when the installation enables MCP authoring. */
160
+ readonly oauthConfig?: IamOAuthConfig
161
+ }
162
+
163
+ /**
164
+ * The per-installation configuration a deploy writes, derived from where the installation answers.
165
+ *
166
+ * IAM's OAuth configuration is present only when MCP authoring is enabled; without it the variable is left
167
+ * as it is, and the manifest — whose `/mcp` row then admits no OAuth token — is what turns MCP off.
168
+ */
169
+ export const deployedServiceEnvironment = (input: DeployedServiceInput): PlatformServiceEnvironment => {
170
+ const iamOrigin = platformOrigin(input.scheme, input.hosts.iam)
171
+ const iamProxySecret = deriveIamProxySecret(input.provisioningKey)
172
+ const iam = new Map([
173
+ ['ENVIRONMENT', input.environment],
174
+ // The `iss` of every minted token AND the OIDC redirect base, so it must be the address
175
+ // routed to the proxy in front of this service.
176
+ ['ISSUER', iamOrigin],
177
+ [IAM_PROXY_SECRET_VARIABLE, iamProxySecret],
178
+ ])
179
+ if (input.oauthConfig !== undefined) {
180
+ iam.set(IAM_OAUTH_CONFIG_VARIABLE, JSON.stringify(input.oauthConfig))
181
+ }
182
+ return {
183
+ iam,
184
+ operations: new Map([
185
+ ['ENVIRONMENT', input.environment],
186
+ ['FABRIKA_IAM_ISSUER', iamOrigin],
187
+ ['FABRIKA_OPERATIONS_PUBLIC_HOST', input.hosts.operations],
188
+ ]),
189
+ proxy: new Map([
190
+ ['ENVIRONMENT', input.environment],
191
+ ['FABRIKA_IAM_ISSUER', iamOrigin],
192
+ ['FABRIKA_PROXY_SESSION_OWNER_JSON', proxySessionOwner(input)],
193
+ // Caddy sends it on the session owner's route.
194
+ [IAM_PROXY_SECRET_VARIABLE, iamProxySecret],
195
+ ]),
196
+ control: new Map([
197
+ ['ENVIRONMENT', input.environment],
198
+ ['FABRIKA_IAM_ISSUER', iamOrigin],
199
+ // A bare host: `controlPublicOrigin` accepts either spelling.
200
+ ['FABRIKA_CONTROL_DOMAIN', input.hosts.control],
201
+ // Control picks its own table, MCP or not, by this digest, and refuses to start under another.
202
+ [FABRIKA_SERVICE_TABLE_DIGEST, input.controlTableDigest],
203
+ ['OPERATIONS_ARTIFACT_ORIGIN', platformOrigin(input.scheme, input.hosts.operations)],
204
+ ]),
205
+ }
206
+ }
@@ -5,8 +5,14 @@ export { EMAIL_FLAGS, type InstallationEmail, readInstallationEmail } from './em
5
5
  export { configureEnvironment, type EnvironmentConfig, type EnvironmentEffects, type ExistingEnvironmentProtection, existingEnvironmentProtection, triggerPlatformWorkflow, } from './environment';
6
6
  export { ghRepoExists, hasGhCli } from './gh';
7
7
  export { action, detail, fail, info, ok, step, url, warn } from './log';
8
+ export { type IamOAuthConfig, type McpClient, parseMcpClientsJson, platformIamOAuthConfig } from './mcp';
8
9
  export { type CommandEnv, describeArgument, readEnv, readFlag, requiredSetting, setting, shellWord } from './options';
10
+ export { assertPinnedTag } from './pin';
9
11
  export { confirm } from './prompt';
10
12
  export { branchProtectionCommand, DEPLOYMENT_BRANCH_POLICY, environmentPolicyCommand, environmentReviewerCommand, type GhAttempt, isPlanLimited, PLAN_LIMITED, probeSidecarBranchProtection, type ProtectionOutcome, protectSidecarBranch, } from './protection';
13
+ export { type PlatformHosts, type PlatformOAuthResourceTemplate, type PlatformOAuthScopeGrant, platformOrigin, type PlatformProxyApp, platformProxyAppFor, type PlatformProxyComposition, type PlatformProxyManifest, type PlatformProxyManifestTemplate, type PlatformProxyPlacement, type PlatformProxyService, platformServiceTableDigest, resolvePlatformProxyManifest, } from './proxy-manifest';
11
14
  export { INITIAL_SCAFFOLD_COMMIT_MESSAGE, REFRESH_SCAFFOLD_COMMIT_MESSAGE, scaffoldSidecarRepository, type SidecarScaffoldEffects, type SidecarScaffoldInput, type SidecarScaffoldResult, } from './scaffold';
15
+ export { generateInstallationSecrets, generateSigningKeys, generateVaultKey, type InstallationSecrets, randomPxKey, randomSecret } from './secrets';
16
+ export { checkedSecretsFilePath, renderSecretsFile, SECRETS_FILE_FLAG, SECRETS_FILE_VARIABLE, writeSecretsFile } from './secrets-file';
17
+ export { deployedServiceEnvironment, type DeployedServiceInput, deriveIamProxySecret, IAM_OAUTH_CONFIG_VARIABLE, INSTALLATION_SECRET_VARIABLES, installationServiceEnvironment, type InstallationServiceInput, type PlatformData, type PlatformPlacementInput, type PlatformService, type PlatformServiceEnvironment, type PlatformStorage, } from './service-environment';
12
18
  export { attempt, capture, probe, run, type ShellAttempt, type ShellStep } from './shell';
@@ -0,0 +1,18 @@
1
+ import { type OAuthManagedClient, type OAuthResourceDto } from '@fabrika/iam-contract';
2
+ import { type PlatformProxyComposition, type PlatformProxyManifestTemplate } from './proxy-manifest';
3
+ /** One operator-registered MCP client: its CIMD identity, plus where IAM fetches it when that differs. */
4
+ export interface McpClient extends OAuthManagedClient {
5
+ readonly metadataUrl?: string;
6
+ }
7
+ /** The document IAM parses from `FABRIKA_IAM_OAUTH_CONFIG`. */
8
+ export interface IamOAuthConfig {
9
+ readonly clients: readonly McpClient[];
10
+ readonly resources: readonly OAuthResourceDto[];
11
+ }
12
+ /**
13
+ * Parse the operator's MCP client list — a JSON array. Anything malformed, an empty list or a repeated
14
+ * client id is refused here, before a deploy writes a value IAM would refuse to boot with.
15
+ */
16
+ export declare const parseMcpClientsJson: (raw: string) => readonly McpClient[];
17
+ /** IAM's OAuth configuration for one placed installation: the clients, and one resource per app that serves one. */
18
+ export declare const platformIamOAuthConfig: (template: PlatformProxyManifestTemplate, composition: PlatformProxyComposition, clients: readonly McpClient[]) => IamOAuthConfig;
@@ -0,0 +1,2 @@
1
+ /** The pinned ref, or an error naming what was found. A branch is refused, deliberately and loudly. */
2
+ export declare const assertPinnedTag: (ref: string) => string;
@@ -0,0 +1,109 @@
1
+ import { type InstallationEndpointTable } from '@fabrika/auth-core';
2
+ import { type InstallationProxyApp } from '@fabrika/proxy-core/manifest';
3
+ /** The platform services an installation's proxy fronts. Each name is a service hostname in the topology. */
4
+ export type PlatformProxyService = 'iam' | 'control' | 'operations';
5
+ /** The public hostname of each platform service, without a scheme and without a port. */
6
+ export type PlatformHosts = Readonly<Record<PlatformProxyService, string>>;
7
+ /** `https://<host>` — the origin a browser, a token's `iss` and a return-origin registry all use. */
8
+ export declare const platformOrigin: (scheme: "http" | "https", host: string) => string;
9
+ /** What one OAuth scope lets a token do: the owning app's actions, resolved by IAM at the token endpoint. */
10
+ export interface PlatformOAuthScopeGrant {
11
+ readonly scope: string;
12
+ readonly actions: readonly string[];
13
+ }
14
+ /**
15
+ * A path an app serves to OAuth clients, protected only on an installation that enables it.
16
+ *
17
+ * The resource URI is the app's public origin plus `path`, so the template holds the path and a deploy
18
+ * binds the origin. Copied from the owning service module by the generator, like `table`.
19
+ */
20
+ export interface PlatformOAuthResourceTemplate {
21
+ readonly path: string;
22
+ readonly scopes: readonly string[];
23
+ readonly scopeGrants: readonly PlatformOAuthScopeGrant[];
24
+ }
25
+ /**
26
+ * One fronted app, in the form that is the same on every installation: protected by its service contract (ADR-0022
27
+ * "Installation entries"), copied in by the generator and never written by hand.
28
+ */
29
+ export interface PlatformProxyApp {
30
+ /** The IAM app id. It is the audience of every token the proxy mints for this app's host. */
31
+ readonly id: string;
32
+ /** The topology service that answers for it. */
33
+ readonly service: PlatformProxyService;
34
+ /**
35
+ * The proxy's public listener this app answers on.
36
+ *
37
+ * On a `zerops-subdomain` installation a port IS a hostname — Zerops mints one generated host per
38
+ * HTTP port — so this is the only installation-independent half of `hosts`. A custom-domain
39
+ * installation ignores it: every domain arrives on one listener and the `Host` header decides.
40
+ */
41
+ readonly port: number;
42
+ /** Where the proxy dials it over the project's private network. */
43
+ readonly upstream: string;
44
+ /** The service's rows; with an `oauthResource`, the table served when the composition names an authorization server. */
45
+ readonly table: InstallationEndpointTable;
46
+ /** Present only on an app that can serve OAuth clients; off unless the composition names an authorization server. */
47
+ readonly oauthResource?: PlatformOAuthResourceTemplate;
48
+ /**
49
+ * Present exactly with `oauthResource`: the service's table when it serves no OAuth client. The service picks the
50
+ * same one, by the digest the deploy writes beside it (`platformServiceTableDigest`).
51
+ */
52
+ readonly tableWithoutOAuth?: InstallationEndpointTable;
53
+ }
54
+ /** Everything about an installation's manifest that does not depend on WHICH installation it is. */
55
+ export interface PlatformProxyManifestTemplate {
56
+ readonly apps: readonly PlatformProxyApp[];
57
+ }
58
+ /**
59
+ * The template's entry for one platform service.
60
+ *
61
+ * The app IDS live in the template, so a caller that needs one — the deploy's schema reconcile needs
62
+ * the console's — reads it from there rather than restating a literal that could drift from the
63
+ * document the proxy is actually configured with.
64
+ */
65
+ export declare const platformProxyAppFor: (template: PlatformProxyManifestTemplate, service: PlatformProxyService) => PlatformProxyApp;
66
+ /** Where one app answers in a particular composition. */
67
+ export interface PlatformProxyPlacement {
68
+ /** Public hostnames, without a port — `parseProxyManifest` refuses a `:port` suffix. */
69
+ readonly hosts: readonly string[];
70
+ /** Overrides the private dial address. The local composition runs IAM on a port of its own. */
71
+ readonly upstream?: string;
72
+ }
73
+ /** One composition of the platform: a deployed installation, or the local Docker stack. */
74
+ export interface PlatformProxyComposition {
75
+ /** The scheme the BROWSER speaks to these apps — configuration, never a header (see `ProxyApp.scheme`). */
76
+ readonly scheme: 'http' | 'https';
77
+ readonly placement: Readonly<Record<PlatformProxyService, PlatformProxyPlacement>>;
78
+ /**
79
+ * The public IAM origin that issues OAuth tokens. Present only when the installation enables MCP
80
+ * authoring; absent leaves every `oauthResource` unregistered and serves each service's table without OAuth.
81
+ */
82
+ readonly authorizationServer?: string;
83
+ /** The port browsers reach every app on, when it is not the scheme's default. The local composition's is 18080. */
84
+ readonly publicPort?: number;
85
+ }
86
+ /**
87
+ * The RFC 8707 resource URI and RFC 9728 metadata URL of an app's OAuth resource, bound to the app's
88
+ * FIRST host: the proxy refuses a resource on a host the app does not answer on.
89
+ */
90
+ export declare const platformOAuthResourceUris: (composition: Pick<PlatformProxyComposition, "scheme" | "publicPort">, hosts: readonly string[], template: PlatformOAuthResourceTemplate) => {
91
+ readonly resource: string;
92
+ readonly resourceMetadata: string;
93
+ };
94
+ /**
95
+ * Bind a template to one composition and get the document the proxy actually parses.
96
+ *
97
+ * The result is returned THROUGH `parseProxyManifest`, so a duplicate id, a repeated host or a `:port`
98
+ * suffix is refused right here instead of at a deployed proxy's next build.
99
+ */
100
+ export declare const resolvePlatformProxyManifest: (template: PlatformProxyManifestTemplate, composition: PlatformProxyComposition) => PlatformProxyManifest;
101
+ /** The platform proxy's manifest: one installation entry per platform service. */
102
+ export interface PlatformProxyManifest {
103
+ apps: InstallationProxyApp[];
104
+ }
105
+ /**
106
+ * `FABRIKA_SERVICE_TABLE_DIGEST` for a service: the digest of the table this manifest publishes for it, which the
107
+ * service compares with its own and refuses to start under another.
108
+ */
109
+ export declare const platformServiceTableDigest: (manifest: PlatformProxyManifest, appId: string) => string;
@@ -0,0 +1,18 @@
1
+ /** `--secrets-file`: where the local copy goes. A new file, outside the source checkout. */
2
+ export declare const SECRETS_FILE_FLAG = "--secrets-file";
3
+ export declare const SECRETS_FILE_VARIABLE = "FABRIKA_PLATFORM_SECRETS_FILE";
4
+ /**
5
+ * Settle the path before anything is contacted.
6
+ *
7
+ * Refused when it exists, because overwriting one would destroy another installation's only copy, and
8
+ * when it is inside the source checkout, where it would dirty the checkout a deploy uploads and could be
9
+ * committed.
10
+ */
11
+ export declare const checkedSecretsFilePath: (path: string, sourceDir: string) => string;
12
+ /**
13
+ * The file's text: comment lines, then shell-sourceable assignments, named as the commands that read
14
+ * them name them. `header` is the provider's own lines, each written as a `#` comment.
15
+ */
16
+ export declare const renderSecretsFile: (header: readonly string[], assignments: readonly (readonly [string, string])[]) => string;
17
+ /** Create the file with mode 0600, failing rather than replacing one that appeared since the check. */
18
+ export declare const writeSecretsFile: (path: string, text: string) => Promise<void>;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * A 256-bit secret in base64url, never starting with `-` or `_`.
3
+ *
4
+ * The re-roll is copied from `@fabrika/local-stack`'s `prepare.ts` and it is not superstition: a
5
+ * credential beginning with `-` reads as a FLAG to anything that later takes it on a command line, no
6
+ * matter how it is quoted. One rolled password beginning with `-` made `mc alias set` print its usage
7
+ * and loop forever. It costs nothing and removes a bug that appears about one install in sixteen.
8
+ */
9
+ export declare const randomSecret: () => string;
10
+ /** The `px_` prefix IAM's own credentials carry, so a key looks like what it is wherever it turns up. */
11
+ export declare const randomPxKey: () => string;
12
+ /** The control plane's vault KEK. base64, NOT base64url: the vault imports these bytes as an AES key. */
13
+ export declare const generateVaultKey: () => string;
14
+ /** IAM's token-signing material: a JSON array with one ES256 private JWK, index 0 the active signer. */
15
+ export declare const generateSigningKeys: () => string;
16
+ /** Everything a container installation is seeded with. Several of these are shared by more than one service. */
17
+ export interface InstallationSecrets {
18
+ /** IAM's token-signing material: a JSON array of ES256 private JWKs, index 0 active. */
19
+ readonly signingKeys: string;
20
+ /** Authenticates IAM's management `/rpc/*` surface. Held by IAM, control and Operations. */
21
+ readonly rpcKey: string;
22
+ /** Authenticates IAM's `/auth/mint/*` surface, which the proxy calls on the cold path. */
23
+ readonly proxyKey: string;
24
+ /** The `px_` admin bearer IAM admits as a synthetic global admin. `platform init` and `admin` take it. */
25
+ readonly provisioningKey: string;
26
+ /** The catalog credential control and Operations share. No `px_` prefix — it is not an IAM credential. */
27
+ readonly operationsSyncKey: string;
28
+ /** The control plane's vault KEK: 32 raw bytes at base64. Its loss is unrecoverable by design. */
29
+ readonly vaultKey: string;
30
+ }
31
+ /** Roll one installation's secrets. Pure entropy in, no I/O, nothing persisted. */
32
+ export declare const generateInstallationSecrets: () => InstallationSecrets;
@@ -0,0 +1,78 @@
1
+ import type { InstallationEmail } from './email';
2
+ import type { IamOAuthConfig } from './mcp';
3
+ import { type PlatformHosts } from './proxy-manifest';
4
+ import type { InstallationSecrets } from './secrets';
5
+ /** The four services an installation configures. Each is a service of the platform's own topology. */
6
+ export type PlatformService = 'iam' | 'operations' | 'control' | 'proxy';
7
+ /** Each service's variables, in the order they are written. */
8
+ export type PlatformServiceEnvironment = Readonly<Record<PlatformService, ReadonlyMap<string, string>>>;
9
+ /** IAM's OAuth configuration for MCP clients (ADR-0049): written only when the installation enables MCP authoring. */
10
+ export declare const IAM_OAUTH_CONFIG_VARIABLE = "FABRIKA_IAM_OAUTH_CONFIG";
11
+ /** An object store's coordinates, in the provider's own spelling (values or references to them). */
12
+ export interface PlatformStorage {
13
+ readonly bucket: string;
14
+ readonly accessKeyId: string;
15
+ readonly secretAccessKey: string;
16
+ readonly endpoint: string;
17
+ }
18
+ /** Where each service's data lives. */
19
+ export interface PlatformData {
20
+ readonly iamDatabase: string;
21
+ readonly controlDatabase: string;
22
+ readonly operationsDatabase: string;
23
+ /** Control's run logs. */
24
+ readonly runLogs: PlatformStorage;
25
+ /** Operations' artifacts and source maps. */
26
+ readonly operationsBlobs: PlatformStorage;
27
+ }
28
+ /** Where the installation answers. Both the bring-up and every deploy derive their variables from these. */
29
+ export interface PlatformPlacementInput {
30
+ readonly environment: string;
31
+ readonly scheme: 'http' | 'https';
32
+ readonly hosts: PlatformHosts;
33
+ /** The private address the platform proxy dials IAM at, which owns the session (`host:port`). */
34
+ readonly iamUpstream: string;
35
+ }
36
+ /** What `installationServiceEnvironment` needs. Everything in it is settled before the first write. */
37
+ export interface InstallationServiceInput extends PlatformPlacementInput {
38
+ readonly secrets: InstallationSecrets;
39
+ readonly data: PlatformData;
40
+ /** IAM sends its own mail with it, and Control hands it to applications whose job declares `mailer: 'installation'`. */
41
+ readonly email: InstallationEmail;
42
+ }
43
+ /**
44
+ * EVERY fabrika variable a bring-up places, per service.
45
+ *
46
+ * The proxy manifest is deliberately absent: the deploy owns it, in the same run as the code it
47
+ * describes (ADR-0027).
48
+ */
49
+ export declare const installationServiceEnvironment: (input: InstallationServiceInput) => PlatformServiceEnvironment;
50
+ /**
51
+ * The fabrika variables whose VALUE a bring-up generates, per service.
52
+ *
53
+ * Their presence on a live service is what "this project already holds an installation" means, and they
54
+ * are written as credentials. A provider adds the names of its own that carry a generated value.
55
+ */
56
+ export declare const INSTALLATION_SECRET_VARIABLES: Readonly<Record<PlatformService, readonly string[]>>;
57
+ /**
58
+ * The secret the platform proxy sends IAM's route, so IAM honours the client address and request id only from the proxy
59
+ * (ADR-0022 rule 5). Derived from the provisioning key, which every deploy holds, so each deploy writes the same value
60
+ * and nothing stores or reads one back. Never from the proxy key: namespace proxies hold that one.
61
+ */
62
+ export declare const deriveIamProxySecret: (provisioningKey: string) => string;
63
+ /** What a deploy derives the service environment from. */
64
+ export interface DeployedServiceInput extends PlatformPlacementInput {
65
+ /** `FABRIKA_IAM_PROVISIONING_KEY`, which the IAM proxy secret is derived from. */
66
+ readonly provisioningKey: string;
67
+ /** The digest of the console table the deploy's manifest publishes (`platformServiceTableDigest`). */
68
+ readonly controlTableDigest: string;
69
+ /** Present only when the installation enables MCP authoring. */
70
+ readonly oauthConfig?: IamOAuthConfig;
71
+ }
72
+ /**
73
+ * The per-installation configuration a deploy writes, derived from where the installation answers.
74
+ *
75
+ * IAM's OAuth configuration is present only when MCP authoring is enabled; without it the variable is left
76
+ * as it is, and the manifest — whose `/mcp` row then admits no OAuth token — is what turns MCP off.
77
+ */
78
+ export declare const deployedServiceEnvironment: (input: DeployedServiceInput) => PlatformServiceEnvironment;