anhedral 0.10.1 → 0.11.1

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 (183) hide show
  1. package/README.md +79 -124
  2. package/assets/patches/LICENSE.braces +21 -0
  3. package/assets/patches/LICENSE.node-forge +50 -0
  4. package/assets/patches/audit-deps.mjs +167 -0
  5. package/assets/patches/braces@3.0.3.patch +127 -0
  6. package/assets/patches/node-forge@1.4.0.patch +41 -0
  7. package/dist/auth-schema.js +3 -3
  8. package/dist/bin.js +284 -163
  9. package/dist/capabilities.d.ts +4 -4
  10. package/dist/capabilities.js +6 -2
  11. package/dist/capability-contract.d.ts +47 -0
  12. package/dist/capability-contract.js +153 -0
  13. package/dist/catalog-model.d.ts +24 -0
  14. package/dist/catalog-model.js +1 -0
  15. package/dist/catalog-registration.d.ts +16 -0
  16. package/dist/catalog-registration.js +22 -0
  17. package/dist/catalog-snapshot.d.ts +5 -0
  18. package/dist/catalog-snapshot.js +97 -0
  19. package/dist/cli-arguments.d.ts +16 -0
  20. package/dist/cli-arguments.js +115 -0
  21. package/dist/cli-output.d.ts +8 -0
  22. package/dist/cli-output.js +236 -0
  23. package/dist/cloudflare.d.ts +14 -3
  24. package/dist/cloudflare.js +196 -36
  25. package/dist/command-schema.d.ts +21 -0
  26. package/dist/command-schema.js +418 -0
  27. package/dist/delivery.d.ts +12 -5
  28. package/dist/delivery.js +173 -39
  29. package/dist/dependencies.d.ts +24 -0
  30. package/dist/dependencies.js +48 -0
  31. package/dist/dependency-patches.d.ts +7 -0
  32. package/dist/dependency-patches.js +125 -0
  33. package/dist/index.d.ts +26 -1
  34. package/dist/index.js +17 -1
  35. package/dist/inspector-model.d.ts +123 -0
  36. package/dist/inspector-model.js +1 -0
  37. package/dist/integration-service-readers.d.ts +13 -0
  38. package/dist/integration-service-readers.js +173 -0
  39. package/dist/lifecycle-model.d.ts +15 -0
  40. package/dist/lifecycle-model.js +20 -0
  41. package/dist/lifecycle.d.ts +11 -0
  42. package/dist/lifecycle.js +91 -0
  43. package/dist/mobile-delivery.d.ts +100 -0
  44. package/dist/mobile-delivery.js +319 -0
  45. package/dist/neon-service-data.d.ts +8 -0
  46. package/dist/neon-service-data.js +117 -0
  47. package/dist/platforms/mobile.js +8 -5
  48. package/dist/pnpm-policy.d.ts +2 -2
  49. package/dist/pnpm-policy.js +19 -45
  50. package/dist/project-catalog.d.ts +41 -0
  51. package/dist/project-catalog.js +288 -0
  52. package/dist/project-config.d.ts +14 -0
  53. package/dist/project-config.js +89 -0
  54. package/dist/project-inspector.d.ts +4 -0
  55. package/dist/project-inspector.js +702 -0
  56. package/dist/project-lifecycle.d.ts +25 -0
  57. package/dist/project-lifecycle.js +57 -0
  58. package/dist/project-state.d.ts +22 -1
  59. package/dist/project-state.js +361 -27
  60. package/dist/provider-auth.d.ts +41 -0
  61. package/dist/provider-auth.js +209 -0
  62. package/dist/provider-readiness.js +27 -10
  63. package/dist/providers/adapters.d.ts +17 -0
  64. package/dist/providers/adapters.js +272 -0
  65. package/dist/providers/api.d.ts +29 -0
  66. package/dist/providers/api.js +253 -0
  67. package/dist/providers/config.d.ts +15 -0
  68. package/dist/providers/config.js +182 -0
  69. package/dist/providers/definitions.d.ts +318 -0
  70. package/dist/providers/definitions.js +127 -0
  71. package/dist/providers/provision.d.ts +24 -0
  72. package/dist/providers/provision.js +76 -0
  73. package/dist/providers/receipts.d.ts +20 -0
  74. package/dist/providers/receipts.js +66 -0
  75. package/dist/providers/recovery-verification.d.ts +7 -0
  76. package/dist/providers/recovery-verification.js +112 -0
  77. package/dist/providers/recovery.d.ts +30 -0
  78. package/dist/providers/recovery.js +34 -0
  79. package/dist/providers/runtime.d.ts +10 -0
  80. package/dist/providers/runtime.js +254 -0
  81. package/dist/providers/schema.d.ts +28 -0
  82. package/dist/providers/schema.js +49 -0
  83. package/dist/providers/state.d.ts +55 -0
  84. package/dist/providers/state.js +289 -0
  85. package/dist/provision.d.ts +10 -1
  86. package/dist/provision.js +91 -4
  87. package/dist/r2-service-data.d.ts +2 -0
  88. package/dist/r2-service-data.js +136 -0
  89. package/dist/readiness.js +9 -13
  90. package/dist/registry/add.d.ts +6 -0
  91. package/dist/registry/add.js +93 -22
  92. package/dist/registry/commands.d.ts +3 -2
  93. package/dist/registry/commands.js +52 -15
  94. package/dist/registry/options.d.ts +1 -1
  95. package/dist/registry/options.js +5 -4
  96. package/dist/registry/preview.d.ts +11 -0
  97. package/dist/registry/preview.js +91 -0
  98. package/dist/registry/receipt.d.ts +1 -0
  99. package/dist/registry/receipt.js +19 -4
  100. package/dist/registry/resolve.js +5 -1
  101. package/dist/registry/usage.d.ts +10 -0
  102. package/dist/registry/usage.js +18 -37
  103. package/dist/render.d.ts +2 -0
  104. package/dist/render.js +6 -0
  105. package/dist/runtime-policy.d.ts +4 -0
  106. package/dist/runtime-policy.js +21 -0
  107. package/dist/scaffold/auth.js +3 -19
  108. package/dist/scaffold/bootstrap.js +2 -2
  109. package/dist/scaffold/compose.js +9 -3
  110. package/dist/scaffold/database.js +107 -25
  111. package/dist/scaffold/documentation.js +18 -13
  112. package/dist/scaffold/lint.d.ts +4 -0
  113. package/dist/scaffold/lint.js +56 -0
  114. package/dist/scaffold/neon-realtime.d.ts +2 -0
  115. package/dist/scaffold/neon-realtime.js +97 -0
  116. package/dist/scaffold/stack-documentation.js +1 -1
  117. package/dist/scaffold/void.d.ts +4 -0
  118. package/dist/scaffold/void.js +256 -0
  119. package/dist/scaffold/web.js +7 -1
  120. package/dist/scaffold/workspace.js +127 -25
  121. package/dist/service-deletion.d.ts +29 -0
  122. package/dist/service-deletion.js +195 -0
  123. package/dist/service-descriptor.d.ts +10 -0
  124. package/dist/service-descriptor.js +78 -0
  125. package/dist/service-model.d.ts +49 -0
  126. package/dist/service-model.js +8 -0
  127. package/dist/service-operations.d.ts +29 -0
  128. package/dist/service-operations.js +78 -0
  129. package/dist/service-readers.d.ts +8 -0
  130. package/dist/service-readers.js +247 -0
  131. package/dist/services-command.d.ts +39 -0
  132. package/dist/services-command.js +100 -0
  133. package/dist/ship.d.ts +348 -0
  134. package/dist/ship.js +237 -0
  135. package/dist/stack-registry.d.ts +4 -2
  136. package/dist/stack-registry.js +48 -12
  137. package/dist/standard.d.ts +2 -1
  138. package/dist/standard.js +33 -14
  139. package/dist/transaction.d.ts +2 -0
  140. package/dist/transaction.js +10 -0
  141. package/dist/util.js +17 -2
  142. package/dist/vercel.d.ts +5 -3
  143. package/dist/vercel.js +96 -14
  144. package/dist/version.d.ts +1 -1
  145. package/dist/version.js +1 -1
  146. package/dist/vinext.d.ts +1 -0
  147. package/dist/vinext.js +13 -1
  148. package/dist/void-execution.d.ts +10 -0
  149. package/dist/void-execution.js +94 -0
  150. package/dist/void-migrations.d.ts +6 -0
  151. package/dist/void-migrations.js +110 -0
  152. package/dist/void-state.d.ts +16 -0
  153. package/dist/void-state.js +65 -0
  154. package/dist/void.d.ts +3 -0
  155. package/dist/void.js +5 -0
  156. package/docs/cli-design.md +67 -0
  157. package/docs/delivery-workflow.md +32 -17
  158. package/docs/plugin-ui.md +102 -0
  159. package/docs/provider-configuration.md +116 -0
  160. package/docs/stack-standard.md +175 -0
  161. package/docs/void-verification.md +185 -0
  162. package/package.json +29 -23
  163. package/assets/anhedral-cli-init-technical.svg +0 -322
  164. package/assets/anhedral-cli-init.svg +0 -322
  165. package/assets/anhedral-mark.svg +0 -4
  166. package/assets/anhedral.svg +0 -4
  167. package/assets/favicon.ico +0 -0
  168. package/assets/security/LICENSES.txt +0 -63
  169. package/assets/security/audit-deps.mjs +0 -300
  170. package/assets/security/braces-regression.mjs +0 -102
  171. package/assets/security/braces@3.0.3.patch +0 -285
  172. package/assets/security/decode-uri-component@0.2.2.patch +0 -149
  173. package/assets/security/decoder-regression.mjs +0 -37
  174. package/assets/security/forge-regression.mjs +0 -46
  175. package/assets/security/manifest.json +0 -53
  176. package/assets/security/node-forge@1.4.0.patch +0 -26
  177. package/dist/managed-hosting.d.ts +0 -49
  178. package/dist/managed-hosting.js +0 -373
  179. package/dist/security-backports.d.ts +0 -3
  180. package/dist/security-backports.js +0 -26
  181. package/docs/application-stack-standard.md +0 -104
  182. package/docs/managed-hosting-architecture.md +0 -87
  183. package/docs/sponsorships.md +0 -25
