@homeflare/alchemy 0.6.0 → 0.7.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 (120) hide show
  1. package/README.md +54 -10
  2. package/dist/caddy/admin-calls.d.ts +48 -0
  3. package/dist/caddy/admin-calls.d.ts.map +1 -0
  4. package/dist/caddy/admin-guard.d.ts +40 -0
  5. package/dist/caddy/admin-guard.d.ts.map +1 -0
  6. package/dist/caddy/admin.d.ts +73 -0
  7. package/dist/caddy/admin.d.ts.map +1 -0
  8. package/dist/caddy/caddyfile-tripwire.d.ts +5 -0
  9. package/dist/caddy/caddyfile-tripwire.d.ts.map +1 -0
  10. package/dist/caddy/config-form.d.ts +27 -0
  11. package/dist/caddy/config-form.d.ts.map +1 -0
  12. package/dist/caddy/config-lifecycle.d.ts +45 -0
  13. package/dist/caddy/config-lifecycle.d.ts.map +1 -0
  14. package/dist/caddy/config.d.ts +30 -0
  15. package/dist/caddy/config.d.ts.map +1 -0
  16. package/dist/caddy/digest.d.ts +7 -0
  17. package/dist/caddy/digest.d.ts.map +1 -0
  18. package/dist/caddy/fake-caddy.d.ts +43 -0
  19. package/dist/caddy/fake-caddy.d.ts.map +1 -0
  20. package/dist/caddy/index.d.ts +21 -0
  21. package/dist/caddy/index.d.ts.map +1 -0
  22. package/dist/caddy/index.js +912 -0
  23. package/dist/caddy/index.js.map +28 -0
  24. package/dist/caddy/local-admin.d.ts +45 -0
  25. package/dist/caddy/local-admin.d.ts.map +1 -0
  26. package/dist/caddy/providers.d.ts +14 -0
  27. package/dist/caddy/providers.d.ts.map +1 -0
  28. package/dist/caddy/with-file.d.ts +47 -0
  29. package/dist/caddy/with-file.d.ts.map +1 -0
  30. package/dist/cloudflare/fake-mesh.d.ts +58 -0
  31. package/dist/cloudflare/fake-mesh.d.ts.map +1 -0
  32. package/dist/cloudflare/index.d.ts +9 -3
  33. package/dist/cloudflare/index.d.ts.map +1 -1
  34. package/dist/cloudflare/index.js +218 -7
  35. package/dist/cloudflare/index.js.map +9 -4
  36. package/dist/cloudflare/mesh-node-api.d.ts +75 -0
  37. package/dist/cloudflare/mesh-node-api.d.ts.map +1 -0
  38. package/dist/cloudflare/mesh-node-form.d.ts +82 -0
  39. package/dist/cloudflare/mesh-node-form.d.ts.map +1 -0
  40. package/dist/cloudflare/mesh-node-harness.d.ts +46 -0
  41. package/dist/cloudflare/mesh-node-harness.d.ts.map +1 -0
  42. package/dist/cloudflare/mesh-node-lifecycle.d.ts +22 -0
  43. package/dist/cloudflare/mesh-node-lifecycle.d.ts.map +1 -0
  44. package/dist/cloudflare/mesh-node-token.d.ts +23 -0
  45. package/dist/cloudflare/mesh-node-token.d.ts.map +1 -0
  46. package/dist/cloudflare/mesh-node.d.ts +48 -0
  47. package/dist/cloudflare/mesh-node.d.ts.map +1 -0
  48. package/dist/cloudflare/providers.d.ts +1 -12
  49. package/dist/cloudflare/providers.d.ts.map +1 -1
  50. package/dist/index.d.ts +1 -0
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/launchd/index.js.map +2 -2
  53. package/dist/launchd/secret-tripwire.d.ts +1 -0
  54. package/dist/launchd/secret-tripwire.d.ts.map +1 -1
  55. package/dist/openbao/cloudflare-role.d.ts.map +1 -1
  56. package/dist/openbao/fake-engines.d.ts +30 -0
  57. package/dist/openbao/fake-engines.d.ts.map +1 -0
  58. package/dist/openbao/fake-stack.d.ts +29 -0
  59. package/dist/openbao/fake-stack.d.ts.map +1 -0
  60. package/dist/openbao/index.js +231 -151
  61. package/dist/openbao/index.js.map +9 -7
  62. package/dist/openbao/policy.d.ts +2 -0
  63. package/dist/openbao/policy.d.ts.map +1 -1
  64. package/dist/openbao/proxmox-role-form.d.ts +18 -8
  65. package/dist/openbao/proxmox-role-form.d.ts.map +1 -1
  66. package/dist/openbao/proxmox-role-wire.d.ts +18 -0
  67. package/dist/openbao/proxmox-role-wire.d.ts.map +1 -0
  68. package/dist/openbao/proxmox-role.d.ts.map +1 -1
  69. package/dist/openbao/rename.d.ts +106 -0
  70. package/dist/openbao/rename.d.ts.map +1 -0
  71. package/docs/caddy.md +180 -0
  72. package/docs/mesh-node.md +188 -0
  73. package/package.json +7 -2
  74. package/src/caddy/admin-calls.ts +128 -0
  75. package/src/caddy/admin-guard.ts +170 -0
  76. package/src/caddy/admin.ts +74 -0
  77. package/src/caddy/caddyfile-tripwire.ts +133 -0
  78. package/src/caddy/config-form.ts +64 -0
  79. package/src/caddy/config-lifecycle.test.ts +218 -0
  80. package/src/caddy/config-lifecycle.ts +148 -0
  81. package/src/caddy/config.ts +116 -0
  82. package/src/caddy/digest.ts +44 -0
  83. package/src/caddy/fake-caddy.ts +160 -0
  84. package/src/caddy/guards.test.ts +156 -0
  85. package/src/caddy/index.ts +25 -0
  86. package/src/caddy/local-admin.test.ts +160 -0
  87. package/src/caddy/local-admin.ts +189 -0
  88. package/src/caddy/providers.test.ts +244 -0
  89. package/src/caddy/providers.ts +17 -0
  90. package/src/caddy/with-file.ts +62 -0
  91. package/src/cloudflare/fake-mesh.ts +181 -0
  92. package/src/cloudflare/index.ts +9 -3
  93. package/src/cloudflare/mesh-node-api.ts +127 -0
  94. package/src/cloudflare/mesh-node-edges.test.ts +103 -0
  95. package/src/cloudflare/mesh-node-form.test.ts +80 -0
  96. package/src/cloudflare/mesh-node-form.ts +115 -0
  97. package/src/cloudflare/mesh-node-harness.ts +124 -0
  98. package/src/cloudflare/mesh-node-lifecycle.ts +187 -0
  99. package/src/cloudflare/mesh-node-policy.test.ts +151 -0
  100. package/src/cloudflare/mesh-node-token.test.ts +117 -0
  101. package/src/cloudflare/mesh-node-token.ts +125 -0
  102. package/src/cloudflare/mesh-node.test.ts +172 -0
  103. package/src/cloudflare/mesh-node.ts +120 -0
  104. package/src/cloudflare/providers.ts +20 -2
  105. package/src/index.ts +1 -0
  106. package/src/launchd/secret-tripwire.ts +1 -1
  107. package/src/openbao/REPLACE.md +97 -21
  108. package/src/openbao/cloudflare-role-wire.test.ts +8 -34
  109. package/src/openbao/cloudflare-role.ts +30 -8
  110. package/src/openbao/fake-engines.ts +119 -0
  111. package/src/openbao/fake-stack.ts +112 -0
  112. package/src/openbao/policy-rename.test.ts +112 -0
  113. package/src/openbao/policy-wire.test.ts +7 -26
  114. package/src/openbao/policy.ts +27 -4
  115. package/src/openbao/proxmox-role-form.ts +27 -8
  116. package/src/openbao/proxmox-role-wire.ts +24 -0
  117. package/src/openbao/proxmox-role.ts +62 -37
  118. package/src/openbao/rename-occupied.test.ts +166 -0
  119. package/src/openbao/rename.ts +162 -0
  120. package/src/openbao/role-rename.test.ts +205 -0
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The read Bao.ProxmoxRole makes of `<mount>/roles/<name>`, split from proxmox-role.ts so the diff,
3
+ * reconcile and the rename's re-scope check share one definition of "the live role".
4
+ */
5
+ import * as Effect from 'effect/Effect';
6
+ import { baoRead } from './bao-http.ts';
7
+ import { type BaoProxmoxRoleProps, attributesOf, rolePath } from './proxmox-role-form.ts';
8
+
9
+ /**
10
+ * The live role, or undefined when OpenBao answers 404.
11
+ *
12
+ * ⚠️ A missing MOUNT and a missing ROLE both read as undefined here, because both answer 404:
13
+ * an absent role is a read that found nothing, and a path under no mount is OpenBao's
14
+ * unsupported-path error, which is also a 404 (sdk/logical/response_util.go). They are not the
15
+ * same failure — one is a typo in `mount`, the other is a role that has yet to be created — so
16
+ * reconcile lets OpenBao's own `errors` through on the write rather than inventing a message.
17
+ * A bad mount says "no handler for route".
18
+ */
19
+ export const readRole = (props: Pick<BaoProxmoxRoleProps, 'mount' | 'name'>) =>
20
+ Effect.gen(function* () {
21
+ const live = yield* baoRead(rolePath(props.mount, props.name));
22
+ if (live === undefined) return undefined;
23
+ return attributesOf(props, live);
24
+ });
@@ -40,15 +40,25 @@ import { isResolved } from 'alchemy/Diff';
40
40
  import * as Provider from 'alchemy/Provider';
