@zabaca/zbc 0.26.0 → 0.27.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 (33) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/package.json +1 -1
  3. package/src/commands/secret.ts +1 -66
  4. package/src/commands/update.ts +44 -1
  5. package/src/engine/actions.ts +35 -3
  6. package/src/engine/on-demand.ts +9 -1
  7. package/src/engine/secret-outputs.ts +15 -0
  8. package/src/engine/secrets.ts +81 -1
  9. package/src/utils/copy-refresh.ts +124 -19
  10. package/src/utils/template-history.ts +66 -0
  11. package/templates/history.json +1 -0
  12. package/templates/infra/modules/cloudflare/index.ts +140 -1
  13. package/templates/infra/modules/cloudflare-access/index.ts +176 -65
  14. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  15. package/templates/infra/modules/cloudflare-api/index.ts +56 -0
  16. package/templates/infra/modules/cloudflare-email/index.ts +44 -17
  17. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  18. package/templates/infra/modules/cloudflare-stored-token/index.ts +343 -0
  19. package/templates/infra/modules/cloudflare-stored-token/registry.json +12 -0
  20. package/templates/infra/modules/cloudflare-token/index.ts +46 -17
  21. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  22. package/templates/infra/modules/cloudflare-tunnel/index.ts +63 -8
  23. package/templates/infra/modules/cloudflare-tunnel/registry.json +1 -1
  24. package/templates/infra/modules/d1/index.ts +37 -35
  25. package/templates/infra/modules/d1/registry.json +1 -1
  26. package/templates/infra/modules/docker-compose-stack/index.ts +3 -1
  27. package/templates/infra/modules/queue/index.ts +28 -18
  28. package/templates/infra/modules/queue/registry.json +1 -1
  29. package/templates/infra/modules/r2/index.ts +20 -11
  30. package/templates/infra/modules/r2/registry.json +1 -1
  31. package/templates/infra/src/context.ts +41 -0
  32. package/templates/infra/src/testing.ts +19 -1
  33. package/templates/infra/src/types.ts +23 -0