@@ -0,0 +1,289 @@
1
+ import path from 'node:path';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs';
4
+ import { readBoundedFile, MAX_PROJECT_JSON_BYTES } from '../bounded-file.js';
5
+ import { atomicJson } from '../project-state.js';
6
+ import { digest, object, ProviderRequestError } from './api.js';
7
+ import { verifyRecoveredResource } from './recovery-verification.js';
8
+ import { splitReceipt, validReceipt, validCredentials, restoreReceipt, } from './receipts.js';
9
+ import { INTEGRATION_PROVIDERS, } from './config.js';
10
+ function validDescriptor(value) {
11
+ return (record(value) &&
12
+ Object.keys(value).every((key) => ['key', 'route'].includes(key)) &&
13
+ typeof value.key === 'string' &&
14
+ /^(project|application|domain|web-app|ios-app|android-app|sending-key|webhook|service-account|client-key)$/.test(value.key) &&
15
+ typeof value.route === 'string' &&
16
+ value.route.length <= 1024 &&
17
+ /^\/[a-zA-Z0-9_/-]+$/.test(value.route) &&
18
+ !value.route.includes('//'));
19
+ }
20
+ function record(value) {
21
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
22
+ }
23
+ /** Validate saved operations before trusting their replay protection or resource values. */
24
+ function validState(value) {
25
+ if (!record(value) ||
26
+ value.schemaVersion !== 2 ||
27
+ Object.keys(value).some((key) => !['schemaVersion', 'providers'].includes(key)) ||
28
+ !record(value.providers))
29
+ return false;
30
+ return Object.entries(value.providers).every(([id, provider]) => {
31
+ if (!INTEGRATION_PROVIDERS.includes(id) ||
32
+ !record(provider) ||
33
+ Object.keys(provider).some((key) => !['config', 'operations'].includes(key)) ||
34
+ typeof provider.config !== 'string' ||
35
+ !/^[a-f0-9]{64}$/.test(provider.config) ||
36
+ !record(provider.operations))
37
+ return false;
38
+ return Object.entries(provider.operations).every(([key, operation]) => {
39
+ if (!/^[a-f0-9]{64}$/.test(key) ||
40
+ !record(operation) ||
41
+ Object.keys(operation).some((field) => !['status', 'value', 'credentialFields', 'descriptor'].includes(field)))
42
+ return false;
43
+ if (!validDescriptor(operation.descriptor))
44
+ return false;
45
+ if (operation.status === 'pending')
46
+ return !Object.hasOwn(operation, 'value') && !Object.hasOwn(operation, 'credentialFields');
47
+ if (operation.status !== 'complete' || !record(operation.value))
48
+ return false;
49
+ return (validReceipt(id, operation.value) &&
50
+ (operation.credentialFields === undefined ||
51
+ (Array.isArray(operation.credentialFields) &&
52
+ new Set(operation.credentialFields).size === operation.credentialFields.length &&
53
+ operation.credentialFields.every((field) => typeof field === 'string' &&
54
+ validCredentials(id, { [field]: 'validation-placeholder' })))));
55
+ });
56
+ });
57
+ }
58
+ export async function privateStateDirectory(root, run) {
59
+ root = realpathSync(root);
60
+ const directory = path.join(root, '.anhedral');
61
+ if (existsSync(directory) &&
62
+ (lstatSync(directory).isSymbolicLink() || !lstatSync(directory).isDirectory()))
63
+ throw new Error('Provider state directory must be a regular directory.');
64
+ const environment = { ...process.env, CI: '1', NO_COLOR: '1' };
65
+ if (realpathSync((await run('git', ['rev-parse', '--show-toplevel'], root, environment)).trim()) !==
66
+ root)
67
+ throw new Error('Provider configuration requires its own application repository.');
68
+ for (const file of [
69
+ '.anhedral/providers.json',
70
+ '.anhedral/provider-credentials.json',
71
+ '.anhedral/runtime.json',
72
+ ]) {
73
+ if ((await run('git', ['ls-files', '--', file], root, environment)).trim())
74
+ throw new Error('Provider state must not be tracked.');
75
+ if ((await run('git', ['check-ignore', '--no-index', '--', file], root, environment)).trim() !==
76
+ file)
77
+ throw new Error('Ignore .anhedral/ before provisioning providers.');
78
+ }
79
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
80
+ if (realpathSync(directory) !== directory)
81
+ throw new Error('Provider state directory escapes the project.');
82
+ return directory;
83
+ }
84
+ function validCredentialsState(value) {
85
+ return (record(value) &&
86
+ value.schemaVersion === 1 &&
87
+ !Object.keys(value).some((key) => !['schemaVersion', 'providers'].includes(key)) &&
88
+ record(value.providers) &&
89
+ Object.entries(value.providers).every(([id, operations]) => INTEGRATION_PROVIDERS.includes(id) &&
90
+ record(operations) &&
91
+ Object.entries(operations).every(([key, entries]) => /^[a-f0-9]{64}$/.test(key) && validCredentials(id, entries))));
92
+ }
93
+ function privateJson(file) {
94
+ const stat = lstatSync(file);
95
+ if (!stat.isFile() || stat.isSymbolicLink())
96
+ throw new Error('Provider state must be a regular private file.');
97
+ if (process.platform !== 'win32' && stat.mode & 0o077)
98
+ throw new Error('Provider state contains credentials; restrict its permissions to 0600.');
99
+ try {
100
+ return JSON.parse(readBoundedFile(file, MAX_PROJECT_JSON_BYTES).toString('utf8'));
101
+ }
102
+ catch {
103
+ throw new Error('Invalid provider state.');
104
+ }
105
+ }
106
+ export function readProviderStateStatus(directory) {
107
+ const file = path.join(directory, 'providers.json');
108
+ if (!existsSync(file))
109
+ return { schemaVersion: 2, providers: [] };
110
+ if (lstatSync(directory).isSymbolicLink() || !lstatSync(directory).isDirectory())
111
+ throw new Error('Provider state directory must be a regular private directory.');
112
+ const state = privateJson(file);
113
+ if (!validState(state))
114
+ throw new Error('Invalid provider state.');
115
+ return {
116
+ schemaVersion: 2,
117
+ providers: Object.entries(state.providers).map(([id, provider]) => ({
118
+ provider: id,
119
+ operations: Object.entries(provider.operations).map(([operation, saved]) => ({
120
+ operation,
121
+ status: saved.status,
122
+ ...(saved.value ? { resources: saved.value } : {}),
123
+ descriptor: saved.descriptor,
124
+ recovery: ['sending-key', 'webhook', 'service-account'].includes(saved.descriptor.key)
125
+ ? 'requires-one-time-credential'
126
+ : ['project', 'application', 'domain', 'web-app', 'ios-app', 'android-app'].includes(saved.descriptor.key)
127
+ ? 'verified-resource'
128
+ : 'unsupported-operation',
129
+ })),
130
+ })),
131
+ };
132
+ }
133
+ /** Store credentials before completing a minimal receipt. A crash leaves a pending
134
+ * operation, never permission to replay a provider mutation with an unknown outcome. */
135
+ export class ProvisioningState {
136
+ write;
137
+ file;
138
+ credentialsFile;
139
+ state;
140
+ credentials;
141
+ constructor(directory, write = atomicJson) {
142
+ this.write = write;
143
+ if (lstatSync(directory).isSymbolicLink() || !lstatSync(directory).isDirectory())
144
+ throw new Error('Provider state directory must be a regular private directory.');
145
+ directory = realpathSync(directory);
146
+ this.file = path.join(directory, 'providers.json');
147
+ this.credentialsFile = path.join(directory, 'provider-credentials.json');
148
+ const credentials = existsSync(this.credentialsFile)
149
+ ? privateJson(this.credentialsFile)
150
+ : { schemaVersion: 1, providers: {} };
151
+ if (!validCredentialsState(credentials))
152
+ throw new Error('Invalid provider credential state.');
153
+ this.credentials = credentials;
154
+ const state = existsSync(this.file)
155
+ ? privateJson(this.file)
156
+ : { schemaVersion: 2, providers: {} };
157
+ if (!validState(state))
158
+ throw new Error('Invalid provider state.');
159
+ this.state = state;
160
+ this.assertCredentials();
161
+ }
162
+ assertCredentials() {
163
+ for (const [id, provider] of Object.entries(this.state.providers)) {
164
+ for (const [operation, saved] of Object.entries(provider.operations)) {
165
+ const credentials = this.credentials.providers[id]?.[operation] ?? {};
166
+ if (saved.credentialFields?.some((field) => !credentials[field]))
167
+ throw new Error('Provider creation credentials are missing. Restore private state before retrying.');
168
+ }
169
+ }
170
+ }
171
+ retainCredentials(id, operation, entries) {
172
+ if (!Object.keys(entries).length)
173
+ return;
174
+ const provider = (this.credentials.providers[id] ??= {});
175
+ const previous = provider[operation];
176
+ // Compare the private credential records directly; credential values must not
177
+ // flow through the SHA-256 helper used for public operation fingerprints.
178
+ if (previous && !isDeepStrictEqual(previous, entries))
179
+ throw new Error('Provider credential state conflicts with the saved creation result.');
180
+ provider[operation] = entries;
181
+ }
182
+ /** No configurations, credentials, provider payloads or mutation bodies in status. */
183
+ status() {
184
+ return {
185
+ schemaVersion: 2,
186
+ providers: Object.entries(this.state.providers).map(([id, provider]) => ({
187
+ provider: id,
188
+ operations: Object.entries(provider.operations).map(([operation, saved]) => ({
189
+ operation,
190
+ status: saved.status,
191
+ resources: saved.value ?? {},
192
+ })),
193
+ })),
194
+ };
195
+ }
196
+ context(id, settings) {
197
+ const hash = digest(settings);
198
+ const saved = this.state.providers[id];
199
+ if (saved && saved.config !== hash)
200
+ throw new Error(`${id}: desired configuration changed. Reconcile saved resource IDs before changing provider state.`);
201
+ if (!saved)
202
+ this.state.providers[id] = { config: hash, operations: {} };
203
+ }
204
+ async recoverResource(id, operation, resource, settings, api, beforeCommit = () => { }) {
205
+ this.context(id, settings);
206
+ const provider = this.state.providers[id];
207
+ const saved = provider.operations[operation];
208
+ if (!saved || saved.status !== 'pending')
209
+ throw new Error('Only an explicitly identified pending provider operation can be reconciled.');
210
+ const receipt = await verifyRecoveredResource(id, saved.descriptor, resource, settings, api);
211
+ beforeCommit();
212
+ const complete = {
213
+ status: 'complete',
214
+ descriptor: saved.descriptor,
215
+ value: receipt,
216
+ };
217
+ provider.operations[operation] = complete;
218
+ try {
219
+ this.write(this.file, this.state);
220
+ }
221
+ catch (error) {
222
+ provider.operations[operation] = saved;
223
+ throw error;
224
+ }
225
+ return {
226
+ provider: id,
227
+ operation,
228
+ status: 'complete',
229
+ resources: receipt,
230
+ mutation: 'local-receipt-only',
231
+ };
232
+ }
233
+ async create(id, key, api, route, body) {
234
+ const state = this.state.providers[id];
235
+ if (!state)
236
+ throw new Error('Select a provider configuration before creating resources.');
237
+ const operation = digest({ key, route, body });
238
+ const saved = state.operations[operation];
239
+ if (saved?.status === 'complete')
240
+ return restoreReceipt(saved.value, this.credentials.providers[id]?.[operation] ?? {});
241
+ if (saved)
242
+ throw new Error(`${id}: interrupted ${key} creation has an unknown outcome. Inspect the provider and reconcile the saved operation before retrying.`);
243
+ const descriptor = { key, route };
244
+ if (!validDescriptor(descriptor))
245
+ throw new Error('Unsupported provider operation descriptor.');
246
+ state.operations[operation] = { status: 'pending', descriptor };
247
+ this.write(this.file, this.state);
248
+ let value;
249
+ try {
250
+ value = object(await api(route, 'POST', body, operation));
251
+ }
252
+ catch (error) {
253
+ if (error instanceof ProviderRequestError && error.rejected) {
254
+ delete state.operations[operation];
255
+ this.write(this.file, this.state);
256
+ }
257
+ throw error;
258
+ }
259
+ const { receipt, credentials } = splitReceipt(id, value);
260
+ const expected = id === 'resend' && key === 'sending-key'
261
+ ? 'token'
262
+ : id === 'stripe' && key === 'webhook'
263
+ ? 'secret'
264
+ : id === 'openai' && key === 'service-account'
265
+ ? 'api_key'
266
+ : undefined;
267
+ if (expected && !credentials[expected])
268
+ throw new Error('Provider omitted the one-time creation credential. Inspect the pending operation before retrying.');
269
+ this.retainCredentials(id, operation, credentials);
270
+ if (Object.keys(credentials).length)
271
+ this.write(this.credentialsFile, this.credentials);
272
+ state.operations[operation] = {
273
+ status: 'complete',
274
+ descriptor,
275
+ value: receipt,
276
+ ...(Object.keys(credentials).length
277
+ ? { credentialFields: Object.keys(credentials) }
278
+ : {}),
279
+ };
280
+ try {
281
+ this.write(this.file, this.state);
282
+ }
283
+ catch (error) {
284
+ state.operations[operation] = { status: 'pending', descriptor };
285
+ throw error;
286
+ }
287
+ return restoreReceipt(receipt, credentials);
288
+ }
289
+ }
@@ -1,7 +1,7 @@
1
1
  import { type DeliveryRunner } from './project-state.js';
