@fabrika/provider-zerops 0.9.0-dev.1 → 0.9.0-dev.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/package.json +17 -14
  2. package/sandbox/Dockerfile +16 -0
  3. package/sandbox/bin/postgres-auth.sh +38 -0
  4. package/sandbox/bin/reset.sh +12 -0
  5. package/sandbox/bin/run-build.sh +35 -0
  6. package/sandbox/bin/run-launcher.sh +18 -0
  7. package/sandbox/bin/start-launcher.sh +25 -0
  8. package/sandbox/bin/stop.sh +47 -0
  9. package/sandbox/init.sh +61 -0
  10. package/src/api/client.ts +15 -1
  11. package/src/api/errors.ts +7 -3
  12. package/src/api/readers.ts +29 -0
  13. package/src/api/types.ts +52 -0
  14. package/src/api.ts +2 -0
  15. package/src/cli.ts +11 -0
  16. package/src/collaborators.ts +0 -14
  17. package/src/compile.ts +1 -1
  18. package/src/control.ts +159 -92
  19. package/src/execution.ts +45 -195
  20. package/src/index.ts +2 -0
  21. package/src/installation/admin.ts +1 -1
  22. package/src/installation/deploy-options.ts +10 -2
  23. package/src/installation/deploy.ts +241 -81
  24. package/src/installation/generated/platform-console-schema.ts +3 -0
  25. package/src/installation/generated/platform-proxy-manifest.ts +1 -1
  26. package/src/installation/guide.md +53 -19
  27. package/src/installation/hosts.ts +1 -7
  28. package/src/installation/index.ts +20 -16
  29. package/src/installation/init-options.ts +2 -1
  30. package/src/installation/install-environment.ts +47 -108
  31. package/src/installation/install-options.ts +3 -1
  32. package/src/installation/install-secrets.ts +24 -68
  33. package/src/installation/install.ts +9 -4
  34. package/src/installation/plain-credentials.ts +91 -0
  35. package/src/installation/sidecar.ts +5 -26
  36. package/src/installation/templates/README.md +13 -12
  37. package/src/installation/templates/platform.yml +3 -0
  38. package/src/installation/topology/setups.ts +17 -4
  39. package/src/installation/topology/topology.ts +33 -23
  40. package/src/installation/upgrade-options.ts +2 -2
  41. package/src/managed-env.ts +1 -174
  42. package/src/manifest.ts +14 -17
  43. package/src/namespace/claims.ts +60 -1
  44. package/src/namespace/codec.ts +17 -0
  45. package/src/namespace/errors.ts +22 -1
  46. package/src/namespace/manifest.ts +36 -23
  47. package/src/namespace/provisioning.ts +88 -114
  48. package/src/namespace/proxy-attempt.ts +14 -2
  49. package/src/namespace/proxy-reads.ts +28 -23
  50. package/src/namespace/proxy-secrets.ts +18 -5
  51. package/src/namespace/sandbox-host.ts +212 -0
  52. package/src/namespace/subdomain.ts +113 -0
  53. package/src/namespace/topology.ts +1 -1
  54. package/src/namespace/types.ts +13 -0
  55. package/src/namespace/update.ts +1 -0
  56. package/src/namespace-cli.ts +152 -0
  57. package/src/plain-credentials.ts +90 -0
  58. package/src/plan.ts +1 -6
  59. package/src/provider.ts +88 -166
  60. package/src/proxy-manifest-carrier.ts +39 -0
  61. package/src/sandbox/base-image.ts +100 -0
  62. package/src/sandbox/constants.ts +44 -0
  63. package/src/sandbox/deploy.ts +471 -0
  64. package/src/sandbox/dev-artifact.ts +206 -0
  65. package/src/sandbox/lifecycle.ts +204 -0
  66. package/src/sandbox/scripts.ts +26 -0
  67. package/src/sandbox-host.ts +28 -0
  68. package/src/source/port.ts +5 -0
  69. package/src/types.ts +6 -2
  70. package/src/zbox/client.ts +259 -0
  71. package/src/zbox/errors.ts +45 -0
  72. package/src/zbox/index.ts +22 -0
  73. package/src/zbox/types.ts +165 -0
  74. package/types/src/api/client.d.ts +5 -0
  75. package/types/src/api/errors.d.ts +26 -0
  76. package/types/src/api/polling.d.ts +41 -0
  77. package/types/src/api/readers.d.ts +1115 -0
  78. package/types/src/api/service-env-limit.d.ts +17 -0
  79. package/types/src/api/service-env-response.d.ts +23 -0
  80. package/types/src/api/types.d.ts +687 -0
  81. package/types/src/api.d.ts +6 -0
  82. package/types/src/authoring.d.ts +9 -0
  83. package/types/src/cli-args.d.ts +19 -0
  84. package/types/src/cli.d.ts +13 -0
  85. package/types/src/collaborators.d.ts +16 -0
  86. package/types/src/compile.d.ts +91 -0
  87. package/types/src/control.d.ts +51 -0
  88. package/types/src/database-budget.d.ts +38 -0
  89. package/types/src/descriptor.d.ts +28 -0
  90. package/types/src/execution.d.ts +114 -0
  91. package/types/src/exposure.d.ts +47 -0
  92. package/types/src/index.d.ts +31 -0
  93. package/types/src/installation/admin-options.d.ts +24 -0
  94. package/types/src/installation/admin.d.ts +35 -0
  95. package/types/src/installation/checker-release.d.ts +12 -0
  96. package/types/src/installation/deploy-options.d.ts +42 -0
  97. package/types/src/installation/deploy.d.ts +136 -0
  98. package/types/src/installation/generated/platform-console-schema.d.ts +2 -0
  99. package/types/src/installation/generated/platform-proxy-manifest.d.ts +2 -0
  100. package/types/src/installation/hosts.d.ts +34 -0
  101. package/types/src/installation/index.d.ts +7 -0
  102. package/types/src/installation/init-options.d.ts +38 -0
  103. package/types/src/installation/init.d.ts +60 -0
  104. package/types/src/installation/install-collaborators.d.ts +24 -0
  105. package/types/src/installation/install-environment.d.ts +63 -0
  106. package/types/src/installation/install-options.d.ts +49 -0
  107. package/types/src/installation/install-project.d.ts +13 -0
  108. package/types/src/installation/install-provisioning.d.ts +58 -0
  109. package/types/src/installation/install-secrets.d.ts +17 -0
  110. package/types/src/installation/install-token.d.ts +10 -0
  111. package/types/src/installation/install.d.ts +23 -0
  112. package/types/src/installation/installation-source.d.ts +8 -0
  113. package/types/src/installation/log.d.ts +44 -0
  114. package/types/src/installation/machine-key.d.ts +19 -0
  115. package/types/src/installation/placement-options.d.ts +11 -0
  116. package/types/src/installation/plain-credentials.d.ts +20 -0
  117. package/types/src/installation/platform-archive.d.ts +7 -0
  118. package/types/src/installation/platform-source.d.ts +8 -0
  119. package/types/src/installation/platform-upload.d.ts +3 -0
  120. package/types/src/installation/sidecar.d.ts +49 -0
  121. package/types/src/installation/source-options.d.ts +1 -0
  122. package/types/src/installation/topology/artifacts.d.ts +8 -0
  123. package/types/src/installation/topology/index.d.ts +5 -0
  124. package/types/src/installation/topology/installation-schemas.d.ts +2242 -0
  125. package/types/src/installation/topology/invariants.d.ts +23 -0
  126. package/types/src/installation/topology/setups.d.ts +59 -0
  127. package/types/src/installation/topology/topology.d.ts +153 -0
  128. package/types/src/installation/topology/validate.d.ts +11 -0
  129. package/types/src/installation/upgrade-options.d.ts +26 -0
  130. package/types/src/installation/upgrade-output.d.ts +6 -0
  131. package/types/src/installation/upgrade.d.ts +88 -0
  132. package/types/src/managed-env.d.ts +24 -0
  133. package/types/src/manifest.d.ts +199 -0
  134. package/types/src/namespace/claims.d.ts +16 -0
  135. package/types/src/namespace/codec.d.ts +352 -0
  136. package/types/src/namespace/constants.d.ts +25 -0
  137. package/types/src/namespace/errors.d.ts +25 -0
  138. package/types/src/namespace/manifest.d.ts +4 -0
  139. package/types/src/namespace/operator.d.ts +12 -0
  140. package/types/src/namespace/provisioning.d.ts +4 -0
  141. package/types/src/namespace/proxy-attempt.d.ts +39 -0
  142. package/types/src/namespace/proxy-reads.d.ts +27 -0
  143. package/types/src/namespace/proxy-secrets.d.ts +8 -0
  144. package/types/src/namespace/proxy-source.d.ts +74 -0
  145. package/types/src/namespace/sandbox-host.d.ts +23 -0
  146. package/types/src/namespace/subdomain.d.ts +43 -0
  147. package/types/src/namespace/topology.d.ts +9 -0
  148. package/types/src/namespace/types.d.ts +111 -0
  149. package/types/src/namespace/update.d.ts +6 -0
  150. package/types/src/namespace/validation.d.ts +12 -0
  151. package/types/src/namespace-cli.d.ts +2 -0
  152. package/types/src/namespace.d.ts +9 -0
  153. package/types/src/plain-credentials.d.ts +7 -0
  154. package/types/src/plan.d.ts +11 -0
  155. package/types/src/provider.d.ts +60 -0
  156. package/types/src/proxy-manifest-carrier.d.ts +37 -0
  157. package/types/src/sandbox/base-image.d.ts +28 -0
  158. package/types/src/sandbox/constants.d.ts +30 -0
  159. package/types/src/sandbox/deploy.d.ts +75 -0
  160. package/types/src/sandbox/dev-artifact.d.ts +51 -0
  161. package/types/src/sandbox/lifecycle.d.ts +27 -0
  162. package/types/src/sandbox/scripts.d.ts +11 -0
  163. package/types/src/sandbox-host.d.ts +16 -0
  164. package/types/src/schema.generated.d.ts +376 -0
  165. package/types/src/service-names.d.ts +4 -0
  166. package/types/src/service-references.d.ts +13 -0
  167. package/types/src/source/constants.d.ts +6 -0
  168. package/types/src/source/port.d.ts +65 -0
  169. package/types/src/source/types.d.ts +4 -0
  170. package/types/src/source/validation.d.ts +19 -0
  171. package/types/src/source.d.ts +2 -0
  172. package/types/src/types.d.ts +125 -0
  173. package/types/src/version-attempt.d.ts +8 -0
  174. package/types/src/zbox/client.d.ts +2 -0
  175. package/types/src/zbox/errors.d.ts +25 -0
  176. package/types/src/zbox/index.d.ts +3 -0
  177. package/types/src/zbox/types.d.ts +433 -0
  178. package/src/installation/mcp.ts +0 -102
  179. package/src/installation/proxy-manifest.ts +0 -214
  180. package/src/installation/secrets.ts +0 -78