41
41
  import * as Effect from 'effect/Effect';
42
42
  import type * as HttpClient from 'effect/unstable/http/HttpClient';
43
- import { baoDelete, baoRead, baoWrite } from './bao-http.ts';
43
+ import { baoDelete, baoWrite } from './bao-http.ts';
44
44
  import {
45
45
  type BaoProxmoxRoleAttributes,
46
46
  type BaoProxmoxRoleProps,
47
- attributesOf,
48
47
  matches,
48
+ rescopeRefusal,
49
49
  rolePath,
50
50
  writeBody,
51
51
  } from './proxmox-role-form.ts';
52
+ import { readRole } from './proxmox-role-wire.ts';
53
+ import {
54
+ declaredRolePath,
55
+ declaredString,
56
+ isMoved,
57
+ isPendingProp,
58
+ judgeMove,
59
+ refuseMovedUpdate,
60
+ triedRolePath,
61
+ } from './rename.ts';
52
62
 
53
63
  export type { BaoProxmoxRoleAttributes, BaoProxmoxRoleProps };
54
64
 
@@ -64,21 +74,6 @@ export const BaoProxmoxRole = Resource<BaoProxmoxRole>('Bao.ProxmoxRole', {
64
74
  defaultRemovalPolicy: 'retain',
65
75
  });