2
2
  import { type CloudflareRequest } from './cloudflare.js';
3
3
  interface Resource {
4
- kind: 'd1' | 'r2' | 'kv' | 'queue';
4
+ kind: 'd1' | 'r2' | 'kv' | 'queue' | 'stream';
5
5
  name: string;
6
6
  id?: string;
7
7
  target: string;
@@ -23,6 +23,7 @@ export declare function provisionApplication(root: string, dryRun?: boolean, run
23
23
  name: string;
24
24
  id: string;
25
25
  reused: boolean;
26
+ createdByProject: boolean;
26
27
  }[];
27
28
  state: string;
28
29
  externalIntegrations: string[];
@@ -32,6 +33,14 @@ export declare function provisionApplication(root: string, dryRun?: boolean, run
32
33
  accountId: string | null;
33
34
  resources: Resource[];
34
35
  externalIntegrations: string[];
36
+ } | {
37
+ mutation: boolean;
38
+ writer: "void";
39
+ deferredToDeployment: boolean;
40
+ projectId: string;
41
+ accountId: string | null;
42
+ resources: Resource[];
43
+ externalIntegrations: string[];
35
44
  }>;
36
45
  /** Reconcile committed identities against the customer account without creating resources or rewriting configuration. */
37
46
  export declare function inspectApplicationResources(root: string, request: CloudflareRequest): Promise<{
package/dist/provision.js CHANGED
@@ -1,5 +1,7 @@
1
- import { readFileSync, realpathSync, writeFileSync } from 'node:fs';
1
+ import { assertNoDeletedServices } from './service-deletion.js';
2
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
2
3
  import path from 'node:path';
4
+ import { readBoundedFile } from './bounded-file.js';
3
5
  import { applyEdits, modify } from 'jsonc-parser';
4
6
  import { atomicJson, authenticate, defaultRunner, environment, readApplication, readConfig, targetDirectory, withApplicationLock, } from './project-state.js';
5
7
  import { cloudflareRequest, listCloudflare } from './cloudflare.js';
@@ -8,9 +10,28 @@ const resourceTypes = {
8
10
  r2: { endpoint: '/r2/buckets', nameField: 'name', idField: 'name' },
9
11
  kv: { endpoint: '/storage/kv/namespaces', nameField: 'title', idField: 'id' },
10
12
  queue: { endpoint: '/queues', nameField: 'queue_name', idField: 'queue_id' },
13
+ stream: { endpoint: '/pipelines/v1/streams', nameField: 'name', idField: 'id' },
11
14
  };
12
15
  async function listResources(request, kind) {
13
16
  const { endpoint } = resourceTypes[kind];
17
+ if (kind === 'stream') {
18
+ const streams = [];
19
+ let bytes = 0;
20
+ for (let page = 0; page < 1000; page++) {
21
+ const response = await request('GET', `${endpoint}?page=${page}&per_page=100`);
22
+ if (!Array.isArray(response.result))
23
+ throw new Error('Unsupported stream listing.');
24
+ if (response.result.some((item) => !item || typeof item !== 'object' || Array.isArray(item)))
25
+ throw new Error('Unsupported stream resource.');
26
+ streams.push(...response.result);
27
+ bytes += Buffer.byteLength(JSON.stringify(response.result));
28
+ if (streams.length > 10_000 || bytes > 10 * 1024 * 1024)
29
+ throw new Error('Stream listing exceeded collection limit; select resource IDs explicitly.');
30
+ if (response.result.length < 100)
31
+ return streams;
32
+ }
33
+ throw new Error('Stream listing exceeded pagination limit.');
34
+ }
14
35
  if (kind !== 'r2')
15
36
  return listCloudflare(request, endpoint);
16
37
  const value = (await request('GET', endpoint)).result;
@@ -18,6 +39,15 @@ async function listResources(request, kind) {
18
39
  throw new Error('Unsupported or truncated R2 bucket listing; select resources explicitly with provider tooling.');
19
40
  return value.buckets;
20
41
  }
42
+ async function assertPrivateStream(request, id) {
43
+ if (!/^[a-f0-9]{32}$/i.test(id))
44
+ throw new Error('Invalid Basin stream ID.');
45
+ const stream = (await request('GET', `${resourceTypes.stream.endpoint}/${id}`)).result;
46
+ if (stream?.http?.enabled !== false ||
47
+ stream.worker_binding?.enabled !== true ||
48
+ stream.format?.type !== 'json')
49
+ throw new Error('Basin stream must use a private Worker binding with JSON events and HTTP ingestion disabled.');
50
+ }
21
51
  /** Provisioning and recovery use the same independently verified private-storage policy. */
22
52
  async function assertPrivateBucket(request, name) {
23
53
  const endpoint = `${resourceTypes.r2.endpoint}/${encodeURIComponent(name)}/domains`;
@@ -79,22 +109,44 @@ export function planProvisioning(root) {
79
109
  target: target.id,
80
110
  });
81
111
  }
112
+ if (config.pipelines !== undefined) {
113
+ if (!Array.isArray(config.pipelines))
114
+ throw new Error('Invalid Basin stream bindings.');
115
+ config.pipelines.forEach((entry, index) => {
116
+ if (!entry ||
117
+ typeof entry.binding !== 'string' ||
118
+ typeof entry.stream !== 'string' ||
119
+ entry.pipeline)
120
+ throw new Error('Use explicit Basin stream bindings.');
121
+ resources.push({
122
+ kind: 'stream',
123
+ name: resourceName(`${project.name}-${entry.binding.toLowerCase()}`),
124
+ target: target.id,
125
+ id: entry.stream.startsWith('REPLACE_WITH_') ? undefined : entry.stream,
126
+ field: ['pipelines', index, 'stream'],
127
+ });
128
+ });
129
+ }
82
130
  }
83
131
  return {
84
132
  projectId: project.id,
85
133
  accountId: project.accountId,
86
134
  resources,
87
- externalIntegrations: ['hyperdrive', 'pipelines'].filter((key) => project.targets.some((target) => key in readConfig(targetDirectory(root, target)))),
135
+ externalIntegrations: ['hyperdrive'].filter((key) => project.targets.some((target) => key in readConfig(targetDirectory(root, target)))),
88
136
  };
89
137
  }