package/CHANGELOG.md CHANGED
@@ -5,6 +5,103 @@ only add or fix things are described by their `release(cli): @zabaca/zbc <x.y.z>
5
5
  commit message and the PRs it names; this file exists for the ones a consumer
6
6
  has to read before upgrading.
7
7
 
8
+ ## 0.27.0
9
+
10
+ ### `cloudflare-access`: a service token is minted by an action, and its secret is stored, not printed
11
+
12
+ **Every instance that declares `serviceTokenName` must change before it applies again.**
13
+
14
+ An apply used to create the service token and print its client id and secret
15
+ once, for you to capture. It no longer creates the token, rotates it, or prints
16
+ or emits a secret. The `clientSecret` output is gone.
17
+
18
+ What to do, per instance with `serviceTokenName`:
19
+
20
+ 1. Add `serviceTokenSecret: '<KEY>'`: the key in that environment's
21
+ `secrets.yaml` under which the token's client secret is kept. Without it the
22
+ instance is refused.
23
+ 2. Make sure the secret is under that key:
24
+ - **The token exists and you hold its secret:** put it there
25
+ (`sops set`), or name the key it is already under.
26
+ - **The token exists and nobody holds the secret:**
27
+ `zbc run <env> <instance> rotate --yes`. The old secret stops working at
28
+ once, so whatever uses the door needs the new one in the same sitting.
29
+ - **A new token:** `zbc run <env> <instance> mint`.
30
+ Commit `secrets.yaml` after `mint` or `rotate`.
31
+ 3. Remove `rotate: true` if you have it; it is refused. `rotate: false` is
32
+ still accepted and does nothing.
33
+ 4. Replace anything that read the secret from the apply log or from
34
+ `zbc apply --json` with a read of the key:
35
+ `zbc secret get <env> <KEY>`. A Worker in the same environment names the key
36
+ in `workerSecrets`.
37
+
38
+ An apply of an instance whose token does not exist stops and says to run
39
+ `mint`. An apply whose key is missing from `secrets.yaml` stops before calling
40
+ Cloudflare. `clientId` is still an output.
41
+
42
+ The space kit follows: each machine door in the install file
43
+ (`access.agent`, `telegram`, `texts`, `clients`, `leads`) needs a `secret`
44
+ beside `application` and `token`, the name its token's secret is held under.
45
+ An install with a door turned on is refused until it has one.
46
+
47
+ ### `cloudflare-tunnel`: the run token is a declared secret
48
+
49
+ `runToken` was a plain output, written verbatim into `zbc apply --json`. It is
50
+ now a secret output: `[redacted]` in that file and in anything the engine
51
+ prints. An instance that imports it still receives the real value in memory.
52
+
53
+ - If you read `runToken` out of `--json`, set `runTokenSecret: '<KEY>'` on the
54
+ instance, run `zbc run <env> <instance> store-run-token`, commit
55
+ `secrets.yaml`, and read the key with `zbc secret get`.
56
+ - An `ephemeral: true` tunnel is refused before anything applies: recreating
57
+ the tunnel changes its token under a cloudflared no apply reaches.
58
+
59
+ ### An action can store a secret (`ctx.storeSecret`)
60
+
61
+ New, for module authors: an action may write one key of the environment's
62
+ `secrets.yaml` through sops. An apply cannot. See ADR-0023.
63
+
64
+ ### Copy-mode `zbc update` no longer replaces or deletes what the project wrote
65
+
66
+ `zbc update` in a copy-mode project chose what to refresh by directory name. A
67
+ module the project wrote under a built-in's name (`d1`, before zbc had one), or
68
+ a built-in it had edited, was overwritten with zbc's, and every file in
69
+ `packages/infra/src/` that zbc does not ship was deleted, all with exit 0.
70
+
71
+ It now replaces or removes a file only when some version of zbc shipped it,
72
+ formatting and comments aside:
73
+
74
+ - A built-in-named module with a file no version of zbc shipped is kept whole
75
+ and printed as `keep`. If you relied on `update` to reset such a module, pass
76
+ `--overwrite-edits`.
77
+ - An edited file in `packages/infra/src/` stops the update before anything is
78
+ written. Move the edit out, or pass `--overwrite-engine-edits`.
79
+ - Your own files beside zbc's are left in place and listed.
80
+ - A library a refreshed module imports that the project does not have is named
81
+ with the `zbc add` that brings it.
82
+
83
+ A kept module stays at the vintage it was copied at while the engine under it
84
+ moves, so read the `keep` lines and check those modules still load.
85
+
86
+ ### `cloudflare-api` gains exports the Cloudflare modules now import
87
+
88
+ `r2`, `queue`, `d1`, `cloudflare-email` and `cloudflare-tunnel` import
89
+ `apiTokenFor`, `apiTokenSchema` and `tokenScopeHint` from `../cloudflare-api`.
90
+ A subtree project gets the library with the modules. A copy-mode project gets
91
+ it from `zbc update` as long as its copy of `cloudflare-api` is unedited; if
92
+ you edited it, `update` keeps yours and the refreshed modules will not load
93
+ until you add the three exports or pass `--overwrite-edits`.
94
+
95
+ No instance needs changing: `apiToken` is optional on `r2`, `queue`, `d1` and
96
+ `cloudflare-email`, and every form accepted before still is.
97
+
98
+ ### `cloudflare` can prove a deploy is what answers
99
+
100
+ Nothing to change in an existing instance. If you poll a health path after
101
+ `zbc apply` to see the new commit, `deployCheck: { path }` beside `deployIdVar`
102
+ now does it inside the apply and fails the apply when the Worker never names
103
+ the deploy. The module also emits `deployId`.
104
+
8
105
  ## 0.26.0
9
106
 
10
107
  ### `zbc init` no longer writes `.claude/settings.json` into an existing repo
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zabaca/zbc",
3
- "version": "0.26.0",
3
+ "version": "0.27.0",
4
4
  "description": "Zabaca stack CLI — scaffold and deploy infrastructure",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,6 +1,5 @@
1
1
  import * as path from 'node:path'
2
2
  import { defineCommand } from 'citty'
3
- import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
4
3
  import {
5
4
  decryptSubmission,
6
5
  decryptWithDocumentKey,
@@ -14,7 +13,7 @@ import {
14
13
  import { resolveSecret } from '../../templates/infra/src/context'
15
14
  import { applyEnvironment } from '../engine/apply'
16
15
  import { discoverInstances } from '../engine/discover'
17
- import { loadSecrets } from '../engine/secrets'
16
+ import { loadSecrets, writeSecrets } from '../engine/secrets'
18
17
  import { findProjectRoot } from '../utils/find-project-root'
19
18
  import { loadConfig } from '../utils/load-config'
20
19
 
@@ -40,70 +39,6 @@ function sleep(ms: number): Promise<void> {
40
39
  return new Promise((resolve) => setTimeout(resolve, ms))
41
40
  }
42
41
 
43
- /**
44
- * Merge `values` into the environment's secrets.yaml. With a `.sops.yaml` at
45
- * the project root, writes go through sops so plaintext never lands on disk:
46
- * `sops set` per key into an existing encrypted file, or a stdin-piped
47
- * `sops -e` (with --filename-override so creation rules match) to create one.
48
- * Without `.sops.yaml`, falls back to plain YAML (development mode, mirroring
49
- * loadSecrets).
50
- */
51
- async function writeSecrets(
52
- projectRoot: string,
53
- envDir: string,
54
- values: Record<string, string>,
55
- ): Promise<void> {
56
- const secretsPath = path.join(envDir, 'secrets.yaml')
57
- const file = Bun.file(secretsPath)
58
- const exists = await file.exists()
59
- const hasSopsConfig = await Bun.file(path.join(projectRoot, '.sops.yaml')).exists()
60
-
61
- if (!hasSopsConfig) {
62
- const existing = exists ? (parseYaml(await file.text()) ?? {}) : {}
63
- await Bun.write(secretsPath, stringifyYaml({ ...existing, ...values }))
64
- return
65
- }
66
-
67
- const alreadyEncrypted = exists && parseYaml(await file.text())?.sops
68
- if (alreadyEncrypted) {
69
- for (const [key, value] of Object.entries(values)) {
70
- const proc = Bun.spawnSync(
71
- ['sops', 'set', secretsPath, `["${key}"]`, JSON.stringify(value)],
72
- { cwd: projectRoot, stderr: 'pipe' },
73
- )
74
- if (proc.exitCode !== 0) {
75
- throw new Error(`sops set failed for ${key}: ${proc.stderr.toString()}`)
76
- }
77
- }
78
- return
79
- }
80
-
81
- // Missing (or plain, pre-sops) file: merge in memory, encrypt via stdin so
82
- // plaintext never touches the filesystem.
83
- const existing = exists ? (parseYaml(await file.text()) ?? {}) : {}
84
- const plaintext = stringifyYaml({ ...existing, ...values })
85
- const proc = Bun.spawnSync(
86
- [
87
- 'sops',
88
- '--config',
89
- path.join(projectRoot, '.sops.yaml'),
90
- '--filename-override',
91
- secretsPath,
92
- '-e',
93
- '--input-type',
94
- 'yaml',
95
- '--output-type',
96
- 'yaml',
97
- '/dev/stdin',
98
- ],
99
- { cwd: projectRoot, stdin: new TextEncoder().encode(plaintext), stderr: 'pipe' },
100
- )
101
- if (proc.exitCode !== 0) {
102
- throw new Error(`sops encrypt failed: ${proc.stderr.toString()}`)
103
- }
104
- await Bun.write(secretsPath, proc.stdout)
105
- }
106
-
107
42
  /**
108
43
  * Find the project's Secret Relay and converge it through the normal apply
109
44
  * graph (outputs are per-run, not persisted — ADR-0003), returning its
@@ -46,6 +46,17 @@ export const updateCommand = defineCommand({
46
46
  type: 'string',
47
47
  description: 'zbc-core ref to pull (default: the tag matching this CLI version)',
48
48
  },
49
+ 'overwrite-engine-edits': {
50
+ type: 'boolean',
51
+ description: "Copy mode: replace engine files the project edited with this CLI's",
52
+ default: false,
53
+ },
54
+ 'overwrite-edits': {
55
+ type: 'boolean',
56
+ description:
57
+ "Copy mode: replace edited engine files and edited or own built-in-named modules with this CLI's",
58
+ default: false,
59
+ },
49
60
  strict: {
50
61
  type: 'boolean',
51
62
  description: `Exit non-zero if ${VENDOR_PREFIX}/ holds files zbc-core does not ship`,
@@ -138,9 +149,36 @@ export const updateCommand = defineCommand({
138
149
  console.error(`✗ ${(err as Error).message}`)
139
150
  process.exit(1)
140
151
  }
141
- const result = await refreshCopiedTemplates(projectRoot)
152
+ const result = await refreshCopiedTemplates(projectRoot, {
153
+ overwriteEngine: args['overwrite-engine-edits'] || args['overwrite-edits'],
154
+ overwriteModules: args['overwrite-edits'],
155
+ })
156
+ if (result.editedEngine.length > 0) {
157
+ console.error("✗ The engine in packages/infra/src has edits of this project's own:")
158
+ for (const file of result.editedEngine) console.error(` ${file}`)
159
+ console.error(
160
+ ' No version of zbc shipped these files as they read here, and the engine cannot be\n' +
161
+ ' refreshed in part. Nothing was changed. Move the edits out of packages/infra/src,\n' +
162
+ " or run `zbc update --overwrite-engine-edits` to replace them with this CLI's files.",
163
+ )
164
+ process.exit(1)
165
+ }
142
166
  for (const skip of result.skipped) console.log(` skip ${skip.path} (${skip.reason})`)
143
167
  for (const gone of result.removed) console.log(` remove ${gone} (no longer shipped)`)
168
+ for (const kept of result.kept) {
169
+ console.log(
170
+ ` keep ${kept.path} (${kept.files.join(', ')} ${kept.files.length === 1 ? 'matches' : 'match'} no version zbc shipped)`,
171
+ )
172
+ }
173
+ for (const file of result.own) console.log(` yours, left in place: ${file}`)
174
+ if (result.kept.length > 0) {
175
+ console.log('')
176
+ console.log(
177
+ " Kept modules are this project's own or edited copies. They stay at their vintage,\n" +
178
+ ' so check they still load against the refreshed engine.\n' +
179
+ ' `zbc update --overwrite-edits` replaces them with the built-ins.',
180
+ )
181
+ }
144
182
  if (result.refreshed.length === 0) {
145
183
  console.log(' nothing to refresh (no copied engine or built-in modules found)')
146
184
  }
@@ -152,6 +190,11 @@ export const updateCommand = defineCommand({
152
190
  ` cd packages/infra && bun add ${missing.map(([n, v]) => `${n}@${v}`).join(' ')}`,
153
191
  )
154
192
  }
193
+ if (result.missingModules.length > 0) {
194
+ console.log('')
195
+ console.log(' Refreshed modules import libraries this project does not have:')
196
+ for (const name of result.missingModules) console.log(` zbc add ${name}`)
197
+ }
155
198
  await writeStamp(projectRoot, { mode: 'copy', cliVersion: pkg.version })
156
199
  console.log(
157
200
  `✓ refreshed ${result.refreshed.length} path(s) — review the diff before committing.`,
@@ -7,6 +7,7 @@
7
7
  // by a test asserting it stays unimported — which is also outside the graph,
8
8
  // the decrypted secrets, and the imports edge that the act needs.
9
9
 
10
+ import * as path from 'node:path'
10
11
  import type { ApplyContext, ModuleInstance } from '../../templates/infra/src/types'
11
12
  import type { InstanceRunOptions } from './apply'
12
13
  import { discoverInstances } from './discover'
@@ -14,7 +15,7 @@ import { applyImportsEagerly, withOnDemandImports } from './on-demand'
14
15
  import { createReadinessGate } from './readiness'
15
16
  import { resolveOrder } from './resolve'
16
17
  import { createSecretOutputRegistry, redactError } from './secret-outputs'
17
- import { loadSecrets } from './secrets'
18
+ import { loadSecrets, writeSecrets } from './secrets'
18
19
 
19
20
  export interface RunActionOptions extends InstanceRunOptions {
20
21
  /** The instance to act on. Required — an action is never fanned out. */
@@ -25,6 +26,12 @@ export interface RunActionOptions extends InstanceRunOptions {
25
26
  confirmed?: boolean
26
27
  /** Where the instances came from, for error messages. */
27
28
  envLabel?: string
29
+ /**
30
+ * Writes one key of the environment's secrets.yaml. With it, the action's
31
+ * body may call `ctx.storeSecret`; without it, that call throws as it does in
32
+ * an apply (ADR-0023).
33
+ */
34
+ storeSecret?: (key: string, value: string) => Promise<void>
28
35
  }
29
36
 
30
37
  /** One action as `zbc run` and `zbc list` report it. */
@@ -134,7 +141,20 @@ export async function runAction(
134
141
  instance,
135
142
  runOpts,
136
143
  outputs,
137
- { onDemand: true, asker },
144
+ {
145
+ onDemand: true,
146
+ asker,
147
+ ...(opts.storeSecret
148
+ ? {
149
+ storeSecret: async (key: string, value: string) => {
150
+ // Before the write: a value that fails to store is as much a
151
+ // credential in the error that says so as one that did not.
152
+ registry.recordValue(`secrets.yaml ${key}`, value)
153
+ await opts.storeSecret?.(key, value)
154
+ },
155
+ }
156
+ : {}),
157
+ },
138
158
  (ctx: ApplyContext) => action.run(validatedConfig, ctx),
139
159
  )
140
160
  } catch (err) {
@@ -151,7 +171,19 @@ export async function runEnvironmentAction(
151
171
  ): Promise<void> {
152
172
  const instances = await discoverInstances(envDir)
153
173
  const secrets = await loadSecrets(envDir)
154
- await runAction(instances, { ...opts, secrets, projectRoot, envLabel: envDir })
174
+ const file = path.relative(projectRoot, path.join(envDir, 'secrets.yaml'))
175
+ await runAction(instances, {
176
+ ...opts,
177
+ secrets,
178
+ projectRoot,
179
+ envLabel: envDir,
180
+ async storeSecret(key, value) {
181
+ await writeSecrets(projectRoot, envDir, { [key]: value }, { valueViaStdin: true })
182
+ // The one thing the operator has to do next, said where they will see it:
183
+ // a stored secret that is not committed is lost with this checkout.
184
+ console.log(` Stored ${key} in ${file}. Commit that file.`)
185
+ },
186
+ })
155
187
  }
156
188
 
157
189
  /** The I/O half of "what can this instance do": no secrets, no provider, no run. */
@@ -57,6 +57,11 @@ interface OnDemandCommon {
57
57
  asker: string
58
58
  /** An extra line after an on-demand apply — a destroy says it will tear it down again. */
59
59
  afterApply?: (name: string) => string
60
+ /**
61
+ * The writer behind `ctx.storeSecret` for THIS body. Set for an action and
62
+ * for nothing else; never handed on to the imports the body causes to apply.
63
+ */
64
+ storeSecret?: (key: string, value: string) => Promise<void>
60
65
  }
61
66
 
62
67
  /**
@@ -150,6 +155,9 @@ function onDemandContext(
150
155
  secrets: opts.secrets,
151
156
  imports: importOutputs,
152
157
  projectRoot: opts.projectRoot,
158
+ // Only what `mode` carries: an action's body. The imports this context
159
+ // applies on demand are applies, built elsewhere, and get no writer.
160
+ ...(mode.storeSecret ? { storeSecret: mode.storeSecret } : {}),
153
161
  })
154
162
 
155
163
  /** Both spellings of the edge go through here before reaching `base`. */
@@ -184,7 +192,7 @@ function onDemandContext(
184
192
  if (!dep) throw new Error(`Cannot apply "${name}": it is not among ${instance.name}'s imports`)
