@zabaca/zbc 0.11.0 → 0.13.0

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 (74) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/package.json +2 -1
  3. package/templates/apps/inbox/package.json +1 -1
  4. package/templates/apps/walgit/CONTEXT.md +135 -0
  5. package/templates/apps/walgit/Dockerfile +40 -18
  6. package/templates/apps/walgit/README.md +518 -55
  7. package/templates/apps/walgit/e2e/README.md +100 -6
  8. package/templates/apps/walgit/e2e/harness.ts +262 -1
  9. package/templates/apps/walgit/e2e/live.ts +588 -0
  10. package/templates/apps/walgit/e2e/scenarios.ts +367 -5
  11. package/templates/apps/walgit/e2e/suite.ts +5 -5
  12. package/templates/apps/walgit/examples/watch.ts +209 -0
  13. package/templates/apps/walgit/package.json +12 -3
  14. package/templates/apps/walgit/registry.json +6 -11
  15. package/templates/apps/walgit/shared/capabilities.ts +189 -0
  16. package/templates/apps/walgit/shared/container-env.ts +114 -0
  17. package/templates/apps/walgit/shared/credentials.ts +81 -0
  18. package/templates/apps/walgit/shared/events.ts +277 -0
  19. package/templates/apps/walgit/shared/landing.ts +1241 -0
  20. package/templates/apps/walgit/shared/llms.ts +463 -0
  21. package/templates/apps/walgit/shared/outbox.ts +266 -0
  22. package/templates/apps/walgit/shared/policy.ts +59 -0
  23. package/templates/apps/walgit/shared/protocol.ts +197 -0
  24. package/templates/apps/walgit/shared/provenance.ts +154 -0
  25. package/templates/apps/walgit/shared/ref-cache.ts +181 -0
  26. package/templates/apps/walgit/shared/telemetry.ts +219 -0
  27. package/templates/apps/walgit/src/announce-main.ts +37 -0
  28. package/templates/apps/walgit/src/announce.ts +98 -0
  29. package/templates/apps/walgit/src/append-only.ts +112 -0
  30. package/templates/apps/walgit/src/cache.ts +172 -0
  31. package/templates/apps/walgit/src/cli.ts +493 -0
  32. package/templates/apps/walgit/src/compact.ts +25 -23
  33. package/templates/apps/walgit/src/delete-repo.ts +237 -0
  34. package/templates/apps/walgit/src/expire.ts +248 -0
  35. package/templates/apps/walgit/src/gc.ts +8 -16
  36. package/templates/apps/walgit/src/git-backend.ts +29 -0
  37. package/templates/apps/walgit/src/git.ts +78 -0
  38. package/templates/apps/walgit/src/hook-main.ts +259 -17
  39. package/templates/apps/walgit/src/hooks.ts +4 -3
  40. package/templates/apps/walgit/src/http.ts +237 -45
  41. package/templates/apps/walgit/src/instructions.ts +240 -0
  42. package/templates/apps/walgit/src/keys.ts +126 -0
  43. package/templates/apps/walgit/src/limits.ts +158 -0
  44. package/templates/apps/walgit/src/materialize.bench.ts +10 -10
  45. package/templates/apps/walgit/src/materialize.ts +48 -40
  46. package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
  47. package/templates/apps/walgit/src/orphans.ts +2 -5
  48. package/templates/apps/walgit/src/pending.ts +201 -0
  49. package/templates/apps/walgit/src/push-cert.ts +254 -0
  50. package/templates/apps/walgit/src/push.ts +233 -46
  51. package/templates/apps/walgit/src/reconcile.ts +5 -8
  52. package/templates/apps/walgit/src/repo.ts +22 -77
  53. package/templates/apps/walgit/src/server.ts +148 -26
  54. package/templates/apps/walgit/src/signers.ts +577 -0
  55. package/templates/apps/walgit/src/store-env.ts +5 -4
  56. package/templates/apps/walgit/src/store.ts +47 -24
  57. package/templates/apps/walgit/src/usage.ts +404 -0
  58. package/templates/apps/walgit/src/verify.ts +171 -0
  59. package/templates/apps/walgit/src/wal-index.ts +189 -11
  60. package/templates/apps/walgit/tsconfig.json +8 -2
  61. package/templates/apps/walgit/tsconfig.worker.json +24 -0
  62. package/templates/apps/walgit/worker/events-do.ts +259 -0
  63. package/templates/apps/walgit/worker/index.ts +572 -0
  64. package/templates/apps/walgit/wrangler.jsonc +95 -0
  65. package/templates/apps/warehouse/package.json +1 -1
  66. package/templates/infra/modules/cloudflare/index.ts +77 -6
  67. package/templates/infra/modules/cloudflare-access/index.ts +85 -14
  68. package/templates/infra/modules/fly/index.ts +150 -10
  69. package/templates/infra/modules/turso/index.ts +43 -3
  70. package/templates/infra/package.json +1 -1
  71. package/templates/apps/walgit/entrypoint.sh +0 -59
  72. package/templates/apps/walgit/fly.toml +0 -52
  73. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  74. package/templates/apps/walgit/sshd_config +0 -38