90
138
  export async function provisionApplication(root, dryRun = false, run = defaultRunner, suppliedRequest) {
91
139
  root = realpathSync(root);
92
140
  const plan = planProvisioning(root);
141
+ assertNoDeletedServices(root, plan.resources);
93
142
  if (dryRun)
94
143
  return { ...plan, mutation: false };
144
+ if (readApplication(root).deliveryEngine === 'void')
145
+ return { ...plan, mutation: false, writer: 'void', deferredToDeployment: true };
95
146
  return withApplicationLock(root, async () => {
96
147
  const project = readApplication(root);
97
148
  const plan = planProvisioning(root);
149
+ assertNoDeletedServices(root, plan.resources);
98
150
  const configured = new Map(project.targets.map((target) => {
99
151
  const file = path.join(targetDirectory(root, target), 'wrangler.jsonc');
100
152
  return [file, readFileSync(file, 'utf8')];
@@ -107,6 +159,24 @@ export async function provisionApplication(root, dryRun = false, run = defaultRu
107
159
  await authenticate(root, project, run);
108
160
  const request = suppliedRequest ??
109
161
  (await cloudflareRequest(project, targetDirectory(root, project.targets[0]), run, environment(project)));
162
+ const previousFile = path.join(root, '.anhedral/resources.json');
163
+ let previousResources = [];
164
+ if (existsSync(previousFile)) {
165
+ const previous = JSON.parse(readBoundedFile(previousFile, 256 * 1024).toString('utf8'));
166
+ if (previous.schemaVersion !== 1 ||
167
+ previous.projectId !== project.id ||
168
+ previous.accountId !== project.accountId ||
169
+ !Array.isArray(previous.resources) ||
170
+ previous.resources.length > 500 ||
171
+ previous.resources.some((entry) => !entry ||
172
+ typeof entry !== 'object' ||
173
+ Array.isArray(entry) ||
174
+ !['d1', 'r2', 'kv', 'queue', 'stream'].includes(String(entry.kind)) ||
175
+ ['name', 'id'].some((field) => typeof entry[field] !== 'string') ||
176
+ typeof entry.reused !== 'boolean'))
177
+ throw new Error('Previous resource ownership cannot be verified.');
178
+ previousResources = previous.resources;
179
+ }
110
180
  const receipts = [];
111
181
  const resources = new Map();
112
182
  for (const resource of plan.resources) {
@@ -125,8 +195,16 @@ export async function provisionApplication(root, dryRun = false, run = defaultRu
125
195
  throw new Error('Configured resource ID does not match its account/name; no replacement was created.');
126
196
  assertConfiguration();
127
197
  if (!value)
128
- value = (await request('POST', endpoint, { [nameField]: resource.name }))
129
- .result;
198
+ value = (await request('POST', endpoint, {
199
+ [nameField]: resource.name,
200
+ ...(resource.kind === 'stream'
201
+ ? {
202
+ http: { enabled: false, authentication: true },
203
+ worker_binding: { enabled: true },
204
+ format: { type: 'json', unstructured: true },
205
+ }
206
+ : {}),
207
+ })).result;
130
208
  if (!value || typeof value[idField] !== 'string' || !value[idField])
131
209
  throw new Error('Provider did not return a resource identity; inspect provider state before retrying.');
132
210
  receipt = {
@@ -134,6 +212,11 @@ export async function provisionApplication(root, dryRun = false, run = defaultRu
134
212
  name: resource.name,
135
213
  id: value[idField],
136
214
  reused,
215
+ createdByProject: !reused ||
216
+ previousResources.some((previous) => previous.kind === resource.kind &&
217
+ previous.name === resource.name &&
218
+ previous.id === value[idField] &&
219
+ (previous.createdByProject === true || previous.reused === false)),
137
220
  };
138
221
  resources.set(key, receipt);
139
222
  receipts.push(receipt);
@@ -148,6 +231,8 @@ export async function provisionApplication(root, dryRun = false, run = defaultRu
148
231
  });
149
232
  if (resource.kind === 'r2')
150
233
  await assertPrivateBucket(request, resource.name);
234
+ if (resource.kind === 'stream')
235
+ await assertPrivateStream(request, receipt.id);
151
236
  }
152
237
  assertConfiguration();
153
238
  if (resource.id && receipt.id !== resource.id)
@@ -191,6 +276,8 @@ export async function inspectApplicationResources(root, request) {
191
276
  throw new Error('Committed resource identity differs from the registered account; recovery will not replace it.');
192
277
  if (resource.kind === 'r2')
193
278
  await assertPrivateBucket(request, resource.name);
279
+ if (resource.kind === 'stream')
280
+ await assertPrivateStream(request, id);
194
281
  receipts.push({ kind: resource.kind, name: resource.name, id, target: resource.target });
195
282
  }
196
283
  return { resources: receipts, externalIntegrations: plan.externalIntegrations };
@@ -0,0 +1,2 @@
1
+ import type { ServiceData, ServiceDescriptor } from './service-model.js';
2
+ export declare function browseR2Objects(service: ServiceDescriptor, cursor: string | undefined, env?: NodeJS.ProcessEnv, send?: typeof fetch): Promise<ServiceData>;
@@ -0,0 +1,136 @@
1
+ import { createHash, createHmac } from 'node:crypto';
2
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
3
+ const hmac = (key, value) => createHmac('sha256', key).update(value).digest();
4
+ const encode = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => '%' + char.charCodeAt(0).toString(16).toUpperCase());
5
+ function xmlValue(value) {
6
+ return value.replace(/&(?:amp|lt|gt|quot|apos);/g, (entity) => ({ '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&apos;': "'" })[entity]);
7
+ }
8
+ export async function browseR2Objects(service, cursor, env = process.env, send = fetch) {
9
+ if (service.kind !== 'r2' ||
10
+ !/^[a-f0-9]{32}$/.test(service.accountId) ||
11
+ !service.name ||
12
+ !/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(service.name) ||
13
+ (cursor !== undefined && (cursor.length > 4096 || /[\x00-\x1f\x7f]/.test(cursor))))
14
+ throw new Error('Choose a supported R2 bucket and cursor.');
15
+ const key = env[`ANHEDRAL_R2_ACCESS_KEY_ID_${service.accountId.toUpperCase()}`] ??
16
+ env.ANHEDRAL_R2_ACCESS_KEY_ID;
17
+ const secret = env[`ANHEDRAL_R2_SECRET_ACCESS_KEY_${service.accountId.toUpperCase()}`] ??
18
+ env.ANHEDRAL_R2_SECRET_ACCESS_KEY;
19
+ if (!key ||
20
+ !secret ||
21
+ !/^[a-zA-Z0-9_-]{8,128}$/.test(key) ||
22
+ !/^[\x21-\x7e]{8,256}$/.test(secret))
23
+ throw new Error('Provide scoped read-only R2 S3 credentials for metadata browsing.');
24
+ const host = `${service.accountId}.r2.cloudflarestorage.com`;
25
+ const pathname = `/${service.name}`;
26
+ const params = {
27
+ 'list-type': '2',
28
+ 'max-keys': '25',
29
+ ...(cursor ? { 'continuation-token': cursor } : {}),
30
+ };
31
+ const query = Object.entries(params)
32
+ .sort(([a], [b]) => a.localeCompare(b))
33
+ .map(([name, value]) => `${encode(name)}=${encode(value)}`)
34
+ .join('&');
35
+ const timestamp = new Date().toISOString().replace(/[-:]/g, '').slice(0, 15) + 'Z';
36
+ const date = timestamp.slice(0, 8);
37
+ const payloadHash = hash('');
38
+ const headers = `host:${host}\nx-amz-content-sha256:${payloadHash}\nx-amz-date:${timestamp}\n`;
39
+ const signed = 'host;x-amz-content-sha256;x-amz-date';
40
+ const scope = `${date}/auto/s3/aws4_request`;
41
+ const canonical = `GET\n${pathname}\n${query}\n${headers}\n${signed}\n${payloadHash}`;
42
+ const signingKey = hmac(hmac(hmac(hmac('AWS4' + secret, date), 'auto'), 's3'), 'aws4_request');
43
+ const signature = createHmac('sha256', signingKey)
44
+ .update(`AWS4-HMAC-SHA256\n${timestamp}\n${scope}\n${hash(canonical)}`)
45
+ .digest('hex');
46
+ const controller = new AbortController();
47
+ const timer = setTimeout(() => controller.abort(), 10000);
48
+ try {
49
+ const response = await send(`https://${host}${pathname}?${query}`, {
50
+ method: 'GET',
51
+ redirect: 'error',
52
+ signal: controller.signal,
53
+ headers: {
54
+ Authorization: `AWS4-HMAC-SHA256 Credential=${key}/${scope}, SignedHeaders=${signed}, Signature=${signature}`,
55
+ 'x-amz-date': timestamp,
56
+ 'x-amz-content-sha256': payloadHash,
57
+ },
58
+ });
59
+ if (!response.ok) {
60
+ void response.body?.cancel();
61
+ throw new Error('R2 metadata read requires scoped access and provider availability.');
62
+ }
63
+ const reader = response.body?.getReader();
64
+ if (!reader)
65
+ throw new Error('Empty R2 metadata response.');
66
+ const abort = () => {
67
+ void reader.cancel();
68
+ };
69
+ controller.signal.addEventListener('abort', abort, { once: true });
70
+ const chunks = [];
71
+ let bytes = 0;
72
+ try {
73
+ for (;;) {
74
+ const chunk = await reader.read();
75
+ if (chunk.done)
76
+ break;
77
+ bytes += chunk.value.length;
78
+ if (bytes > 2 * 1024 * 1024 || controller.signal.aborted)
79
+ throw new Error('R2 metadata exceeded its limits.');
80
+ chunks.push(chunk.value);
81
+ }
82
+ }
83
+ catch (error) {
84
+ void reader.cancel().catch(() => undefined);
85
+ throw error;
86
+ }
87
+ finally {
88
+ controller.signal.removeEventListener('abort', abort);
89
+ reader.releaseLock();
90
+ }
91
+ if (controller.signal.aborted)
92
+ throw new Error('R2 metadata request timed out.');
93
+ const xml = Buffer.concat(chunks).toString('utf8');
94
+ if (/<!DOCTYPE|<!ENTITY/i.test(xml) ||
95
+ !/<ListBucketResult(?:\s[^>]*)?>/.test(xml) ||
96
+ !xml.includes('</ListBucketResult>') ||
97
+ !/<IsTruncated>(?:true|false)<\/IsTruncated>/.test(xml) ||
98
+ xmlValue(xml.match(/<Name>([^<]*)<\/Name>/)?.[1] ?? '') !== service.name)
99
+ throw new Error('R2 metadata does not match the selected bucket.');
100
+ const contents = [...xml.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)];
101
+ if (contents.length > 25)
102
+ throw new Error('R2 metadata page exceeded its limit.');
103
+ const rows = contents.map((entry) => {
104
+ const value = entry[1];
105
+ const key = xmlValue(value.match(/<Key>([^<]*)<\/Key>/)?.[1] ?? '');
106
+ const size = Number(value.match(/<Size>(\d+)<\/Size>/)?.[1]);
107
+ const modified = value.match(/<LastModified>([^<]*)<\/LastModified>/)?.[1];
108
+ if (!key ||
109
+ !Number.isSafeInteger(size) ||
110
+ size < 0 ||
111
+ !modified ||
112
+ !Number.isFinite(Date.parse(modified)))
113
+ throw new Error('Unsupported object metadata.');
114
+ return [key.slice(0, 1000), size, modified];
115
+ });
116
+ const nextCursor = xmlValue(xml.match(/<NextContinuationToken>([^<]*)<\/NextContinuationToken>/)?.[1] ?? '');
117
+ const hasMore = xml.includes('<IsTruncated>true</IsTruncated>');
118
+ if (hasMore && (!nextCursor || nextCursor.length > 4096))
119
+ throw new Error('R2 cursor is unavailable.');
120
+ return {
121
+ fetchedAt: new Date().toISOString(),
122
+ columns: ['Object key', 'Size (bytes)', 'Last modified'],
123
+ rows,
124
+ offset: 0,
125
+ hasMore,
126
+ masked: false,
127
+ ...(hasMore ? { nextCursor } : {}),
128
+ };
129
+ }
130
+ catch {
131
+ throw new Error('R2 metadata could not be read. Check selected bucket, read-only S3 credentials, permissions, and response limits.');
132
+ }
133
+ finally {
134
+ clearTimeout(timer);
135
+ }
136
+ }