185
193
  if (name in importOutputs) throw new Error(`Import "${name}" was already applied`)
186
194
 
187
- await ensureApplied(dep, mode.asker, opts, outputs, mode)
195
+ await ensureApplied(dep, mode.asker, opts, outputs, { ...mode, storeSecret: undefined })
188
196
  // THE EDGE, again: the value this body is about to read is held until the
189
197
  // module that minted it says it is usable.
190
198
  await opts.gate?.ensureReady(name)
@@ -57,6 +57,11 @@ export interface SecretOutputRegistry {
57
57
  * not the caller, decides there is nothing to hide.
58
58
  */
59
59
  record(instance: ModuleInstance, outputs: unknown): void
60
+ /**
61
+ * Remember one credential that is no instance's output: a value an action
62
+ * just stored. It is scrubbed from text as a declared output is.
63
+ */
64
+ recordValue(label: string, value: string): void
60
65
  /** Whether this run has minted anything at all — see `redactError`. */
61
66
  hasSecrets(): boolean
62
67
  /**
@@ -134,6 +139,16 @@ export function createSecretOutputRegistry(): SecretOutputRegistry {
134
139
  secrets.sort((a, b) => b.value.length - a.value.length)
135
140
  }
136
141
  },
142
+ recordValue(label, value) {
143
+ if (value.length < MIN_REDACTABLE_LENGTH) return
144
+ const existing = secrets.find((s) => s.value === value)
145
+ if (existing) {
146
+ if (!existing.labels.includes(label)) existing.labels.push(label)
147
+ return
148
+ }
149
+ secrets.push({ value, labels: [label] })
150
+ secrets.sort((a, b) => b.value.length - a.value.length)
151
+ },
137
152
  hasSecrets() {
138
153
  return secrets.length > 0
139
154
  },
@@ -1,5 +1,5 @@
1
1
  import * as path from 'node:path'
2
- import { parse as parseYaml } from 'yaml'
2
+ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
3
3
 
4
4
  export async function loadSecrets(envDir: string): Promise<Record<string, string>> {
5
5
  const secretsPath = path.join(envDir, 'secrets.yaml')
@@ -31,3 +31,83 @@ export async function loadSecrets(envDir: string): Promise<Record<string, string
31
31
 
32
32
  return parsed as Record<string, string>
33
33
  }
34
+
35
+ /**
36
+ * Merge `values` into the environment's secrets.yaml. With a `.sops.yaml` at
37
+ * the project root, writes go through sops so plaintext never lands on disk:
38
+ * `sops set` per key into an existing encrypted file, or a stdin-piped
39
+ * `sops -e` (with --filename-override so creation rules match) to create one.
40
+ * Without `.sops.yaml`, falls back to plain YAML (development mode, mirroring
41
+ * loadSecrets).
42
+ */
43
+ export async function writeSecrets(
44
+ projectRoot: string,
45
+ envDir: string,
46
+ values: Record<string, string>,
47
+ opts: { valueViaStdin?: boolean } = {},
48
+ ): Promise<void> {
49
+ const secretsPath = path.join(envDir, 'secrets.yaml')
50
+ const file = Bun.file(secretsPath)
51
+ const exists = await file.exists()
52
+ const hasSopsConfig = await Bun.file(path.join(projectRoot, '.sops.yaml')).exists()
53
+
54
+ if (!hasSopsConfig) {
55
+ const existing = exists ? (parseYaml(await file.text()) ?? {}) : {}
56
+ await Bun.write(secretsPath, stringifyYaml({ ...existing, ...values }))
57
+ return
58
+ }
59
+
60
+ const alreadyEncrypted = exists && parseYaml(await file.text())?.sops
61
+ if (alreadyEncrypted) {
62
+ for (const [key, value] of Object.entries(values)) {
63
+ // On stdin the value is in no process listing. `--value-stdin` is newer
64
+ // than `sops set` itself, so only the caller that asks for it depends on it.
65
+ const proc = opts.valueViaStdin
66
+ ? Bun.spawnSync(['sops', 'set', '--value-stdin', secretsPath, `["${key}"]`], {
67
+ cwd: projectRoot,
68
+ env: process.env,
69
+ stdin: new TextEncoder().encode(JSON.stringify(value)),
70
+ stderr: 'pipe',
71
+ })
72
+ : Bun.spawnSync(['sops', 'set', secretsPath, `["${key}"]`, JSON.stringify(value)], {
73
+ cwd: projectRoot,
74
+ env: process.env,
75
+ stderr: 'pipe',
76
+ })
77
+ if (proc.exitCode !== 0) {
78
+ throw new Error(`sops set failed for ${key}: ${proc.stderr.toString()}`)
79
+ }
80
+ }
81
+ return
82
+ }
83
+
84
+ // Missing (or plain, pre-sops) file: merge in memory, encrypt via stdin so
85
+ // plaintext never touches the filesystem.
86
+ const existing = exists ? (parseYaml(await file.text()) ?? {}) : {}
87
+ const plaintext = stringifyYaml({ ...existing, ...values })
88
+ const proc = Bun.spawnSync(
89
+ [
90
+ 'sops',
91
+ '--config',
92
+ path.join(projectRoot, '.sops.yaml'),
93
+ '--filename-override',
94
+ secretsPath,
95
+ '-e',
96
+ '--input-type',
97
+ 'yaml',
98
+ '--output-type',
99
+ 'yaml',
100
+ '/dev/stdin',
101
+ ],
102
+ {
103
+ cwd: projectRoot,
104
+ env: process.env,
105
+ stdin: new TextEncoder().encode(plaintext),
106
+ stderr: 'pipe',
107
+ },
108
+ )
109
+ if (proc.exitCode !== 0) {
110
+ throw new Error(`sops encrypt failed: ${proc.stderr.toString()}`)
111
+ }
112
+ await Bun.write(secretsPath, proc.stdout)
113
+ }