66
76
 
67
- /**
68
- * ⚠️ A missing MOUNT and a missing ROLE both read as undefined here, because both answer 404:
69
- * an absent role is a read that found nothing, and a path under no mount is OpenBao's
70
- * unsupported-path error, which is also a 404 (sdk/logical/response_util.go). They are not the
71
- * same failure — one is a typo in `mount`, the other is a role that has yet to be created — so
72
- * reconcile lets OpenBao's own `errors` through on the write rather than inventing a message.
73
- * A bad mount says "no handler for route".
74
- */
75
- const readRole = (props: BaoProxmoxRoleProps) =>
76
- Effect.gen(function* () {
77
- const live = yield* baoRead(rolePath(props.mount, props.name));
78
- if (live === undefined) return undefined;
79
- return attributesOf(props, live);
80
- });
81
-
82
77
  export const BaoProxmoxRoleProvider = () =>
83
78
  Provider.effect(
84
79
  BaoProxmoxRole,
@@ -103,8 +98,35 @@ export const BaoProxmoxRoleProvider = () =>
103
98
  * says everything is fine — exactly the drift the hand-written check-* gates exist to
104
99
  * catch, and exactly what a provider that trusted its own state would walk past.
105
100
  */
106
- diff: Effect.fn(function* ({ news, output }) {
107
- if (output === undefined || !isResolved(news)) return undefined;
101
+ diff: Effect.fn(function* ({ news, olds, output }) {
102
+ /**
103
+ * ⛔ A NEW `mount` OR `name` IS A `replace` (rename.ts). It is a DIFFERENT path, so none of
104
+ * the reasons below apply. Until 2026-09-21 it planned `update` and left the old role
105
+ * minting under no state record. Under the default `retain` the old role still mints;
106
+ * under `destroy` its consumers fail at the delete (REPLACE.md). ⛔ A move onto a role
107
+ * that already exists fails the plan (`judgeMove`).
108
+ * ⛔ THE RE-SCOPE GUARD TRAVELS WITH THE RENAME, checked here because the new generation's
109
+ * reconcile finds no live role to compare. While `mintUser` or `allowMintUserChange` is
110
+ * still an Output it cannot be checked, so the diff defers, and reconcile refuses the
111
+ * resulting `update`.
112
+ */
113
+ const tried = triedRolePath(output, olds, rolePath);
114
+ const declared = declaredRolePath(news, rolePath);
115
+ const move = yield* judgeMove('Bao.ProxmoxRole', tried, declared, (path) => path);
116
+ if (output === undefined) return undefined;
117
+ if (move !== undefined) {
118
+ const mintUser = declaredString(news, 'mintUser');
119
+ if (mintUser === undefined || isPendingProp(news, 'allowMintUserChange'))
120
+ return undefined;
121
+ const from = (yield* readRole(output))?.mintUser ?? output.mintUser;
122
+ const allow = declaredString(news, 'allowMintUserChange');
123
+ const refusal = rescopeRefusal(from, mintUser, allow);
124
+ if (refusal === undefined) return { action: 'replace' } as const;
125
+ return yield* Effect.die(
126
+ new Error(`Bao.ProxmoxRole ${move.from} → ${move.to}: the rename ${refusal}`),
127
+ );
128
+ }
129
+ if (!isResolved(news)) return undefined;
108
130
  const live = yield* readRole(news);
109
131
  if (live === undefined) return { action: 'update' } as const;
110
132
  if (matches(live, news)) return { action: 'noop' } as const;
@@ -126,7 +148,13 @@ export const BaoProxmoxRoleProvider = () =>
126
148
  return { action: 'update' } as const;
127
149
  }),
128
150
 
129
- reconcile: Effect.fn(function* ({ news }) {
151
+ reconcile: Effect.fn(function* ({ news, output }) {
152
+ const path = rolePath(news.mount, news.name);
153
+ // ⛔ An `update` across a move the diff could not see — refused before any read or write.
154
+ const before = output === undefined ? path : rolePath(output.mount, output.name);
155
+ if (isMoved(before, path) === true) {
156
+ return yield* refuseMovedUpdate('Bao.ProxmoxRole', before, path);
157
+ }
130
158
  const live = yield* readRole(news);
131
159
  /**
132
160
  * ⛔ A mint_user CHANGE RE-SCOPES EVERY CREDENTIAL THE ROLE WILL EVER MINT, SILENTLY.
@@ -137,20 +165,15 @@ export const BaoProxmoxRoleProvider = () =>
137
165
  * move unless the declaration NAMES THE VALUE IT IS REPLACING. Creating a role never
138
166
  * trips this — there is nothing to re-scope — and the permission expires by itself
139
167
  * once the change lands, because live then equals the declaration.
168
+ * ⚠️ A RENAME CREATES A NEW ROLE, SO IT NEVER REACHES THIS CHECK. The diff asks the same
169
+ * question of the role being replaced (`rescopeRefusal`, proxmox-role-form.ts).
140
170
  */
141
- if (
142
- live !== undefined &&
143
- live.mintUser !== news.mintUser &&
144
- news.allowMintUserChange !== live.mintUser
145
- ) {
146
- return yield* Effect.die(
147
- new Error(
148
- `Bao.ProxmoxRole ${rolePath(news.mount, news.name)}: live mint_user ` +
149
- `${live.mintUser} != declared ${news.mintUser}. Every token this role mints ` +
150
- 'inherits the ACL of that PVE user. To re-scope deliberately, declare ' +
151
- `allowMintUserChange: '${live.mintUser}'.`,
152
- ),
153
- );
171
+ const rescope =
172
+ live === undefined
173
+ ? undefined
174
+ : rescopeRefusal(live.mintUser, news.mintUser, news.allowMintUserChange);
175
+ if (rescope !== undefined) {
176
+ return yield* Effect.die(new Error(`Bao.ProxmoxRole ${path}: ${rescope}`));
154
177
  }
155
178
  if (live === undefined || !matches(live, news)) {
156
179
  const write = writeBody(news);
@@ -164,18 +187,18 @@ export const BaoProxmoxRoleProvider = () =>
164
187
  if (!write.ok) {
165
188
  return yield* Effect.die(
166
189
  new Error(
167
- `Bao.ProxmoxRole ${rolePath(news.mount, news.name)}: unparseable duration ` +
190
+ `Bao.ProxmoxRole ${path}: unparseable duration ` +
168
191
  `${write.bad.join(', ')}. Use 30s / 5m / 1h / 1d, or 0.`,
169
192
  ),
170
193
  );
171
194
  }
172
- yield* baoWrite('PUT', rolePath(news.mount, news.name), write.body);
195
+ yield* baoWrite('PUT', path, write.body);
173
196
  }
174
197
  const after = yield* readRole(news);
175
198
  if (after === undefined) {
176
199
  return yield* Effect.die(
177
200
  new Error(
178
- `Bao.ProxmoxRole ${rolePath(news.mount, news.name)}: write returned no error ` +
201
+ `Bao.ProxmoxRole ${path}: write returned no error ` +
179
202
  'but the role is still absent.',
180
203
  ),
181
204
  );
@@ -197,7 +220,9 @@ export const BaoProxmoxRoleProvider = () =>
197
220
  * So this is an availability change for every consumer of `creds/<name>` and NOT a
198
221
  * containment action: to contain a leaked credential, revoke the lease (which deletes
199
222
  * the PVE token) or delete the token in PVE. Deleting the role only hides the door it
200
- * came through. REASONED from Vault lease semantics; not exercised here.
223
+ * came through. The plugin's own test pins this (homeflare-openbao-plugins,
224
+ * TestDeletingARoleLeavesItsOutstandingLeasesRevocable): the delete is one storage
225
+ * delete, and each lease stays revocable without the role.
201
226
  *
202
227
  * ⚠️ IDEMPOTENT AS ALCHEMY REQUIRES — already gone is success. It used to get that by
203
228
  * going through `baoReadText`, which discarded the exit code entirely, so a REFUSED
@@ -0,0 +1,166 @@
1
+ /**
2
+ * A move onto an object that already exists, through Alchemy's own plan and apply (fake-stack.ts).
3
+ * Before `judgeMove` read the target, the first test below was a GREEN deploy that deleted both
4
+ * policies: each new generation wrote over the other's, and each old generation's delete then
5
+ * removed what the other had just written (rename.ts has the measurement).
6
+ */
7
+ import assert from 'node:assert/strict';
8
+ import { describe, it } from 'node:test';
9
+ import * as Output from 'alchemy/Output';
10
+ import * as RemovalPolicy from 'alchemy/RemovalPolicy';
11
+ import * as Effect from 'effect/Effect';
12
+ import * as Layer from 'effect/Layer';
13
+ import * as FetchHttpClient from 'effect/unstable/http/FetchHttpClient';
14
+ import { groupKey } from './cloudflare-group-scope.ts';
15
+ import { CloudflarePermissionGroups } from './cloudflare-permission-groups.ts';
16
+ import { BaoCloudflareRole, BaoCloudflareRoleProvider } from './cloudflare-role.ts';
17
+ import { aclPolicies, cloudflareRoles, fakePolicyProviders, proxmoxRoles } from './fake-engines.ts';
18
+ import { type StackBody, withFakeStack, writesOf } from './fake-stack.ts';
19
+ import { BaoPolicy } from './policy.ts';
20
+ import { BaoProxmoxRole, BaoProxmoxRoleProvider } from './proxmox-role.ts';
21
+
22
+ const OCCUPIED = /would land on an object that already exists/;
23
+
24
+ /** Two policies, `X` and `Y`, each with fragments named after its logical id, under destroy. */
25
+ const pair = (x: string, y: string): StackBody =>
26
+ Effect.gen(function* () {
27
+ yield* BaoPolicy('X', { fragments: '/p/x', name: x }).pipe(RemovalPolicy.destroy());
28
+ yield* BaoPolicy('Y', { fragments: '/p/y', name: y }).pipe(RemovalPolicy.destroy());
29
+ });
30
+
31
+ describe('Bao.Policy: a rename onto a policy that exists fails the plan', () => {
32
+ it('a swap under destroy writes nothing and deletes nothing', async () => {
33
+ const store = aclPolicies();
34
+ await withFakeStack(fakePolicyProviders, store, async (stack, bao) => {
35
+ await stack.deploy(pair('a', 'b'));
36
+ const before = new Map(store.live);
37
+ bao.seen.length = 0;
38
+ await assert.rejects(stack.deploy(pair('b', 'a')), OCCUPIED);
39
+ assert.deepEqual(writesOf(bao.seen), []);
40
+ assert.deepEqual(store.live, before);
41
+ });
42
+ });
43
+
44
+ it('a shift (a → b while b → c) is refused for the name still held', async () => {
45
+ const store = aclPolicies();
46
+ await withFakeStack(fakePolicyProviders, store, async (stack, bao) => {
47
+ await stack.deploy(pair('a', 'b'));
48
+ bao.seen.length = 0;
49
+ await assert.rejects(stack.deploy(pair('b', 'c')), /Bao\.Policy: a → b would land/);
50
+ assert.deepEqual(writesOf(bao.seen), []);
51
+ });
52
+ });
53
+
54
+ it('reverting a move whose new generation failed is refused while the old name is live', async () => {
55
+ const store = aclPolicies();
56
+ const one = (name: string, dir: string): StackBody =>
57
+ Effect.asVoid(BaoPolicy('X', { fragments: dir, name }).pipe(RemovalPolicy.destroy()));
58
+ await withFakeStack(fakePolicyProviders, store, async (stack, bao) => {
59
+ await stack.deploy(one('a', '/p/x'));
60
+ await assert.rejects(stack.deploy(one('b', '/p/empty')), /carry no path grant/);
61
+ bao.seen.length = 0;
62
+ await assert.rejects(stack.deploy(one('a', '/p/x')), /Bao\.Policy: b → a would land/);
63
+ assert.deepEqual(writesOf(bao.seen), []);
64
+ assert.ok(store.live.has('sys/policies/acl/a'));
65
+ // ★ Finishing the move instead replaces cleanly and deletes the old name.
66
+ assert.deepEqual(await stack.deploy(one('b', '/p/x')), { X: 'replace' });
67
+ assert.deepEqual([...store.live.keys()], ['sys/policies/acl/b']);
68
+ });
69
+ });
70
+ });
71
+
72
+ /** Every group resolves, to an id named after it. */
73
+ const groups = Layer.succeed(CloudflarePermissionGroups, {
74
+ resolve: (_mount, refs) =>
75
+ Effect.succeed(new Map(refs.map((ref) => [groupKey(ref.name, ref.scope), `id-${ref.name}`]))),
76
+ });
77
+ const roleProviders = Layer.mergeAll(
78
+ BaoCloudflareRoleProvider().pipe(Layer.provide(groups)),
79
+ BaoProxmoxRoleProvider(),
80
+ FetchHttpClient.layer,
81
+ );
82
+
83
+ const cf = (id: string, name: string) =>
84
+ BaoCloudflareRole(id, {
85
+ description: 'Read DNS records on one zone. (zone: example.com)',
86
+ maxTtl: '1h',
87
+ mount: 'cloudflare-example',
88
+ name,
89
+ policies: [
90
+ {
91
+ effect: 'allow',
92
+ groupOrder: 'declared',
93
+ groups: ['DNS Read'],
94
+ resource: 'com.cloudflare.api.account.zone.z1',
95
+ },
96
+ ],
97
+ ttl: '5m',
98
+ }).pipe(RemovalPolicy.destroy());
99
+
100
+ describe('the role families: a move onto a role that exists fails the plan', () => {
101
+ it('Bao.CloudflareRole: a swap under destroy writes nothing', async () => {
102
+ const store = cloudflareRoles();
103
+ const body = (x: string, y: string): StackBody =>
104
+ Effect.gen(function* () {
105
+ yield* cf('X', x);
106
+ yield* cf('Y', y);
107
+ });
108
+ await withFakeStack(roleProviders, store, async (stack, bao) => {
109
+ await stack.deploy(body('dns-read', 'dns-edit'));
110
+ bao.seen.length = 0;
111
+ await assert.rejects(stack.deploy(body('dns-edit', 'dns-read')), OCCUPIED);
112
+ assert.deepEqual(writesOf(bao.seen), []);
113
+ assert.equal(store.live.size, 2);
114
+ });
115
+ });
116
+
117
+ it('Bao.ProxmoxRole: a rename onto a role made by hand writes nothing', async () => {
118
+ const store = proxmoxRoles();
119
+ const role = (name: string): StackBody =>
120
+ Effect.asVoid(
121
+ BaoProxmoxRole('Role', {
122
+ maxTtl: '6h',
123
+ mintUser: 'reader@pve',
124
+ mount: 'proxmox-lab',
125
+ name,
126
+ ttl: '1h',
127
+ }),
128
+ );
129
+ await withFakeStack(roleProviders, store, async (stack, bao) => {
130
+ await stack.deploy(role('read'));
131
+ store.live.set('proxmox-lab/roles/audit', { max_ttl: 0, mint_user: 'auditor@pve', ttl: 0 });
132
+ bao.seen.length = 0;
133
+ await assert.rejects(stack.deploy(role('audit')), OCCUPIED);
134
+ assert.deepEqual(writesOf(bao.seen), []);
135
+ assert.equal(store.live.get('proxmox-lab/roles/audit')?.['mint_user'], 'auditor@pve');
136
+ });
137
+ });
138
+ });
139
+
140
+ describe('Bao.ProxmoxRole: a re-scoping rename whose allowance is still an Output', () => {
141
+ it('defers instead of refusing a value it cannot read yet, then checks it once resolved', async () => {
142
+ const store = proxmoxRoles();
143
+ const base = { maxTtl: '6h', mount: 'proxmox-lab', ttl: '1h' } as const;
144
+ const body = (ttl: string, name: string, mintUser: string): StackBody =>
145
+ Effect.gen(function* () {
146
+ const up = yield* BaoProxmoxRole('Upstream', {
147
+ ...base,
148
+ mintUser: 'up@pve',
149
+ name: 'up',
150
+ ttl,
151
+ });
152
+ const allowMintUserChange = Output.interpolate`reader-${up.ttl}@pve`;
153
+ yield* BaoProxmoxRole('Role', { ...base, allowMintUserChange, mintUser, name });
154
+ });
155
+ await withFakeStack(roleProviders, store, async (stack) => {
156
+ await stack.deploy(body('1h', 'read', 'reader@pve'));
157
+ // ★ Before the defer, this died at plan asking for the allowance it had been given.
158
+ await assert.rejects(stack.deploy(body('2h', 'reader', 'writer@pve')), /identity moved/);
159
+ await assert.rejects(
160
+ stack.deploy(body('2h', 'reader', 'writer@pve')),
161
+ /the rename re-scopes mint_user reader@pve/,
162
+ );
163
+ assert.ok(!store.live.has('proxmox-lab/roles/reader'));
164
+ });
165
+ });
166
+ });
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Rename safety for the families whose identity is a name, or a mount and a name: Bao.Policy,
3
+ * Bao.CloudflareRole and Bao.ProxmoxRole. REPLACE.md has the audit and what each answer does.
4
+ *
5
+ * ⛔ THE BUG THIS CLOSES, REPRODUCED 2026-09-21 AGAINST alchemy@2.0.0-beta.79's OWN PLAN AND APPLY
6
+ * (fake-stack.ts): a Bao.Policy deployed as `old`, then redeclared as `new` under
7
+ * `RemovalPolicy.destroy()`, planned `update` and left BOTH policies live. diff read the NEW
8
+ * path, found nothing, answered `update`, and reconcile wrote the new object. The old one stayed
9
+ * live under no state record, so no later plan would mention it, and not even `destroy` could
10
+ * remove it.
11
+ * ★ A CHANGED IDENTITY IS A DIFFERENT OBJECT, SO THE ANSWER IS `replace`. Create-first
12
+ * (`deleteFirst` false): the new path never collides with the old, the new generation is written,
13
+ * dependents are updated in the same graph, and only then is the old generation deleted. The
14
+ * engine hands that delete the OLD generation's attributes (Apply.ts deleteOldGenerations and the
15
+ * GC pass both pass `output: old.attr`), and every delete here reads `output`, never `news`.
16
+ * ⛔ A new path that collides with ANOTHER live object is refused at plan instead (`judgeMove`).
17
+ * ⚠️ UNDER `retain` THE OLD OBJECT STAYS LIVE. Apply.ts:2164-2173 skips the old generation's delete
18
+ * and logs "Retaining replaced resource (removal policy: retain)". The plan still says `replace`
19
+ * and the apply says what it kept, so it is no longer silent, but the old object is unmanaged
20
+ * from then on. Remove it by hand, or opt into `RemovalPolicy.destroy()`.
21
+ */
22
+ import * as Effect from 'effect/Effect';
23
+ import { baoRead } from './bao-http.ts';
24
+
25
+ const exact = (identity: string): string => identity;
26
+
27
+ /**
28
+ * A string prop of a diff's `news`, once that one prop is resolved; `undefined` while it is still an
29
+ * Output of a changing upstream (a function-typed proxy) or an Effect.
30
+ *
31
+ * ★ THE IDENTITY IS JUDGED BEFORE `isResolved(news)`. That guard returns `undefined` when ANY prop is
32
+ * pending, and the engine then falls back to `update` (Plan.ts, `havePropsChanged`). A rename that
33
+ * lands in the same deploy as a pending `fragments` or `policies` Output would slip through as
34
+ * `update`, which is the orphan again. launchd/host-effect.ts reads its identity the same way.
35
+ */
36
+ export const declaredString = (news: unknown, key: string): string | undefined => {
37
+ if (typeof news !== 'object' || news === null) return undefined;
38
+ const value: unknown = (news as Record<string, unknown>)[key];
39
+ return typeof value === 'string' ? value : undefined;
40
+ };
41
+
42
+ /** True while an optional prop is declared but is not yet a value: an Output of a changing upstream. */
43
+ export const isPendingProp = (news: unknown, key: string): boolean => {
44
+ if (typeof news !== 'object' || news === null) return false;
45
+ const value: unknown = (news as Record<string, unknown>)[key];
46
+ return value !== undefined && typeof value !== 'string';
47
+ };
48
+
49
+ /** A role's API path from a diff's `news`, once both `mount` and `name` are resolved. */
50
+ export const declaredRolePath = (
51
+ news: unknown,
52
+ rolePath: (mount: string, name: string) => string,
53
+ ): string | undefined => {
54
+ const mount = declaredString(news, 'mount');
55
+ const name = declaredString(news, 'name');
56
+ return mount === undefined || name === undefined ? undefined : rolePath(mount, name);
57
+ };
58
+
59
+ /**
60
+ * How OpenBao keys an ACL policy: trimmed and lowercased. openbao v2.6.2
61
+ * vault/policy/policy_store.go:698-700 (`sanitizeName`), applied by SetPolicy (:268), GetPolicy
62
+ * (:378) and DeletePolicy (:562).
63
+ *
64
+ * ⛔ SO `Admin` → `admin` IS THE SAME POLICY, NOT A RENAME. A `replace` there would write it, and then,
65
+ * under `destroy`, delete the old generation, which is that same policy. Every grant it carries
66
+ * would be revoked by a change of case.
67
+ */
68
+ export const policyKey = (name: string): string => name.trim().toLowerCase();
69
+
70
+ /**
71
+ * Whether the declared identity names a different object than the one in state: `true` → moved (the
72
+ * diff asks `judgeMove`, which also reads the target); `false` → the same object; `undefined` → not
73
+ * knowable yet, because the declared side is still an Output. `key` is how the SERVER keys the object (`policyKey`); the default is exact,
74
+ * which is right for a mount path (vault/routing/router.go folds no case) and for both plugins'
75
+ * roles (each stores `roles/<name>` verbatim).
76
+ *
77
+ * ⛔ NEVER `replace` ON AN UNKNOWN IDENTITY. The Output may resolve to the same path, and a replace
78
+ * onto the same path deletes, under `destroy`, the object it has just written. The diff defers
79
+ * instead. If the engine then plans `update` and the identity turns out to have changed,
80
+ * `refuseMovedUpdate` stops reconcile before it writes anything.
81
+ */
82
+ export const isMoved = (
83
+ stored: string,
84
+ declared: string | undefined,
85
+ key: (identity: string) => string = exact,
86
+ ): boolean | undefined => (declared === undefined ? undefined : key(stored) !== key(declared));
87
+
88
+ /**
89
+ * The role path a resource last wrote, or last tried to: its attributes once a write finished, else
90
+ * the props of the create or replacement that did not (`output` is undefined for both).
91
+ */
92
+ export const triedRolePath = (
93
+ output: { readonly mount: string; readonly name: string } | undefined,
94
+ olds: unknown,
95
+ rolePath: (mount: string, name: string) => string,
96
+ ): string | undefined =>
97
+ output === undefined ? declaredRolePath(olds, rolePath) : rolePath(output.mount, output.name);
98
+
99
+ /**
100
+ * The diff's first question, asked before `isResolved(news)`: the move from the identity this
101
+ * resource last wrote or tried (`tried`) to the declared one, or undefined when both name the same
102
+ * object or either is still unknown. `pathOf` is the API path an identity is read at.
103
+ *
104
+ * ⛔ A MOVE ONTO AN OBJECT THAT ALREADY EXISTS FAILS THE PLAN. MEASURED 2026-09-21 through the engine
105
+ * (rename-occupied.test.ts): two policies that swapped names under `RemovalPolicy.destroy()` each
106
+ * planned `replace`, each new generation wrote over the other's live policy, and each old
107
+ * generation's delete then removed the name the other had just written. The deploy was green and
108
+ * both policies were gone, every grant revoked. A shift (a → b while b → c), and a move onto the
109
+ * name of a resource leaving the stack, were measured ending the same way. So was reverting a
110
+ * move whose new generation failed: the old generation still holds the name, and its delete runs
111
+ * after the revert has rewritten it. That is why `tried` falls back to the props of an unfinished
112
+ * write.
113
+ * ⚠️ THE DIFF CANNOT SEE THE REMOVAL POLICY, SO THIS REFUSES UNDER `retain` TOO, where a swap, or a
114
+ * move back onto a retained old generation, would have been harmless. The cost is a move in two
115
+ * deploys through a free name, or removing the target by hand. The alternative is a green deploy
116
+ * that deletes what it has just written.
117
+ * ★ ONE PLAN-TIME READ, OF A PATH THE NEW GENERATION'S RECONCILE READS ANYWAY. A 404, a missing mount
118
+ * included, is free; a refused read fails the plan, as any other diff read does.
119
+ */
120
+ export const judgeMove = (
121
+ family: string,
122
+ tried: string | undefined,
123
+ declared: string | undefined,
124
+ pathOf: (identity: string) => string,
125
+ key: (identity: string) => string = exact,
126
+ ) =>
127
+ Effect.gen(function* () {
128
+ if (tried === undefined || declared === undefined || key(tried) === key(declared)) {
129
+ return undefined;
130
+ }
131
+ if ((yield* baoRead(pathOf(declared))) === undefined) return { from: tried, to: declared };
132
+ return yield* Effect.die(
133
+ new Error(
134
+ `${family}: ${tried} → ${declared} would land on an object that already exists at ` +
135
+ `${declared}. Under RemovalPolicy.destroy() a resource moving off that name (a swap, a ` +
136
+ 'shift, or a reverted move that did not finish) deletes it after this one writes it. ' +
137
+ 'Nothing was written. Move through a name nothing holds, in two deploys, or remove ' +
138
+ `${declared} by hand first.`,
139
+ ),
140
+ );
141
+ });
142
+
143
+ /**
144
+ * Reconcile's guard: an `update` whose prior attributes name another object.
145
+ *
146
+ * ★ REACHED ONLY WHEN THE DIFF COULD NOT SEE THE NEW IDENTITY at plan time. A fresh create, and the
147
+ * new generation of a `replace`, both reach reconcile with `output` undefined (Apply.ts passes
148
+ * `output: attr`, which is empty for a new generation). An `update` reaches it with the previous
149
+ * generation's attributes.
150
+ * ★ THE FAILED DEPLOY SETTLES ITSELF. Apply has already committed the row as `updating`, with the new
151
+ * props and the OLD attributes. By the next plan the upstream Output has landed, so the diff sees
152
+ * both names and answers `replace` (or refuses, if the new name is already taken: `judgeMove`).
153
+ * The old object is then deleted, or retained, by the removal policy, with no hand repair.
154
+ */
155
+ export const refuseMovedUpdate = (family: string, from: string, to: string) =>
156
+ Effect.die(
157
+ new Error(
158
+ `${family}: planned as an update, but its identity moved from ${from} to ${to}. Writing ` +
159
+ `${to} now would leave ${from} live with no state record. Nothing was written. Run the ` +
160
+ 'deploy again: once the value resolves at plan time it plans as a replace.',
161
+ ),
162
+ );