@@ -0,0 +1,212 @@
1
+ import { waitForProcess, type ZeropsApi, type ZeropsService, type ZeropsServiceStatus } from '../api'
2
+ import { defaultSleep, type Sleeper } from '../collaborators'
3
+ import {
4
+ SANDBOX_HOST_API_PORT,
5
+ SANDBOX_HOST_HOSTNAME,
6
+ SANDBOX_HOST_KEY_VARIABLE,
7
+ SANDBOX_HOST_SERVICE_TYPE,
8
+ SANDBOX_HOST_TYPE,
9
+ } from '../sandbox-host'
10
+ import { createZboxClient, ZboxApiError, type ZboxClient, type ZboxFetch, type ZboxWorkspace } from '../zbox'
11
+ import { namespaceError, ZEROPS_SANDBOX_HOST_API_OPEN, ZEROPS_SANDBOX_HOST_KEY_REFUSED, ZEROPS_SANDBOX_HOST_UNSUPPORTED } from './errors'
12
+ import { ensureSubdomainAccess, readSubdomainHosts } from './subdomain'
13
+ import type { NormalizedZeropsNamespaceTarget, ZeropsNamespaceSandboxHost } from './types'
14
+ import { validateService } from './validation'
15
+
16
+ export type ZeropsSandboxHostApi = Pick<
17
+ ZeropsApi,
18
+ | 'listProjectServices'
19
+ | 'importServices'
20
+ | 'getProcess'
21
+ | 'getService'
22
+ | 'putServiceEnv'
23
+ | 'startService'
24
+ | 'stopService'
25
+ | 'enableSubdomainAccess'
26
+ | 'listServiceEnv'
27
+ >
28
+
29
+ export interface ZeropsSandboxHostInput {
30
+ readonly namespaceId: string
31
+ readonly target: NormalizedZeropsNamespaceTarget
32
+ /** The Box API key Control composed from its vault; written to the service, sent as a bearer, never read back. */
33
+ readonly sandboxKey: string
34
+ readonly api: ZeropsSandboxHostApi
35
+ readonly zboxFetch?: ZboxFetch
36
+ readonly sleep?: Sleeper
37
+ readonly signal: AbortSignal
38
+ }
39
+
40
+ /** One service only, never the steady topology: re-applying that at a service carrying code activates an empty version. */
41
+ const SANDBOX_HOST_IMPORT_YAML = `services:
42
+ - hostname: ${SANDBOX_HOST_HOSTNAME}
43
+ type: ${SANDBOX_HOST_TYPE}
44
+ envIsolation: service
45
+ `
46
+
47
+ /** A host someone stopped is started again; UNVERIFIED which of these a stopped `zbox@1` service reads. */
48
+ const NOT_STARTED: ReadonlySet<ZeropsServiceStatus> = new Set(['READY_TO_DEPLOY', 'STOPPED', 'SERVICE_STOPPED'])
49
+
50
+ const POLL_INTERVAL_MS = 3000
51
+
52
+ /** A started Box answers within seconds; the subdomain's first request can lag it a little more. */
53
+ const BOX_REACH_ATTEMPTS = 20
54
+
55
+ const PROBE_TIMEOUT_MS = 30_000
56
+
57
+ /** A sandbox host on a `zerops-subdomain` namespace is refused: a dev environment's wildcard needs a custom domain. */
58
+ export const assertSandboxHostAllowed = (namespaceId: string, target: NormalizedZeropsNamespaceTarget): void => {
59
+ if (target.publicAccess !== 'zerops-subdomain') return
60
+ throw namespaceError(
61
+ ZEROPS_SANDBOX_HOST_UNSUPPORTED,
62
+ `deployment namespace \`${namespaceId}\` is published on zerops.app subdomains; a dev environment needs a custom-domain namespace`,
63
+ false,
64
+ )
65
+ }
66
+
67
+ const findSandboxHost = async (api: ZeropsSandboxHostApi, projectId: string, signal: AbortSignal): Promise<ZeropsService | null> => {
68
+ const matches = (await api.listProjectServices({ projectId, signal })).filter((service) => service.name === SANDBOX_HOST_HOSTNAME)
69
+ if (matches.length > 1) throw new Error(`Zerops namespace has multiple services named \`${SANDBOX_HOST_HOSTNAME}\``)
70
+ return matches[0] ?? null
71
+ }
72
+
73
+ const waitFor = async (input: ZeropsSandboxHostInput, processId: string, label: string): Promise<void> => {
74
+ await waitForProcess({ api: input.api, processId, sleep: input.sleep ?? defaultSleep, signal: input.signal, label })
75
+ }
76
+
77
+ /** The key is a credential: written sensitive, never compared, never read back (a sensitive value reads REDACTED). */
78
+ const writeKey = async (input: ZeropsSandboxHostInput, serviceId: string): Promise<void> => {
79
+ await input.api.putServiceEnv({ serviceId, key: SANDBOX_HOST_KEY_VARIABLE, value: input.sandboxKey, sensitive: true, signal: input.signal })
80
+ }
81
+
82
+ /**
83
+ * Create the service. The platform starts it at once with a key it generated itself (measured live), so Box first
84
+ * refuses ours and the rekey below is what keys it.
85
+ */
86
+ const createSandboxHost = async (input: ZeropsSandboxHostInput, projectId: string): Promise<ZeropsService> => {
87
+ const imported = await input.api.importServices({ projectId, yaml: SANDBOX_HOST_IMPORT_YAML, signal: input.signal })
88
+ for (const service of imported.services) {
89
+ for (const process of service.processes) await waitFor(input, process.id, 'sandbox host import')
90
+ }
91
+ const created = await findSandboxHost(input.api, projectId, input.signal)
92
+ if (created === null) throw new Error(`Zerops namespace project ${projectId} has no sandbox host after its import`)
93
+ return created
94
+ }
95
+
96
+ /** The Box API origin: the `https://` subdomain the platform published for the API port. */
97
+ const readApiOrigin = async (input: ZeropsSandboxHostInput, serviceId: string): Promise<string> => {
98
+ const host = (await readSubdomainHosts(input.api, serviceId, input.signal)).find((entry) => entry.port === SANDBOX_HOST_API_PORT)
99
+ if (host === undefined) {
100
+ throw namespaceError(
101
+ 'sandboxHostNotPublished',
102
+ `Zerops sandbox host ${serviceId} publishes no subdomain for port ${SANDBOX_HOST_API_PORT} yet`,
103
+ true,
104
+ )
105
+ }
106
+ return `https://${host.host}`
107
+ }
108
+
109
+ const isUnauthorized = (error: unknown): boolean => error instanceof ZboxApiError && (error.status === 401 || error.code === 'unauthorized')
110
+
111
+ /** Box not answering yet: unreachable, timed out, or the platform's balancer answering for a starting container. */
112
+ const isStarting = (error: unknown): boolean => error instanceof ZboxApiError && (error.status === 0 || error.status >= 500)
113
+
114
+ /** The workspace, or `unauthorized` when Box refuses the key. Retries only while Box is starting. */
115
+ const reachWorkspace = async (input: ZeropsSandboxHostInput, client: ZboxClient): Promise<ZboxWorkspace | 'unauthorized'> => {
116
+ for (let attempt = 1;; attempt += 1) {
117
+ try {
118
+ return await client.getWorkspace(input.signal)
119
+ } catch (error) {
120
+ if (isUnauthorized(error)) return 'unauthorized'
121
+ input.signal.throwIfAborted()
122
+ if (!isStarting(error) || attempt >= BOX_REACH_ATTEMPTS) throw error
123
+ }
124
+ await (input.sleep ?? defaultSleep)(POLL_INTERVAL_MS, input.signal)
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Box reads its key from its environment when it starts, so a refused key is written again and the service restarted.
130
+ * Measured live: a fresh host always takes this path, since the platform generated its own key at import.
131
+ */
132
+ const rekey = async (input: ZeropsSandboxHostInput, client: ZboxClient, serviceId: string): Promise<void> => {
133
+ console.info(`Zerops namespace ${input.namespaceId}: restarting sandbox host ${serviceId} with the namespace's key`)
134
+ await writeKey(input, serviceId)
135
+ await waitFor(input, (await input.api.stopService({ serviceId, signal: input.signal })).id, 'sandbox host stop')
136
+ await waitFor(input, (await input.api.startService({ serviceId, signal: input.signal })).id, 'sandbox host start')
137
+ if (await reachWorkspace(input, client) === 'unauthorized') {
138
+ throw namespaceError(
139
+ ZEROPS_SANDBOX_HOST_KEY_REFUSED,
140
+ `Zerops sandbox host ${serviceId} still refuses the namespace's key after a restart with it`,
141
+ false,
142
+ )
143
+ }
144
+ }
145
+
146
+ /** Whether Box refuses a request that carries no key. Only the status decides; the body is never read. */
147
+ const refusesWithoutKey = async (input: ZeropsSandboxHostInput, apiOrigin: string): Promise<boolean> => {
148
+ let response: Response
149
+ try {
150
+ response = await (input.zboxFetch ?? fetch)(`${apiOrigin}/api/rest/workspace`, {
151
+ method: 'GET',
152
+ headers: { accept: 'application/json' },
153
+ signal: AbortSignal.any([input.signal, AbortSignal.timeout(PROBE_TIMEOUT_MS)]),
154
+ })
155
+ } catch {
156
+ input.signal.throwIfAborted()
157
+ throw new ZboxApiError('probe workspace without a key', 0, 'unreachable')
158
+ }
159
+ await response.body?.cancel()
160
+ if (response.status === 401) return true
161
+ if (response.status >= 500 || response.status === 429) {
162
+ throw new ZboxApiError('probe workspace without a key', response.status, `http_${response.status}`)
163
+ }
164
+ return false
165
+ }
166
+
167
+ /**
168
+ * Bring the namespace's sandbox host to what a dev environment needs: the `zbox` service, its key and its API
169
+ * subdomain. The router routes the bare `Host` the proxy sends, so the host needs no domain. Each step decides by
170
+ * reading back, so a reconcile converges a host any earlier attempt left half done and changes nothing on a complete one.
171
+ */
172
+ export const ensureSandboxHost = async (input: ZeropsSandboxHostInput): Promise<ZeropsNamespaceSandboxHost> => {
173
+ const { target, signal } = input
174
+ assertSandboxHostAllowed(input.namespaceId, target)
175
+ const projectId = target.projectId
176
+ if (projectId === undefined) throw new Error('Zerops namespace has no project id')
177
+ const found = await findSandboxHost(input.api, projectId, signal)
178
+ if (target.sandboxHost !== undefined && found?.id !== target.sandboxHost.serviceId) {
179
+ throw new Error('Checkpointed namespace sandbox host service identity changed')
180
+ }
181
+ const service = found ?? await createSandboxHost(input, projectId)
182
+ // Before the start: a service of another type that holds the name is never touched.
183
+ validateService(service, projectId, SANDBOX_HOST_SERVICE_TYPE, false)
184
+ if (found?.status !== undefined && NOT_STARTED.has(found.status)) {
185
+ await waitFor(input, (await input.api.startService({ serviceId: found.id, signal })).id, 'sandbox host start')
186
+ }
187
+ await ensureSubdomainAccess({
188
+ api: input.api,
189
+ serviceId: service.id,
190
+ label: 'Zerops namespace sandbox host',
191
+ consequence: 'Control cannot reach its API',
192
+ ...(input.sleep === undefined ? {} : { sleep: input.sleep }),
193
+ signal,
194
+ })
195
+ const apiOrigin = await readApiOrigin(input, service.id)
196
+ const client = createZboxClient({
197
+ baseUrl: apiOrigin,
198
+ apiKey: input.sandboxKey,
199
+ ...(input.zboxFetch === undefined ? {} : { fetch: input.zboxFetch }),
200
+ })
201
+ const reached = await reachWorkspace(input, client)
202
+ const rekeyed = reached === 'unauthorized'
203
+ if (rekeyed) await rekey(input, client, service.id)
204
+ // A host whose API answers without a key is never recorded: one rekey, then a refusal.
205
+ if (!(await refusesWithoutKey(input, apiOrigin))) {
206
+ if (!rekeyed) await rekey(input, client, service.id)
207
+ if (!(await refusesWithoutKey(input, apiOrigin))) {
208
+ throw namespaceError(ZEROPS_SANDBOX_HOST_API_OPEN, `Zerops sandbox host ${service.id} answers its API without a key`, false)
209
+ }
210
+ }
211
+ return { serviceId: service.id, apiOrigin }
212
+ }
@@ -0,0 +1,113 @@
1
+ import type { ProviderNamespaceHost } from '@fabrika/provider-contract'
2
+ import { enableSubdomainAccessWhenHttp, readableContent, ZEROPS_SERVICE_NOT_HTTP, type ZeropsApi, ZeropsApiError } from '../api'
3
+ import { defaultSleep, type Sleeper } from '../collaborators'
4
+ import { ZEROPS_NAMESPACE_SUBDOMAIN_VARIABLE } from './constants'
5
+ import { namespaceError, ZEROPS_NAMESPACE_CANCELLED, ZEROPS_SUBDOMAIN_NOT_PUBLISHED } from './errors'
6
+
7
+ const POLL_INTERVAL_MS = 3000
8
+
9
+ /** The live enable finishes in under a second, but one run still read `false` once before flipping; ten reads is slack. */
10
+ const SUBDOMAIN_READBACK_ATTEMPTS = 10
11
+
12
+ /**
13
+ * One host per published HTTP port, out of the newline-separated URLs the platform writes.
14
+ *
15
+ * The form is `<hostname>-<hash>-<port>.<region>.zerops.app` (e.g. `proxy-2ec8-8080`). Read as URLs
16
+ * rather than split on `-`, so a hostname whose own first label ends in digits cannot be misread; a line
17
+ * that is not a URL, or whose first label carries no trailing port — the single portless line a proxy
18
+ * that has never deployed publishes — is skipped rather than guessed at.
19
+ */
20
+ export const parseZeropsSubdomainHosts = (value: string): ProviderNamespaceHost[] => {
21
+ const hosts: ProviderNamespaceHost[] = []
22
+ for (const line of value.split('\n')) {
23
+ const trimmed = line.trim()
24
+ if (trimmed === '') continue
25
+ let hostname: string
26
+ try {
27
+ hostname = new URL(trimmed).hostname
28
+ } catch {
29
+ continue
30
+ }
31
+ const port = /-(\d+)$/.exec(hostname.split('.')[0] ?? '')?.[1]
32
+ if (port === undefined) continue
33
+ hosts.push({ host: hostname, port: Number.parseInt(port, 10) })
34
+ }
35
+ return hosts.sort((left, right) => left.port - right.port)
36
+ }
37
+
38
+ /** The hosts a service publishes, off the platform-owned `zeropsSubdomain` variable; none while it names none. */
39
+ export const readSubdomainHosts = async (
40
+ api: Pick<ZeropsApi, 'listServiceEnv'>,
41
+ serviceId: string,
42
+ signal: AbortSignal,
43
+ ): Promise<ProviderNamespaceHost[]> => {
44
+ const variables = await api.listServiceEnv({ serviceId, signal })
45
+ const subdomains = readableContent(variables.find((variable) => variable.key === ZEROPS_NAMESPACE_SUBDOMAIN_VARIABLE))
46
+ return subdomains === undefined ? [] : parseZeropsSubdomainHosts(subdomains)
47
+ }
48
+
49
+ export interface SubdomainAccessInput {
50
+ readonly api: Pick<ZeropsApi, 'getService' | 'enableSubdomainAccess'>
51
+ readonly serviceId: string
52
+ /** Names the service in a refusal, e.g. `Zerops namespace proxy`. */
53
+ readonly label: string
54
+ /** What is missing when the subdomain stays off, e.g. `the namespace has no public entry point`. */
55
+ readonly consequence: string
56
+ readonly sleep?: Sleeper
57
+ readonly signal: AbortSignal
58
+ }
59
+
60
+ /**
61
+ * Publish a service on its `*.zerops.app` subdomain — the ONE thing the import document cannot do.
62
+ *
63
+ * `enableSubdomainAccess: true` is accepted by the import and then silently dropped, on a service the
64
+ * document CREATES as much as on one `override` leaves alone; a service imported with it reads back
65
+ * `subdomainAccess: false` for ever. The subdomain is established by
66
+ * `PUT /service-stack/{id}/enable-subdomain-access` and by nothing else, and that call needs a DEPLOYED
67
+ * HTTP port.
68
+ *
69
+ * It runs on RECONCILE too, so a subdomain someone turned off in the GUI comes back, and it either
70
+ * observes `subdomainAccess === true` or throws naming what is missing.
71
+ *
72
+ * The decision is the READ-BACK, never the call returning. On an already-published service the platform
73
+ * answers 2xx and then fails the process it handed back — live-verified — so a 2xx proves nothing.
74
+ *
75
+ * The HTTP ports lag the service's ACTIVE version, so `serviceStackIsNotHttp` is retried for a bounded
76
+ * window (`enableSubdomainAccessWhenHttp`) before it fails the namespace.
77
+ */
78
+ export const ensureSubdomainAccess = async (input: SubdomainAccessInput): Promise<void> => {
79
+ const { api, serviceId, signal } = input
80
+ const sleep = input.sleep ?? defaultSleep
81
+ const published = async (): Promise<boolean> => (await api.getService({ serviceId, signal })).subdomainAccess === true
82
+ if (await published()) {
83
+ return
84
+ }
85
+ try {
86
+ await enableSubdomainAccessWhenHttp({ api, serviceId, sleep, signal })
87
+ } catch (error) {
88
+ if (error instanceof ZeropsApiError && error.code === ZEROPS_SERVICE_NOT_HTTP) {
89
+ throw namespaceError(
90
+ ZEROPS_SERVICE_NOT_HTTP,
91
+ `${input.label} ${serviceId} cannot be published on a zerops.app subdomain: it still exposes no deployed HTTP port (${ZEROPS_SERVICE_NOT_HTTP}) minutes after its deploy`,
92
+ false,
93
+ )
94
+ }
95
+ throw error
96
+ }
97
+ for (let attempt = 0;; attempt += 1) {
98
+ if (signal.aborted) {
99
+ throw namespaceError(ZEROPS_NAMESPACE_CANCELLED, 'Zerops namespace provisioning was cancelled', true)
100
+ }
101
+ if (await published()) {
102
+ return
103
+ }
104
+ if (attempt >= SUBDOMAIN_READBACK_ATTEMPTS) {
105
+ throw namespaceError(
106
+ ZEROPS_SUBDOMAIN_NOT_PUBLISHED,
107
+ `${input.label} ${serviceId} accepted enable-subdomain-access but still reads subdomainAccess: false — ${input.consequence}`,
108
+ true,
109
+ )
110
+ }
111
+ await sleep(POLL_INTERVAL_MS, signal)
112
+ }
113
+ }
@@ -57,7 +57,7 @@ export const projectMarker = (namespace: ProviderDeploymentNamespace): string =>
57
57
  // Imports provision services only. The reserved upload-backed build selects the proxy setup.
58
58
  //
59
59
  // `enableSubdomainAccess` is a DECLARATION here and not a mechanism: the platform accepts it and drops it,
60
- // including on the service this document creates. `ensureSubdomainAccess` below is what establishes the
60
+ // including on the service this document creates. `ensureSubdomainAccess` (`subdomain.ts`) is what establishes the
61
61
  // subdomain, after the proxy's first deploy. Written anyway because it is what ADR-0022's
62
62
  // `assertOnlyPublicService` reads to prove no other service is claimed public.
63
63
  const proxyService = (publicAccess: ZeropsNamespacePublicAccess): ZeropsServiceSpec => ({
@@ -5,6 +5,7 @@ import type { ZeropsArtifactSourceDescriptor } from '../manifest'
5
5
  import type { ZeropsSourceRepository } from '../source'
6
6
  import type { ZeropsSourcePort } from '../source/port'
7
7
  import type { ZeropsSourceTarget } from '../types'
8
+ import type { ZboxFetch } from '../zbox'
8
9
 
9
10
  export type ZeropsNamespacePublicAccess = 'custom-domain' | 'zerops-subdomain'
10
11
 
@@ -60,9 +61,17 @@ export interface ZeropsNamespaceTarget {
60
61
  readonly proxyAppVersionId?: string
61
62
  /** The hosts the published proxy answers on, recorded once so a namespace read needs no platform call. */
62
63
  readonly proxyHosts?: readonly ProviderNamespaceHost[]
64
+ /** The namespace's dev sandbox host, recorded once provisioned; absent while no dev environment uses the namespace. */
65
+ readonly sandboxHost?: ZeropsNamespaceSandboxHost
63
66
  readonly ready?: boolean
64
67
  }
65
68
 
69
+ export interface ZeropsNamespaceSandboxHost {
70
+ readonly serviceId: string
71
+ /** The Box API origin: the service's public subdomain for `SANDBOX_HOST_API_PORT`. */
72
+ readonly apiOrigin: string
73
+ }
74
+
66
75
  export type ZeropsNamespacePolicy = Omit<ZeropsNamespaceTarget, 'proxySource'>
67
76
 
68
77
  export interface NormalizedZeropsNamespaceTarget extends ZeropsNamespaceTarget {
@@ -81,7 +90,11 @@ export interface ZeropsNamespaceOptions {
81
90
  readonly iamUrl: string
82
91
  /** Same credential IAM receives as `FABRIKA_IAM_PROXY_KEY`. */
83
92
  readonly iamKey: string
93
+ /** The installation's own project, which no namespace may create into or adopt. Absent until `platform deploy` writes it. */
94
+ readonly installationProjectId?: string
84
95
  readonly api: ZeropsApi
96
+ /** The transport of the sandbox host's Box API; absent, the global `fetch`. */
97
+ readonly zboxFetch?: ZboxFetch
85
98
  readonly sleep?: Sleeper
86
99
  }
87
100
 
@@ -45,6 +45,7 @@ const FIXED_FIELDS: { readonly [K in FixedField]: (target: ZeropsNamespaceTarget
45
45
  proxyBaselineSequence: (target) => target.proxyBaselineSequence,
46
46
  proxyAppVersionId: (target) => target.proxyAppVersionId,
47
47
  proxyHosts: (target) => target.proxyHosts,
48
+ sandboxHost: (target) => target.sandboxHost,
48
49
  ready: (target) => target.ready,
49
50
  }
50
51
 
@@ -0,0 +1,152 @@
1
+ // `fabrika namespace` on Zerops: the provider options, the plan, and the namespace each command hands Control. The
2
+ // `fabrika` command holds Control's origin and credential, and prints the result.
3
+
4
+ import type { JsonValue, ProviderDeploymentNamespace, ProviderNamespacePlan } from '@fabrika/provider-contract'
5
+ import type { NamespaceCli, NamespaceCommandContext, NamespaceCommandResult } from '@fabrika/provider-contract/app-cli'
6
+ import { parseZeropsCliArgs, type ZeropsCliArgs } from './cli-args'
7
+ import {
8
+ createZeropsNamespaceOperator,
9
+ decodeZeropsNamespaceProxySource,
10
+ verifyZeropsNamespaceProxySource,
11
+ zeropsNamespaceTargetCodec,
12
+ } from './namespace'
13
+ import type { ZeropsNamespacePostgres } from './namespace'
14
+ import { postgresSchema } from './namespace/codec'
15
+
16
+ const NAMESPACE_USAGE = `fabrika namespace — Zerops deployment namespaces
17
+
18
+ Usage:
19
+ fabrika namespace plan --provider=zerops --id=<id> --env=<env> --preset=<cheap|mid|full> [namespace options]
20
+ fabrika namespace create --provider=zerops --id=<id> --env=<env> --preset=<cheap|mid|full> [namespace options] [--control-url=<url>]
21
+ fabrika namespace adopt --provider=zerops --id=<id> --env=<env> --preset=<cheap|mid|full> --project-id=<id> [namespace options] [--control-url=<url>]
22
+ fabrika namespace reconcile --provider=zerops --id=<id> [--control-url=<url>]
23
+
24
+ Options:
25
+ --id=<id> Namespace id.
26
+ --env=<env> Environment.
27
+ --preset=<cheap|mid|full> Provider-owned namespace preset.
28
+ --exclusive-app=<id> App reserved by a full namespace.
29
+ --project-id=<id> Existing Zerops project id for adoption.
30
+ --project-name=<name> Zerops project name (create: default fabrika-<env>-<id>;
31
+ adopt: the existing project's name, default the namespace id).
32
+ --core-package=<tier> LIGHT or SERIOUS.
33
+ --public-access=<mode> custom-domain or zerops-subdomain.
34
+ --postgres-type=<type> Cheap-tier PostgreSQL type.
35
+ --postgres-profile=<profile> Cheap-tier PostgreSQL profile.
36
+ --control-url=<url> Control origin; or FABRIKA_CONTROL_URL.
37
+ --json Print the result as JSON instead of rows.
38
+ -h, --help Show this help.
39
+
40
+ \`plan\` prints one \`<path>\\t<value>\` row per field of the plan, keyed by its path in --json; a multi-line
41
+ value such as the proxy's descriptor file is shown by size only. The other commands print one
42
+ \`<id>\\t<env>\\t<state>\\t<exclusive app>\` row.
43
+
44
+ Mutating namespace commands read the Bearer credential from FABRIKA_CONTROL_TOKEN.
45
+ Plan/create/adopt require FABRIKA_ZEROPS_PROXY_SOURCE_JSON:
46
+ {"repository":{"owner":"...","name":"..."},"commitSha":"...","descriptor":{"path":"zerops.yaml","contents":"...","sha256":"..."}}
47
+ Reconcile uses the persisted namespace source.
48
+ `
49
+
50
+ const required = (value: string | undefined, label: string): string => {
51
+ if (value === undefined || value.trim() === '') {
52
+ throw new Error(`${label} is required`)
53
+ }
54
+ return value.trim()
55
+ }
56
+
57
+ const postgres = (args: ZeropsCliArgs): ZeropsNamespacePostgres | undefined => {
58
+ const type = args.postgresType
59
+ const profile = args.postgresProfile
60
+ if (type === undefined && profile === undefined) return undefined
61
+ if (type === undefined) {
62
+ throw new Error('--postgres-type is required with --postgres-profile')
63
+ }
64
+ const result = postgresSchema.safeParse({ type, profile })
65
+ if (result.success) return result.data
66
+ if (result.error.issues[0]?.path[0] === 'type') throw new Error('--postgres-type must be postgresql:ha@18 or postgresql:single@18')
67
+ throw new Error(`--postgres-profile ${profile} is not supported by ${type}`)
68
+ }
69
+
70
+ const planOptions = (args: ZeropsCliArgs): { [key: string]: JsonValue } | undefined => {
71
+ const values: { [key: string]: JsonValue } = {}
72
+ if (args.projectName !== undefined) values['projectName'] = required(args.projectName, '--project-name')
73
+ if (args.corePackage !== undefined) values['corePackage'] = required(args.corePackage, '--core-package')
74
+ if (args.publicAccess !== undefined) values['publicAccess'] = required(args.publicAccess, '--public-access')
75
+ const database = postgres(args)
76
+ if (database !== undefined) {
77
+ values['postgres'] = database.profile === undefined ? { type: database.type } : { type: database.type, profile: database.profile }
78
+ }
79
+ return Object.keys(values).length === 0 ? undefined : values
80
+ }
81
+
82
+ const namespacePlan = async (
83
+ args: ZeropsCliArgs,
84
+ source: Readonly<Record<string, string | undefined>>,
85
+ ): Promise<ProviderNamespacePlan> => {
86
+ // `FABRIKA_ZEROPS_*` because Zerops reserves the bare `ZEROPS_` prefix and refuses to store a custom
87
+ // variable using it (`userDataZeropsPrefixForbidden`).
88
+ const serialized = required(source['FABRIKA_ZEROPS_PROXY_SOURCE_JSON'], 'FABRIKA_ZEROPS_PROXY_SOURCE_JSON')
89
+ let value: unknown
90
+ try {
91
+ value = JSON.parse(serialized)
92
+ } catch {
93
+ throw new Error('FABRIKA_ZEROPS_PROXY_SOURCE_JSON must contain valid JSON')
94
+ }
95
+ const proxySource = decodeZeropsNamespaceProxySource(value)
96
+ await verifyZeropsNamespaceProxySource(proxySource)
97
+ const operator = createZeropsNamespaceOperator({ proxySource })
98
+ const options = planOptions(args)
99
+ return operator.plan({
100
+ id: required(args.namespaceId, '--id'),
101
+ env: required(args.env, '--env'),
102
+ preset: required(args.preset, '--preset'),
103
+ ...(args.exclusiveAppId === undefined ? {} : { exclusiveAppId: required(args.exclusiveAppId, '--exclusive-app') }),
104
+ ...(options === undefined ? {} : { options }),
105
+ })
106
+ }
107
+
108
+ /** One namespace command. Every input is validated before `context.control()` is read. */
109
+ const runZeropsNamespaceCommand = async (
110
+ subcommand: string,
111
+ argv: readonly string[],
112
+ context: NamespaceCommandContext,
113
+ ): Promise<NamespaceCommandResult> => {
114
+ const args = parseZeropsCliArgs(['namespace', subcommand, ...argv])
115
+ if (subcommand === 'plan') {
116
+ return { plan: await namespacePlan(args, context.source) }
117
+ }
118
+ if (subcommand === 'reconcile') {
119
+ const id = required(args.namespaceId, '--id')
120
+ return { namespace: await context.control().reconcile(id) }
121
+ }
122
+ if (subcommand !== 'create' && subcommand !== 'adopt') {
123
+ throw new Error(`Unknown namespace command: ${subcommand}`)
124
+ }
125
+
126
+ const planned = await namespacePlan(args, context.source)
127
+ const control = context.control()
128
+ if (subcommand === 'create') {
129
+ return { namespace: await control.create(planned.namespace) }
130
+ }
131
+
132
+ const projectId = required(args.projectId, '--project-id')
133
+ const decoded = zeropsNamespaceTargetCodec.decode(planned.namespace.target.payload)
134
+ const namespace: ProviderDeploymentNamespace = {
135
+ ...planned.namespace,
136
+ target: {
137
+ provider: 'zerops',
138
+ version: zeropsNamespaceTargetCodec.version,
139
+ payload: zeropsNamespaceTargetCodec.encode({
140
+ ...decoded,
141
+ // An adopted project keeps its own name, so the plan's default for a created one does not apply.
142
+ projectName: args.projectName ?? planned.namespace.id,
143
+ managed: false,
144
+ projectId,
145
+ ready: false,
146
+ }),
147
+ },
148
+ }
149
+ return { namespace: await control.adopt(namespace) }
150
+ }
151
+
152
+ export const zeropsNamespaceCli: NamespaceCli = { usage: NAMESPACE_USAGE, run: runZeropsNamespaceCommand }
@@ -0,0 +1,90 @@
1
+ // `fabrika app build` refuses an application configuration that writes a credential where everyone can read it.
2
+ //
3
+ // Every `envVariables` value a Zerops application authors (in any setup of its `zerops.yaml`; the compiled import of
4
+ // `fabrika.config.ts` is checked the same way, though its types offer none today) becomes a READABLE service variable,
5
+ // read by every member of the project, and sits in the repository in clear. A `run.routing.headers` value is sent to every visitor. A credential belongs in `pipeline.secrets`, set with
6
+ // `fabrika control apps secrets put`, which Zerops stores sensitive. The check runs at build only, never when a stored
7
+ // manifest is decoded: an application meets it when it raises its own pin, as with any framework API change.
8
+ //
9
+ // The heuristic errs towards refusing, so `target.notSecret` names the variables and headers the author has checked.
10
+
11
+ import type { JsonValue } from '@fabrika/provider-contract'
12
+ import { plainCredentialFinding } from '@fabrika/provider-contract'
13
+
14
+ /** One authored value that looks like a credential: where it is, and why. Never the value. */
15
+ interface AuthoredPlainCredential {
16
+ readonly path: string
17
+ readonly name: string
18
+ readonly because: string
19
+ readonly header: boolean
20
+ }
21
+
22
+ const isMapping = (value: JsonValue | undefined): value is { readonly [key: string]: JsonValue } =>
23
+ typeof value === 'object' && value !== null && !Array.isArray(value)
24
+
25
+ /** Every `envVariables` entry and every `routing.headers[].values` entry of a document, at any depth. */
26
+ const authoredPlainCredentials = (document: JsonValue, root: string, notSecret: ReadonlySet<string>): AuthoredPlainCredential[] => {
27
+ const found: AuthoredPlainCredential[] = []
28
+ const check = (path: string, name: string, value: JsonValue, header: boolean): void => {
29
+ // A header name is case-insensitive, as HTTP has it; a variable name is exact.
30
+ const listed = header ? [...notSecret].some((entry) => entry.toLowerCase() === name.toLowerCase()) : notSecret.has(name)
31
+ if (typeof value !== 'string' || listed) return
32
+ const finding = plainCredentialFinding(name, value)
33
+ if (finding !== null) found.push({ path, name, because: finding.because, header })
34
+ }
35
+ const visit = (value: JsonValue, path: string): void => {
36
+ if (Array.isArray(value)) {
37
+ value.forEach((item, index) => visit(item, `${path}[${index}]`))
38
+ return
39
+ }
40
+ if (!isMapping(value)) return
41
+ for (const [key, item] of Object.entries(value)) {
42
+ const at = `${path}.${key}`
43
+ if (key === 'envVariables' && isMapping(item)) {
44
+ for (const [name, text] of Object.entries(item)) check(`${at}.${name}`, name, text, false)
45
+ continue
46
+ }
47
+ if (key === 'routing' && isMapping(item) && Array.isArray(item['headers'])) {
48
+ item['headers'].forEach((rule, index) => {
49
+ const values = isMapping(rule) ? rule['values'] : undefined
50
+ if (!isMapping(values)) return
51
+ for (const [name, text] of Object.entries(values)) check(`${at}.headers[${index}].values.${name}`, name, text, true)
52
+ })
53
+ }
54
+ visit(item, at)
55
+ }
56
+ }
57
+ visit(document, root)
58
+ return found
59
+ }
60
+
61
+ /**
62
+ * Refuse every authored plain value that looks like a credential, naming each by its path and reason, never by value.
63
+ *
64
+ * `importDocument` is the compiled import of `fabrika.config.ts`; `descriptor` the parsed `zerops.yaml`, every setup.
65
+ */
66
+ export function assertNoAuthoredPlainCredential(
67
+ importDocument: JsonValue,
68
+ descriptor: JsonValue,
69
+ notSecret: readonly string[],
70
+ ): void {
71
+ const allowed = new Set(notSecret)
72
+ const found = [
73
+ ...authoredPlainCredentials(importDocument, 'fabrika.config.ts', allowed),
74
+ ...authoredPlainCredentials(descriptor, 'zerops.yaml', allowed),
75
+ ]
76
+ if (found.length === 0) return
77
+ const lines = found.map((entry) => ` ${entry.path}: ${entry.because}`)
78
+ const remedies = [
79
+ found.some((entry) => !entry.header)
80
+ ? 'An `envVariables` value is a readable service variable, which every member of the Zerops project can read, and it '
81
+ + 'sits in the repository in clear. Declare a credential in `pipeline.secrets` instead and set it with '
82
+ + '`fabrika control apps secrets put --app=<id> --name=<NAME>` (the value on stdin); Zerops stores it sensitive.'
83
+ : '',
84
+ found.some((entry) => entry.header)
85
+ ? 'A `routing.headers` value is sent to every visitor. A credential has no place there.'
86
+ : '',
87
+ 'A value that is not a credential: list its variable or header name in `target.notSecret` of fabrika.config.ts.',
88
+ ].filter((line) => line !== '')
89
+ throw new Error(['fabrika app build: plain configuration that looks like a credential:', ...lines, ...remedies].join('\n'))
90
+ }
package/src/plan.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { type FabrikaManifest, manifestServiceHostnames } from './manifest'
2
- import type { ZeropsRuntimeTarget } from './types'
3
2
 
4
3
  export type ZeropsStepKind =
5
4
  | 'apply-import'
@@ -11,7 +10,6 @@ export type ZeropsStepKind =
11
10
  | 'upload-source'
12
11
  | 'trigger-build'
13
12
  | 'await-version'
14
- | 'reconcile-schema'
15
13
 
16
14
  export interface ZeropsStep {
17
15
  readonly id: string
@@ -30,7 +28,7 @@ export const resolveDeployHostname = (manifest: FabrikaManifest): string => {
30
28
  }
31
29
 
32
30
  /** Build the provider-owned deploy order without touching the platform. */
33
- export const buildZeropsPlan = (manifest: FabrikaManifest, target: ZeropsRuntimeTarget): readonly ZeropsStep[] => {
31
+ export const buildZeropsPlan = (manifest: FabrikaManifest): readonly ZeropsStep[] => {
34
32
  const serviceHostnames = manifestServiceHostnames(manifest)
35
33
  const steps: ZeropsStep[] = []
36
34
 
@@ -59,9 +57,6 @@ export const buildZeropsPlan = (manifest: FabrikaManifest, target: ZeropsRuntime
59
57
  steps.push({ id: 'upload-source', kind: 'upload-source', description: 'Upload the resolved repository snapshot' })
60
58
  steps.push({ id: 'trigger-build', kind: 'trigger-build', description: 'Trigger the Zerops build+deploy pipeline' })
61
59
  steps.push({ id: 'await-version', kind: 'await-version', description: 'Await the Zerops pipeline and relay its build log' })
62
- if (manifest.app.schema !== undefined && target.propustkaUrl !== undefined) {
63
- steps.push({ id: 'reconcile-schema', kind: 'reconcile-schema', description: 'Reconcile authz schema into IAM' })
64
- }
65
60
 
66
61
  return steps
67
62
  }