@@ -86,12 +86,30 @@ const buildSchema = z.object({
86
86
  cwd: z.string().optional(),
87
87
  })
88
88
 
89
+ /**
90
+ * The origin a route pattern answers on, for `deployUrl` when there is no
91
+ * workers.dev URL to report.
92
+ *
93
+ * Only a pattern whose host is a concrete hostname qualifies. A wildcard host
94
+ * (`*.example.com/*`) names a set rather than an address, and emitting
95
+ * `https://*.example.com` would hand a dependent a string that looks like a URL
96
+ * and resolves to nothing.
97
+ */
98
+ export function routeUrl(routes: string[]): string {
99
+ for (const route of routes) {
100
+ const host = route.split('/')[0]
101
+ if (host && !host.includes('*') && host.includes('.')) return `https://${host}`
102
+ }
103
+ return ''
104
+ }
105
+
89
106
  /**
90
107
  * A worker secret/var entry: a plain name (resolved from this environment's
91
108
  * secrets.yaml), a `{ name, value }` literal (vars that are per-instance
92
109
  * config rather than secrets — e.g. DEFAULT_FROM — so a generic wrangler.jsonc
93
- * needs no editing), or a `{ name, from, output }` reference into an imported
94
- * instance's outputs (`ctx.imports[from][output]`).
110
+ * needs no editing), a `{ name, from, output }` reference into an imported
111
+ * instance's outputs (`ctx.imports[from][output]`), or a `{ name, secret }`
112
+ * pair that exposes a secrets.yaml key under a different env var name.
95
113
  */
96
114
  const workerValueSchema = z.union([
97
115
  z.string(),
@@ -109,6 +127,21 @@ const workerValueSchema = z.union([
109
127
  /** Which output of that instance to read. */
110
128
  output: z.string(),
111
129
  }),
130
+ z.object({
131
+ /** Env var name inside the Worker. */
132
+ name: z.string(),
133
+ /**
134
+ * A key in this environment's secrets.yaml, exposed under `name`.
135
+ *
136
+ * The plain-string form already reads a secret, but it forces the Worker's
137
+ * env var to be spelled exactly like the secret. An app whose interface
138
+ * says `WALGIT_S3_ACCESS_KEY_ID` cannot then read a credential filed as
139
+ * `WAREHOUSE_R2_ACCESS_KEY_ID` — and the alternative is a second copy of
140
+ * the same credential under a second name, which is one more thing to
141
+ * forget when it rotates. Same form, same reason, as the `fly` module's.
142
+ */
143
+ secret: z.string(),
144
+ }),
112
145
  ])
113
146
 
114
147
  type WorkerValueEntry = z.infer<typeof workerValueSchema>
@@ -133,6 +166,16 @@ function resolveWorkerValue(
133
166
  return { name: entry.name, value: entry.value }
134
167
  }
135
168
 
169
+ if ('secret' in entry) {
170
+ const value = ctx.secrets[entry.secret]
171
+ if (!value) {
172
+ throw new Error(
173
+ `${fieldName} entry "${entry.name}" references secret "${entry.secret}", which is missing from this environment's secrets.yaml`,
174
+ )
175
+ }
176
+ return { name: entry.name, value }
177
+ }
178
+
136
179
  const instanceOutputs = ctx.imports[entry.from]
137
180
  if (instanceOutputs === undefined) {
138
181
  throw new Error(
@@ -333,8 +376,10 @@ export const cloudflareModule = defineModule({
333
376
  /**
334
377
  * Worker secrets to push after deploy. Each entry is either a plain name
335
378
  * — a key in this environment's secrets.yaml, becoming a Worker secret
336
- * binding of the same name (read at runtime as `env.<NAME>`) — or a
337
- * `{ name, from, output }` reference into an imported instance's outputs.
379
+ * binding of the same name (read at runtime as `env.<NAME>`) — a
380
+ * `{ name, secret }` pair exposing a secrets.yaml key under a different
381
+ * name, or a `{ name, from, output }` reference into an imported
382
+ * instance's outputs.
338
383
  * Pushed via `wrangler secret put` with the value piped through stdin.
339
384
  */
340
385
  workerSecrets: z.array(workerValueSchema).default([]),
@@ -380,6 +425,26 @@ export const cloudflareModule = defineModule({
380
425
  * `name` declared in wrangler.jsonc.
381
426
  */
382
427
  workerName: z.string().optional(),
428
+ /**
429
+ * Hostname patterns this worker answers, e.g. `zbc.zabaca.com/*`, emitted
430
+ * as `--route`. The DNS record for the hostname is NOT created here: it
431
+ * belongs to a `cloudflare-zone` instance, and this instance should import
432
+ * that one so the record exists before the route is claimed.
433
+ *
434
+ * It lives in instance config rather than wrangler.jsonc, and that is the
435
+ * whole point. Preview PRs deploy the SAME wrangler.jsonc under a
436
+ * per-PR `workerName`, so a route declared in the file would be claimed by
437
+ * every preview deploy too — and a Cloudflare route is unique per zone, so
438
+ * the most recently deployed PR would take production's traffic, silently
439
+ * and with no error anywhere. A preview instance omits `routes` and keeps
440
+ * its `*.workers.dev` URL.
441
+ *
442
+ * Deliberately a route, not a wrangler "custom domain": a custom domain
443
+ * has wrangler create its own managed DNS record, which the zone module
444
+ * would then read as undeclared drift, and the two would argue on every
445
+ * apply.
446
+ */
447
+ routes: z.array(z.string()).default([]),
383
448
  }),
384
449
  outputs: z.object({
385
450
  deployUrl: z.string(),
@@ -465,9 +530,10 @@ export const cloudflareModule = defineModule({
465
530
  if (config.wranglerEnv) deployArgs.push('--env', config.wranglerEnv)
466
531
  if (config.workerName) deployArgs.push('--name', config.workerName)
467
532
  if (config.immediateContainerRollout) deployArgs.push('--containers-rollout', 'immediate')
533
+ for (const route of config.routes) deployArgs.push('--route', route)
468
534
  for (const { name, value } of resolvedVars) deployArgs.push('--var', `${name}:${value}`)
469
535
  console.log(
470
- ` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}${resolvedR2.length ? ` [r2: ${resolvedR2.map((b) => `${b.binding}→${b.bucketName}`).join(', ')}]` : ''}`,
536
+ ` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${config.routes.length ? ` [routes: ${config.routes.join(', ')}]` : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}${resolvedR2.length ? ` [r2: ${resolvedR2.map((b) => `${b.binding}→${b.bucketName}`).join(', ')}]` : ''}`,
471
537
  )
472
538
  let out: string
473
539
  try {
@@ -485,8 +551,13 @@ export const cloudflareModule = defineModule({
485
551
  )
486
552
  }
487
553
  const workerName = deployedMatch[1]!
554
+ // A routed worker has no workers.dev URL to print: wrangler DISABLES the
555
+ // subdomain when routes are configured and `workers_dev` is not explicitly
556
+ // true, and prints the routes instead. Falling back to the first route
557
+ // keeps `deployUrl` meaning "where this worker answers" rather than going
558
+ // empty the moment an app gets a real hostname.
488
559
  const urlMatch = out.match(/https:\/\/[^\s"',]+\.workers\.dev[^\s"',]*/)
489
- const deployUrl = urlMatch?.[0] ?? ''
560
+ const deployUrl = urlMatch?.[0] ?? routeUrl(config.routes)
490
561
  console.log(` Deployed: ${deployUrl || '(URL not parsed — see wrangler output)'}`)
491
562
 
492
563
  // 4. Push Worker secrets (after deploy: the script must exist first).
@@ -206,7 +206,17 @@ const configSchema = z
206
206
  */
207
207
  serviceTokenPolicyName: z.string().min(1).optional(),
208
208
  /** Whether the application shows as a tile in the App Launcher. */
209
- appLauncherVisible: z.boolean().default(false),
209
+ /**
210
+ * Whether the application shows as a tile in the App Launcher.
211
+ *
212
+ * DEFAULTS TO TRUE, which is Cloudflare's own default and therefore what
213
+ * omitting the field has always meant. A PUT is a full replace, so "omit
214
+ * it" and "send the default" are the same act and there is no third option
215
+ * — which is why defaulting it to `false` (as this did until 2026-08-23)
216
+ * made the first apply of every migrating consumer a change to live state.
217
+ * An instance that wants the tile hidden says so.
218
+ */
219
+ appLauncherVisible: z.boolean().default(true),
210
220
  /**
211
221
  * Cloudflare's binding cookie. Off, matching Cloudflare's own default and
212
222
  * the module this replaces: a machine caller should never be handed one.
@@ -633,6 +643,70 @@ export function appBody(config: {
633
643
  }
634
644
  }
635
645
 
646
+ /**
647
+ * Which fields of the body disagree with the live application. Pure; exported
648
+ * for tests.
649
+ *
650
+ * ⚠️ EVERY KEY THE BODY CARRIES, and that is the whole point rather than a
651
+ * detail. Until 2026-08-23 this comparison was three hand-listed fields — name,
652
+ * domain, session duration — defended by a comment arguing that the module
653
+ * "declares more of the application than it can read back reliably", so a
654
+ * re-apply "reports honestly without silently accepting drift in a field nobody
655
+ * looked at".
656
+ *
657
+ * That rationale is sound and it covers the wrong case. It defends not
658
+ * comparing a field THE DASHBOARD might have changed. It says nothing about a
659
+ * field THIS MODULE writes from its own default on every single apply — which
660
+ * is not drift being accepted, it is a change being made and not reported. A
661
+ * correct-sounding rationale covering the wrong case is harder to spot than no
662
+ * rationale, and this one hid `app_launcher_visible` flipping a live
663
+ * application while the apply printed `unchanged`.
664
+ *
665
+ * So the answer to "compare it or stop writing it" is COMPARE IT, and the
666
+ * comparison is derived from the body rather than listed beside it: add a field
667
+ * to `appBody` and it is compared, with no second place to remember.
668
+ */
669
+ export function appDiffers(
670
+ desired: Record<string, unknown>,
671
+ live: Record<string, unknown>,
672
+ ): string[] {
673
+ return Object.keys(desired).filter((key) => {
674
+ const want = desired[key]
675
+ const have = live[key]
676
+ // The one field with an identity of its own: `https://Host/` and `host`
677
+ // are the same application, and reading them as different would make every
678
+ // apply a change.
679
+ if (key === 'domain') {
680
+ return normalizeDomain(String(want)) !== normalizeDomain(String(have ?? ''))
681
+ }
682
+ return JSON.stringify(want) !== JSON.stringify(have)
683
+ })
684
+ }
685
+
686
+ /**
687
+ * What the summary line says a person may sign in with. Pure; exported for
688
+ * tests.
689
+ *
690
+ * DECLARED AND UNDECLARED BOTH, because the question this answers is "can a
691
+ * person sign in", not "what did this instance declare". Reporting only the
692
+ * declared set meant that an instance declaring none — the recommended
693
+ * configuration when the organisation already offers what is needed, since
694
+ * declaring one converges nothing and needs write access over state every other
695
+ * application in the account shares — printed "nobody can sign in" three lines
696
+ * under its own report that two providers were offered and kept.
697
+ *
698
+ * The empty case still says nobody can, and that half is not incidental: an
699
+ * organisation really offering nothing must not be reassured by a fix aimed at
700
+ * a false alarm.
701
+ */
702
+ export function signInWith(providers: {
703
+ declared: readonly string[]
704
+ undeclared: readonly string[]
705
+ }): string {
706
+ const all = [...providers.declared, ...providers.undeclared]
707
+ return all.length > 0 ? all.join(', ') : '(nothing, so nobody can sign in)'
708
+ }
709
+
636
710
  /**
637
711
  * The application this instance converges, and how it was recognised.
638
712
  *
@@ -941,21 +1015,18 @@ export const cloudflareAccessModule = defineModule({
941
1015
  let app: CfApp
942
1016
  let appChanged: boolean
943
1017
  if (found) {
944
- // ALWAYS a PUT, even when the compared fields agree. This module declares
945
- // more of the application than it can read back reliably, and a converge
946
- // that skips the write leaves whatever the dashboard did to the fields it
947
- // does not compare. `changed` is computed from the compared subset
948
- // instead, so a re-apply reports honestly without silently accepting
949
- // drift in a field nobody looked at.
950
- appChanged =
951
- found.app.name !== config.name ||
952
- normalizeDomain(found.app.domain) !== domain ||
953
- (typeof found.app.session_duration === 'string' &&
954
- found.app.session_duration !== config.sessionDuration)
1018
+ // ALWAYS a PUT, even when everything agrees: a converge that skips the
1019
+ // write leaves whatever the dashboard did to the fields this module owns.
1020
+ // What it reports is now derived from the body it is about to send, so
1021
+ // every field it writes is a field it compares — see `appDiffers` for why
1022
+ // the previous three-field subset was worse than no comparison.
1023
+ const differing = appDiffers(body, found.app as unknown as Record<string, unknown>)
1024
+ appChanged = differing.length > 0
955
1025
  app = await cf<CfApp>(token, 'PUT', `${account}/access/apps/${found.app.id}`, body)
956
1026
  console.log(
957
1027
  ` Converged Access application "${config.name}" on ${domain} (${app.id}, matched by ` +
958
- `${found.by})`,
1028
+ `${found.by})` +
1029
+ (appChanged ? ` — changed ${differing.join(', ')}` : ''),
959
1030
  )
960
1031
  } else {
961
1032
  app = await cf<CfApp>(token, 'POST', `${account}/access/apps`, body)
@@ -1119,7 +1190,7 @@ export const cloudflareAccessModule = defineModule({
1119
1190
  if (app.aud) console.log(` audience ${app.aud}`)
1120
1191
  if (config.emails.length > 0) {
1121
1192
  console.log(
1122
- ` sign in with ${identityProviders.join(', ') || '(nothing, so nobody can sign in)'}`,
1193
+ ` sign in with ${signInWith({ declared: identityProviders, undeclared: undeclaredIdps })}`,
1123
1194
  )
1124
1195
  console.log(` admits ${config.emails.join(', ')}`)
1125
1196
  }
@@ -58,12 +58,27 @@ const flyValueSchema = z.union([
58
58
  /** Which output of that instance to read. */
59
59
  output: z.string(),
60
60
  }),
61
+ z.object({
62
+ /** Env var name inside the app. */
63
+ name: z.string(),
64
+ /**
65
+ * A key in this environment's secrets.yaml, exposed under `name`.
66
+ *
67
+ * The plain-string form already reads a secret, but it forces the app's
68
+ * env var to be spelled exactly like the secret. An app whose interface
69
+ * says `WALGIT_S3_ACCESS_KEY_ID` cannot then read a credential filed as
70
+ * `WAREHOUSE_R2_ACCESS_KEY_ID` — and the alternative is a second copy of
71
+ * the same credential under a second name, which is one more thing to
72
+ * forget when it rotates.
73
+ */
74
+ secret: z.string(),
75
+ }),
61
76
  ])
62
77
 
63
78
  type FlyValueEntry = z.infer<typeof flyValueSchema>
64
79
 
65
80
  /** Resolve a flySecrets entry to its `{ name, value }` pair. */
66
- function resolveFlyValue(
81
+ export function resolveFlyValue(
67
82
  entry: FlyValueEntry,
68
83
  ctx: { secrets: Record<string, string>; imports: Record<string, unknown> },
69
84
  fieldName: string,
@@ -82,6 +97,17 @@ function resolveFlyValue(
82
97
  return { name: entry.name, value: entry.value }
83
98
  }
84
99
 
100
+ if ('secret' in entry) {
101
+ const value = ctx.secrets[entry.secret]
102
+ if (!value) {
103
+ throw new Error(
104
+ `${fieldName} entry "${entry.name}" reads secret "${entry.secret}", ` +
105
+ "which is missing from this environment's secrets.yaml",
106
+ )
107
+ }
108
+ return { name: entry.name, value }
109
+ }
110
+
85
111
  const instanceOutputs = ctx.imports[entry.from]
86
112
  if (!instanceOutputs) {
87
113
  throw new Error(
@@ -128,6 +154,76 @@ function fly(
128
154
  /** Read `app = "name"` out of the package's fly.toml. The app name belongs to
129
155
  * the package's own topology file; `appName` in config only overrides it (the
130
156
  * per-PR preview case, mirroring the cloudflare module's `workerName`). */
157
+ /** Did `fly deploy` say, in its own words, that machines reached a good state?
158
+ *
159
+ * Exit 0 is not the signal — flyctl prints its build and then exits 0 on paths
160
+ * where nothing converged, which is what the caller's guard exists to catch.
161
+ * The vocabulary differs by path, and the guard originally knew only the
162
+ * first-launch half:
163
+ *
164
+ * launching a new machine -> "Finished launching new machines"
165
+ * a machine-less group -> "No machines in group"
166
+ * non-rolling update -> "update finished: success"
167
+ * ROLLING update -> "✔ Machine <id> is now in a good state"
168
+ *
169
+ * The last line is the one that was missing, and it is the line every deploy
170
+ * after the first prints. zbc-walgit was launched by hand, so CI's first run
171
+ * against it took the rolling path and the guard failed a deploy that had in
172
+ * fact converged (run 32881480843, 2026-08-25). A false red on a healthy
173
+ * deploy costs the guard its credibility as surely as a false green does.
174
+ *
175
+ * "reached stopped state" is NOT convergence and is deliberately not matched:
176
+ * flyctl prints it for an auto-stopped machine on its way to a good state, and
177
+ * also for one that stopped because it died. Only the good-state line settles it.
178
+ */
179
+ export function machinesConverged(out: string): boolean {
180
+ return /(update finished: success|Finished launching new machines|No machines? in group|Machine \w+ is now in a good state)/.test(
181
+ out,
182
+ )
183
+ }
184
+
185
+ /**
186
+ * Which of `wanted` has no certificate yet, given `fly certs list` output.
187
+ *
188
+ * Pure, and separated from apply because the cost of getting it wrong is
189
+ * asymmetric and invisible: `fly certs add` on a hostname that already has a
190
+ * certificate EXITS NON-ZERO, so a hostname wrongly judged absent fails the
191
+ * whole apply, while one wrongly judged present leaves the app serving a
192
+ * default certificate that every client rejects by name.
193
+ *
194
+ * Matching is on the first whitespace-delimited field of each line, never a
195
+ * substring: `git.zabaca.com` appears inside `www.git.zabaca.com`, and a
196
+ * substring test would skip a certificate that was never requested.
197
+ */
198
+ export function certsToRequest(listOutput: string, wanted: string[]): string[] {
199
+ const present = new Set(
200
+ listOutput
201
+ .split('\n')
202
+ .map((line) => line.trim().split(/\s+/)[0])
203
+ .filter(Boolean),
204
+ )
205
+ return wanted.filter((hostname) => !present.has(hostname))
206
+ }
207
+
208
+ /**
209
+ * Machines in the `app` process group, from `fly scale show` output.
210
+ *
211
+ * Returns undefined when the output cannot be read as a table — a flyctl
212
+ * version that reworded it, or a call that failed. Undefined means "do not
213
+ * scale", never "scale to zero": guessing a count from output this did not
214
+ * understand would destroy machines, and the safe direction when the evidence
215
+ * is unreadable is to leave the app alone and let the next apply try again.
216
+ */
217
+ export function machineCount(scaleShowOutput: string): number | undefined {
218
+ for (const line of scaleShowOutput.split('\n')) {
219
+ const cells = line.split('│').map((cell) => cell.trim())
220
+ if (cells.length < 2 || cells[0] !== 'app') continue
221
+ const count = Number(cells[1])
222
+ if (Number.isInteger(count) && count >= 0) return count
223
+ }
224
+ return undefined
225
+ }
226
+
131
227
  function appNameFromFlyToml(workdir: string): string | undefined {
132
228
  const tomlPath = path.join(workdir, 'fly.toml')
133
229
  if (!fs.existsSync(tomlPath)) return undefined
@@ -159,7 +255,9 @@ export const flyModule = defineModule({
159
255
  /**
160
256
  * App secrets, staged before deploy. Each entry is either a plain name (a
161
257
  * key in this environment's secrets.yaml), `{ name, value }` for a literal,
162
- * or `{ name, from, output }` to pull from an imported instance's outputs.
258
+ * `{ name, secret }` to expose a secrets.yaml key under a different env var
259
+ * name, or `{ name, from, output }` to pull from an imported instance's
260
+ * outputs.
163
261
  */
164
262
  flySecrets: z.array(flyValueSchema).default([]),
165
263
  /**
@@ -178,6 +276,16 @@ export const flyModule = defineModule({
178
276
  * for a builder machine to spin up.
179
277
  */
180
278
  localBuild: z.boolean().default(false),
279
+ /**
280
+ * Custom hostnames Fly should hold a TLS certificate for, e.g.
281
+ * `git.zabaca.com`. Each is requested once and left alone thereafter.
282
+ *
283
+ * The DNS record for the hostname must already point at this app, or Fly
284
+ * has nothing to validate against and the certificate sits pending — so
285
+ * the instance declaring a cert should `imports` whatever manages that
286
+ * record, to order the two within one apply.
287
+ */
288
+ certs: z.array(z.string()).default([]),
181
289
  /** Destroy+recreate the whole app on every apply (preview environments). */
182
290
  ephemeral: z.boolean().default(false),
183
291
  }),
@@ -235,7 +343,23 @@ export const flyModule = defineModule({
235
343
  fly(workdir, ['ips', 'allocate-v6', '-a', appName], env)
236
344
  }
237
345
 
238
- // 3. Optional local build. Inherit stdio so build output streams.
346
+ // 3. Custom hostname certificates. Requested before the deploy rather than
347
+ // after, because issuance is asynchronous on Fly's side and a deploy can
348
+ // take minutes — asking first lets validation run during it.
349
+ //
350
+ // `fly certs add` on a hostname that already has a certificate is an
351
+ // error, not a no-op, so this lists first and matches whole lines: a
352
+ // substring test would see `git.zabaca.com` inside `www.git.zabaca.com`
353
+ // and skip a certificate that was never requested.
354
+ if (config.certs.length > 0) {
355
+ const listed = fly(workdir, ['certs', 'list', '-a', appName], env).out
356
+ for (const hostname of certsToRequest(listed, config.certs)) {
357
+ console.log(` Requesting certificate for ${hostname}`)
358
+ fly(workdir, ['certs', 'add', hostname, '-a', appName], env)
359
+ }
360
+ }
361
+
362
+ // 4. Optional local build. Inherit stdio so build output streams.
239
363
  if (config.build) {
240
364
  const buildCwd = path.resolve(ctx.projectRoot, config.build.cwd ?? config.workdir)
241
365
  console.log(
@@ -244,11 +368,11 @@ export const flyModule = defineModule({
244
368
  execSync(config.build.command, { cwd: buildCwd, stdio: 'inherit', env })
245
369
  }
246
370
 
247
- // 4. Resolve every secret BEFORE staging so a bad reference fails fast,
371
+ // 5. Resolve every secret BEFORE staging so a bad reference fails fast,
248
372
  // without leaving a half-configured app. `resolveFlyValue` is pure.
249
373
  const resolved = config.flySecrets.map((entry) => resolveFlyValue(entry, ctx, 'flySecrets'))
250
374
 
251
- // 5. Stage secrets. `--stage` withholds the deployment that `fly secrets
375
+ // 6. Stage secrets. `--stage` withholds the deployment that `fly secrets
252
376
  // set` would otherwise trigger; step 6 picks them up. Values go on the
253
377
  // command line as NAME=VALUE — flyctl offers no stdin form — so they are
254
378
  // visible to a local process listing, though never logged here.
@@ -268,7 +392,7 @@ export const flyModule = defineModule({
268
392
  console.log(` Staged secrets: ${resolved.map((s) => s.name).join(', ')}`)
269
393
  }
270
394
 
271
- // 6. Deploy.
395
+ // 7. Deploy.
272
396
  const deployArgs = ['deploy', '-a', appName, '--yes']
273
397
  if (!config.highAvailability) deployArgs.push('--ha=false')
274
398
  if (config.localBuild) deployArgs.push('--local-only')
@@ -279,15 +403,13 @@ export const flyModule = defineModule({
279
403
 
280
404
  // Success-theater guard, same lesson as the cloudflare module: require a
281
405
  // confirmation that machines actually converged rather than trusting exit 0.
282
- if (
283
- !/(update finished: success|Finished launching new machines|No machines? in group)/.test(out)
284
- ) {
406
+ if (!machinesConverged(out)) {
285
407
  throw new Error(
286
408
  `fly deploy exited 0 but printed no machine-convergence confirmation:\n${out}`,
287
409
  )
288
410
  }
289
411
 
290
- // 7. Read the IPs back for outputs — dependents need the address, and after
412
+ // 8. Read the IPs back for outputs — dependents need the address, and after
291
413
  // step 2 it is whatever Fly actually holds, not what we asked for.
292
414
  const finalIps = fly(workdir, ['ips', 'list', '-a', appName], env)
293
415
  const v4 = finalIps.out.match(/\bv4\s*│\s*([0-9.]+)/)?.[1] ?? ''
@@ -295,6 +417,24 @@ export const flyModule = defineModule({
295
417
  const hostname = `${appName}.fly.dev`
296
418
  console.log(` Deployed: ${hostname}${v4 ? ` (${v4})` : ''}`)
297
419
 
420
+ // 9. Machine count. This is NOT what `--ha` on the deploy above does:
421
+ // flyctl's `--ha` provisions a spare only when it is FIRST launching an
422
+ // app, and a deploy to an app that already exists keeps whatever count
423
+ // it has. So `highAvailability: true` on a live app changed nothing and
424
+ // said nothing — the deploy reported success either way, which is the
425
+ // failure this module already learned to distrust once.
426
+ //
427
+ // `fly scale count` is the converging form, and it runs AFTER the deploy
428
+ // so a machine created here starts from the image just released rather
429
+ // than the previous one.
430
+ const wanted = config.highAvailability ? 2 : 1
431
+ const shown = fly(workdir, ['scale', 'show', '-a', appName], env, { allowFailure: true })
432
+ const current = machineCount(shown.out)
433
+ if (current !== undefined && current !== wanted) {
434
+ console.log(` Scaling machines: ${current} → ${wanted}`)
435
+ fly(workdir, ['scale', 'count', String(wanted), '-a', appName, '--yes'], env)
436
+ }
437
+
298
438
  return { appName, hostname, ipv4: v4, ipv6: v6 }
299
439
  },
300
440
  async destroy(config, ctx) {
@@ -50,6 +50,45 @@ export async function waitUntilReachable(
50
50
  }
51
51
  }
52
52
 
53
+ /**
54
+ * `@libsql/client` and `drizzle-orm` are turso's OPTIONAL dependencies, and this
55
+ * is the seam that keeps them optional.
56
+ *
57
+ * Only the `migrationsDir` branch of `apply` touches them, so `registry.json`
58
+ * lists them under `optionalDependencies` and `zbc add turso` does not pull
59
+ * drizzle into a repository that has no migrations to run. A plain
60
+ * `await import('@libsql/client')` contradicts that: it is a module TypeScript
61
+ * must resolve at compile time, so every consumer that took the module at its
62
+ * word and skipped them compiles three unresolvable imports — `modules/` is the
63
+ * tree they vendor, so the errors are theirs, not just ours.
64
+ *
65
+ * Going through a specifier the compiler cannot fold to a literal moves that
66
+ * resolution to runtime, where the branch has already established the package is
67
+ * installed. The types below are the price: the surface used is written out here
68
+ * rather than read off the real package, so it has to be kept honest by hand.
69
+ * Both are small and neither is on a version we pin.
70
+ */
71
+ const importOptional = <T>(specifier: string): Promise<T> => import(specifier) as Promise<T>
72
+
73
+ /** The one function this module calls in `@libsql/client`, and the two it calls on the result. */
74
+ interface LibsqlClientModule {
75
+ createClient(config: { url: string; authToken?: string }): LibsqlClient
76
+ }
77
+
78
+ interface LibsqlClient {
79
+ execute(sql: string): Promise<unknown>
80
+ close(): void
81
+ }
82
+
83
+ /** The handle is opaque here — it is created and then handed straight to `migrate`. */
84
+ interface DrizzleLibsqlModule {
85
+ drizzle(client: LibsqlClient): unknown
86
+ }
87
+
88
+ interface DrizzleMigratorModule {
89
+ migrate(db: unknown, config: { migrationsFolder: string }): Promise<void>
90
+ }
91
+
53
92
  export const tursoModule = defineModule({
54
93
  name: 'turso',
55
94
  configSchema: z.object({
@@ -144,9 +183,10 @@ export const tursoModule = defineModule({
144
183
 
145
184
  if (config.migrationsDir) {
146
185
  const { resolve } = await import('node:path')
147
- const { createClient: createLibsqlClient } = await import('@libsql/client')
148
- const { drizzle } = await import('drizzle-orm/libsql')
149
- const { migrate } = await import('drizzle-orm/libsql/migrator')
186
+ const { createClient: createLibsqlClient } =
187
+ await importOptional<LibsqlClientModule>('@libsql/client')
188
+ const { drizzle } = await importOptional<DrizzleLibsqlModule>('drizzle-orm/libsql')
189
+ const { migrate } = await importOptional<DrizzleMigratorModule>('drizzle-orm/libsql/migrator')
150
190
 
151
191
  const folder = resolve(ctx.projectRoot, config.migrationsDir)
152
192
  const migrationClient = createLibsqlClient({
@@ -12,7 +12,7 @@
12
12
  "devDependencies": {
13
13
  "@types/bun": "^1.3.14",
14
14
  "@types/node": "^25.6.0",
15
- "typescript": "^5.7.0"
15
+ "typescript": "^7.0.2"
16
16
  },
17
17
  "scripts": {
18
18
  "test": "bun test",
@@ -1,59 +0,0 @@
1
- #!/bin/sh
2
- # walgit boot: materialize SSH identity from secrets, then supervise sshd and
3
- # the smart-HTTP server as one unit.
4
- set -eu
5
-
6
- REPOS_DIR="${WALGIT_REPOS_DIR:-/srv/walgit/repos}"
7
- mkdir -p "$REPOS_DIR"
8
- chown git:git "$REPOS_DIR"
9
-
10
- # The host key comes from a secret because the container filesystem does not
11
- # survive a machine stop. A generated-on-boot key would change on every
12
- # autostart and every client would see the SSH man-in-the-middle warning — on a
13
- # host designed to stop whenever it is idle, that is every day.
14
- if [ -n "${WALGIT_SSH_HOST_KEY:-}" ]; then
15
- printf '%s\n' "$WALGIT_SSH_HOST_KEY" > /etc/ssh/ssh_host_ed25519_key
16
- chmod 600 /etc/ssh/ssh_host_ed25519_key
17
- ssh-keygen -y -f /etc/ssh/ssh_host_ed25519_key > /etc/ssh/ssh_host_ed25519_key.pub
18
- else
19
- echo "walgit: WALGIT_SSH_HOST_KEY is unset — generating an EPHEMERAL host key." >&2
20
- echo "walgit: clients will see a changed host key after every machine stop." >&2
21
- ssh-keygen -q -t ed25519 -N '' -f /etc/ssh/ssh_host_ed25519_key
22
- fi
23
-
24
- # Every authorized key is pinned to the forced command. The client's own command
25
- # line is then never executed — it arrives as SSH_ORIGINAL_COMMAND and is parsed
26
- # by src/repo.ts, which allows exactly two git verbs and one repository name.
27
- AUTH_KEYS=/srv/walgit/.ssh/authorized_keys
28
- : > "$AUTH_KEYS"
29
- if [ -n "${WALGIT_SSH_AUTHORIZED_KEYS:-}" ]; then
30
- printf '%s\n' "$WALGIT_SSH_AUTHORIZED_KEYS" | while IFS= read -r key; do
31
- case "$key" in
32
- ''|\#*) continue ;;
33
- esac
34
- printf 'command="bun /app/src/ssh-shell.ts",no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty %s\n' "$key" >> "$AUTH_KEYS"
35
- done
36
- fi
37
- chown git:git "$AUTH_KEYS"
38
- chmod 600 "$AUTH_KEYS"
39
- if [ ! -s "$AUTH_KEYS" ]; then
40
- echo "walgit: no authorized keys — SSH will refuse every client (set WALGIT_SSH_AUTHORIZED_KEYS)." >&2
41
- fi
42
-
43
- # Two processes, one machine lifetime: if either half dies the machine should
44
- # stop rather than keep serving half a git host, so each kills the other.
45
- /usr/sbin/sshd -D -e &
46
- SSHD=$!
47
- bun /app/src/server.ts &
48
- HTTP=$!
49
-
50
- term() { kill "$SSHD" "$HTTP" 2>/dev/null || true; }
51
- trap term TERM INT
52
-
53
- # Polled rather than `wait -n`, which busybox ash does not reliably provide.
54
- while kill -0 "$SSHD" 2>/dev/null && kill -0 "$HTTP" 2>/dev/null; do
55
- sleep 5
56
- done
57
- echo "walgit: a server process exited — stopping the machine." >&2
58
- term
59
- exit 1