@di-framework/cli-plugin-platform 6.1.1 → 6.2.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 (43) hide show
  1. package/README.md +259 -2
  2. package/dist/assets/http-adapter.js +6 -6
  3. package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
  4. package/dist/assets/wit/deps/di-framework-pglite/package.wit +175 -0
  5. package/dist/bindings.js +7 -6
  6. package/dist/build.d.ts +31 -0
  7. package/dist/build.js +192 -12
  8. package/dist/console/catalog.js +2 -1
  9. package/dist/console/cluster.d.ts +3 -0
  10. package/dist/console/cluster.js +57 -4
  11. package/dist/control/auth.js +14 -2
  12. package/dist/deploy.d.ts +6 -0
  13. package/dist/deploy.js +27 -5
  14. package/dist/deps.js +1 -1
  15. package/dist/environment-names.d.ts +6 -0
  16. package/dist/environment-names.js +10 -0
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/node-compat/console.js +16 -1
  20. package/dist/node-compat/crypto-subtle.d.ts +6 -0
  21. package/dist/node-compat/crypto-subtle.js +41 -4
  22. package/dist/node-compat/crypto.d.ts +3 -2
  23. package/dist/node-compat/crypto.js +66 -17
  24. package/dist/node-compat/fs.d.ts +24 -2
  25. package/dist/node-compat/fs.js +137 -15
  26. package/dist/node-compat/node-errors.d.ts +20 -0
  27. package/dist/node-compat/node-errors.js +73 -0
  28. package/dist/node-compat/storage.d.ts +3 -3
  29. package/dist/node-compat/wasi-random.d.ts +21 -1
  30. package/dist/node-compat/wasi-random.js +45 -12
  31. package/dist/pglite-encryption.d.ts +79 -0
  32. package/dist/pglite-encryption.js +196 -0
  33. package/dist/pglite.d.ts +153 -0
  34. package/dist/pglite.js +423 -0
  35. package/dist/project.d.ts +18 -0
  36. package/dist/project.js +49 -1
  37. package/dist/secret-admission.d.ts +21 -0
  38. package/dist/secret-admission.js +29 -0
  39. package/dist/wit.d.ts +3 -0
  40. package/dist/wit.js +12 -0
  41. package/dist/workload.d.ts +51 -0
  42. package/dist/workload.js +320 -40
  43. package/package.json +2 -2
package/dist/pglite.js ADDED
@@ -0,0 +1,423 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, posix, resolve } from 'node:path';
5
+ import { CommandFailure } from '@di-framework/cli-extension';
6
+ import { captureKubectl } from './kubernetes.js';
7
+ import { DI_PGLITE_VERSION } from './wit.js';
8
+ export { DI_PGLITE_PACKAGE, DI_PGLITE_VERSION, PGLITE_SOURCE } from './wit.js';
9
+ /**
10
+ * Embedded PostgreSQL provider (`di-framework:pglite`), published by di-framework/platform
11
+ * as `ghcr.io/di-framework/pglite-component`. A guest that imports its `database` interface
12
+ * gets the provider plugged in after componentize; the deployed component is then marked
13
+ * exclusive and given persistent storage, because the engine tolerates exactly one opener
14
+ * of its data directory.
15
+ */
16
+ export const PGLITE_REPOSITORY = 'ghcr.io/di-framework/pglite-component';
17
+ /** Absolute (or cwd-relative) path of a local provider build; wins over the config. */
18
+ export const PGLITE_WASM_ENV = 'DI_FRAMEWORK_PGLITE_WASM';
19
+ /** Root of the CLI's download cache. Defaults to `$XDG_CACHE_HOME/di-framework`. */
20
+ export const CACHE_DIR_ENV = 'DI_FRAMEWORK_CACHE_DIR';
21
+ /** Guest environment entry naming the database root the guest passes to `open`. */
22
+ export const PGLITE_DATA_DIR_ENV = 'DI_PGLITE_DATA_DIR';
23
+ /**
24
+ * `localResources.config` entry the patched tenant host reads (di-framework/platform#140).
25
+ * Components only: platform admission rejects it on the service.
26
+ */
27
+ export const EXCLUSIVE_INSTANCE_KEY = 'di-framework.dev/exclusive-instance';
28
+ export const DEFAULT_PGLITE_STORAGE_MOUNT = '/data';
29
+ /** File name of the provider inside a cache entry. */
30
+ export const PGLITE_WASM_FILE = 'di-framework-pglite.wasm';
31
+ /**
32
+ * Encrypting `wasi:filesystem` layer for the provider (`pglite.encryption`), published by
33
+ * di-framework/platform. The build composes it into the provider with an explicit `wac compose`
34
+ * document (`.di-framework/pglite-encryption.wac`, see `encryptProvider`) before the provider is
35
+ * plugged into the guest, so only the engine sees the encrypted view.
36
+ */
37
+ export const PGLITE_ENCFS_REPOSITORY = 'ghcr.io/di-framework/pglite-encfs';
38
+ /** Absolute (or cwd-relative) path of a local encryption layer build; wins over the config. */
39
+ export const PGLITE_ENCFS_WASM_ENV = 'DI_FRAMEWORK_PGLITE_ENCFS_WASM';
40
+ /** File name of the encryption layer inside a cache entry. */
41
+ export const PGLITE_ENCFS_WASM_FILE = 'di-framework-pglite-encfs.wasm';
42
+ /** The provider with the encryption layer plugged in, as the build plugs it into the guest. */
43
+ export const PGLITE_ENCRYPTED_WASM_FILE = 'di-framework-pglite.encrypted.wasm';
44
+ /**
45
+ * The guest environment variable the encryption layer reads its master key from. It must come
46
+ * from the control Secret, so the project declares it in `controlSecretKeys`.
47
+ */
48
+ export const PGLITE_KEY_ENV = 'DI_PGLITE_KEY';
49
+ const WASM_LAYER_MEDIA_TYPE = 'application/wasm';
50
+ const SHA256_DIGEST = /^sha256:[0-9a-f]{64}$/;
51
+ const DIGEST_REFERENCE = /^([a-z0-9]+(?:[.:-][a-z0-9]+)*(?:\/[a-z0-9]+(?:[._-][a-z0-9]+)*)+)@(.+)$/;
52
+ const CONFIG_KEYS = ['image', 'wasm', 'storageMount', 'dataDir', 'encryption'];
53
+ const ENCRYPTION_KEYS = ['image', 'wasm'];
54
+ export const PGLITE_PROVIDER = {
55
+ label: 'PGlite provider',
56
+ field: 'pglite',
57
+ repository: PGLITE_REPOSITORY,
58
+ localEnv: PGLITE_WASM_ENV,
59
+ file: PGLITE_WASM_FILE,
60
+ };
61
+ export const PGLITE_ENCFS = {
62
+ label: 'PGlite encryption layer',
63
+ field: 'pglite.encryption',
64
+ repository: PGLITE_ENCFS_REPOSITORY,
65
+ localEnv: PGLITE_ENCFS_WASM_ENV,
66
+ file: PGLITE_ENCFS_WASM_FILE,
67
+ };
68
+ function configInvalid(message, configPath) {
69
+ throw new CommandFailure('WASMCLOUD_CONFIG_INVALID', message, 2, { configPath });
70
+ }
71
+ export function parseDigestReference(reference, repository = PGLITE_REPOSITORY) {
72
+ const match = DIGEST_REFERENCE.exec(reference);
73
+ const digest = match?.[2] ?? '';
74
+ if (match === null || !SHA256_DIGEST.test(digest)) {
75
+ throw new Error(`"${reference}" is not pinned by digest. Use ${repository}@sha256:<64 hex>; tags such as :${DI_PGLITE_VERSION} move`);
76
+ }
77
+ return { repository: match[1], digest };
78
+ }
79
+ function absoluteGuestPath(value, label, configPath) {
80
+ if (typeof value !== 'string' || !value.startsWith('/'))
81
+ configInvalid(`pglite.${label} must be an absolute guest path`, configPath);
82
+ const normalized = posix.normalize(value);
83
+ return normalized.length > 1 && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;
84
+ }
85
+ /** `image` must be a digest pin and `wasm` a path; at least one of them is required. */
86
+ function validateProviderSource(entry, configPath, component = PGLITE_PROVIDER) {
87
+ const field = component.field;
88
+ if (entry.image !== undefined) {
89
+ if (typeof entry.image !== 'string')
90
+ configInvalid(`${field}.image must be a string`, configPath);
91
+ try {
92
+ parseDigestReference(entry.image, component.repository);
93
+ }
94
+ catch (error) {
95
+ configInvalid(`${field}.image: ${error.message}`, configPath);
96
+ }
97
+ }
98
+ if (entry.wasm !== undefined && (typeof entry.wasm !== 'string' || entry.wasm.trim() === ''))
99
+ configInvalid(`${field}.wasm must be a non-empty path`, configPath);
100
+ if (entry.image === undefined && entry.wasm === undefined)
101
+ configInvalid(`${field} needs "image" (${component.repository}@sha256:<digest>) or a local "wasm" path`, configPath);
102
+ }
103
+ function parseEncryption(value, configPath, resolveFile) {
104
+ if (value === undefined)
105
+ return undefined;
106
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
107
+ configInvalid('pglite.encryption must be an object', configPath);
108
+ const entry = value;
109
+ const unknown = Object.keys(entry).filter((key) => !ENCRYPTION_KEYS.includes(key));
110
+ if (unknown.length > 0)
111
+ configInvalid(`pglite.encryption has unsupported fields: ${unknown.join(', ')}. Use ${ENCRYPTION_KEYS.join(', ')}`, configPath);
112
+ validateProviderSource(entry, configPath, PGLITE_ENCFS);
113
+ return {
114
+ ...(entry.image === undefined ? {} : { image: entry.image }),
115
+ ...(entry.wasm === undefined ? {} : { wasm: resolveFile(entry.wasm) }),
116
+ };
117
+ }
118
+ /** True when `path` is `directory` or below it (both normalized guest paths). */
119
+ export function isWithin(path, directory) {
120
+ return path === directory || path.startsWith(directory === '/' ? '/' : `${directory}/`);
121
+ }
122
+ /** Validates `pglite` from the config. `resolveFile` keeps `wasm` inside the project. */
123
+ export function parsePgliteConfig(value, configPath, resolveFile) {
124
+ if (value === undefined)
125
+ return undefined;
126
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
127
+ configInvalid('pglite must be an object', configPath);
128
+ const entry = value;
129
+ const unknown = Object.keys(entry).filter((key) => !CONFIG_KEYS.includes(key));
130
+ if (unknown.length > 0)
131
+ configInvalid(`pglite has unsupported fields: ${unknown.join(', ')}. Use ${CONFIG_KEYS.join(', ')}`, configPath);
132
+ validateProviderSource(entry, configPath);
133
+ const storageMount = entry.storageMount === undefined
134
+ ? DEFAULT_PGLITE_STORAGE_MOUNT
135
+ : absoluteGuestPath(entry.storageMount, 'storageMount', configPath);
136
+ const dataDir = entry.dataDir === undefined
137
+ ? posix.join(storageMount, 'pglite')
138
+ : absoluteGuestPath(entry.dataDir, 'dataDir', configPath);
139
+ if (!isWithin(dataDir, storageMount))
140
+ configInvalid(`pglite.dataDir ${dataDir} must be inside storageMount ${storageMount}; only that directory is persistent`, configPath);
141
+ const encryption = parseEncryption(entry.encryption, configPath, resolveFile);
142
+ if (encryption?.image !== undefined) {
143
+ const layer = parseDigestReference(encryption.image, PGLITE_ENCFS_REPOSITORY);
144
+ const provider = entry.image === undefined ? undefined : parseDigestReference(entry.image);
145
+ if (layer.repository === PGLITE_REPOSITORY || layer.repository === provider?.repository)
146
+ configInvalid(`pglite.encryption.image must pin the encryption layer (${PGLITE_ENCFS_REPOSITORY}), not the provider repository ${layer.repository}`, configPath);
147
+ if (layer.digest === provider?.digest)
148
+ configInvalid('pglite.encryption.image pins the same digest as pglite.image', configPath);
149
+ }
150
+ return {
151
+ ...(entry.image === undefined ? {} : { image: entry.image }),
152
+ ...(entry.wasm === undefined ? {} : { wasm: resolveFile(entry.wasm) }),
153
+ storageMount,
154
+ dataDir,
155
+ ...(encryption === undefined ? {} : { encryption }),
156
+ };
157
+ }
158
+ export function cacheRoot(env) {
159
+ const explicit = env[CACHE_DIR_ENV]?.trim();
160
+ if (explicit)
161
+ return resolve(explicit);
162
+ const xdg = env.XDG_CACHE_HOME?.trim();
163
+ return xdg ? join(xdg, 'di-framework') : join(env.HOME ?? homedir(), '.cache', 'di-framework');
164
+ }
165
+ /** Where a digest-pinned provider is cached: `<cache>/oci/sha256/<hex>/`. */
166
+ export function cacheEntry(env, digest) {
167
+ return join(cacheRoot(env), 'oci', 'sha256', digest.slice('sha256:'.length));
168
+ }
169
+ function sha256(bytes) {
170
+ return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
171
+ }
172
+ function failure(code, message, details = {}) {
173
+ return new CommandFailure(code, message, 3, details);
174
+ }
175
+ /**
176
+ * The manifest bytes must hash to the pinned digest; then the single `application/wasm`
177
+ * layer names the blob digest the provider bytes must hash to.
178
+ */
179
+ export function verifyManifest(bytes, image) {
180
+ const { digest } = parseDigestReference(image);
181
+ const actual = sha256(bytes);
182
+ if (actual !== digest)
183
+ throw failure('WASMCLOUD_PGLITE_DIGEST_MISMATCH', `Manifest pulled for ${image} hashes to ${actual}, not the pinned ${digest}`, { image, expected: digest, actual });
184
+ let manifest;
185
+ try {
186
+ manifest = JSON.parse(Buffer.from(bytes).toString('utf8'));
187
+ }
188
+ catch {
189
+ throw failure('WASMCLOUD_PGLITE_MANIFEST_INVALID', `Manifest for ${image} is not JSON`, {
190
+ image,
191
+ });
192
+ }
193
+ if (manifest.manifests !== undefined)
194
+ throw failure('WASMCLOUD_PGLITE_MANIFEST_INVALID', `${image} is an image index; pin the digest of the wasm artifact manifest instead`, { image });
195
+ const layers = (manifest.layers ?? []).filter((layer) => layer.mediaType === WASM_LAYER_MEDIA_TYPE);
196
+ const layer = layers[0];
197
+ if (layers.length !== 1 || typeof layer?.digest !== 'string' || !SHA256_DIGEST.test(layer.digest))
198
+ throw failure('WASMCLOUD_PGLITE_MANIFEST_INVALID', `Manifest for ${image} must have exactly one ${WASM_LAYER_MEDIA_TYPE} layer with a sha256 digest`, { image });
199
+ return layer.digest;
200
+ }
201
+ function isWasm(bytes) {
202
+ return (bytes.length >= 4 &&
203
+ bytes[0] === 0 &&
204
+ bytes[1] === 0x61 &&
205
+ bytes[2] === 0x73 &&
206
+ bytes[3] === 0x6d);
207
+ }
208
+ export function verifyLayer(bytes, image, layerDigest) {
209
+ const actual = sha256(bytes);
210
+ if (actual !== layerDigest)
211
+ throw failure('WASMCLOUD_PGLITE_DIGEST_MISMATCH', `Provider layer of ${image} hashes to ${actual}, not ${layerDigest} from its manifest`, { image, expected: layerDigest, actual });
212
+ if (!isWasm(bytes))
213
+ throw failure('WASMCLOUD_PGLITE_MANIFEST_INVALID', `Provider layer of ${image} is not a WebAssembly binary`, { image });
214
+ }
215
+ /** The verified provider bytes of a cache entry, or undefined when it is absent or stale. */
216
+ function readVerifiedEntry(directory, image, file) {
217
+ const manifestPath = join(directory, 'manifest.json');
218
+ const wasmPath = join(directory, file);
219
+ if (!existsSync(manifestPath) || !existsSync(wasmPath))
220
+ return undefined;
221
+ try {
222
+ const bytes = readFileSync(wasmPath);
223
+ verifyLayer(bytes, image, verifyManifest(readFileSync(manifestPath), image));
224
+ return bytes;
225
+ }
226
+ catch {
227
+ return undefined;
228
+ }
229
+ }
230
+ /** Staging directories older than this were left by a killed build and are removed. */
231
+ export const STALE_STAGING_MS = 24 * 60 * 60 * 1000;
232
+ function sweepStaleStaging(root, now) {
233
+ for (const name of readdirSync(root)) {
234
+ if (!name.startsWith('.pull-'))
235
+ continue;
236
+ const path = join(root, name);
237
+ try {
238
+ if (now - statSync(path).mtimeMs > STALE_STAGING_MS)
239
+ rmSync(path, { recursive: true, force: true });
240
+ }
241
+ catch {
242
+ // Another build removed it first.
243
+ }
244
+ }
245
+ }
246
+ async function oras(deps, args, image, cwd, component) {
247
+ const result = await deps.runCaptured('oras', args, { cwd });
248
+ if (result.exitCode === 0)
249
+ return;
250
+ const reason = (result.stderr || result.stdout).trim();
251
+ const detail = reason ? `: ${reason}` : '';
252
+ throw failure('WASMCLOUD_PGLITE_PULL_FAILED', `oras ${args.slice(0, 2).join(' ')} failed for ${image}${detail}. ` +
253
+ `If the package is private, run \`oras login ghcr.io\`; offline, set ${component.localEnv} or ${component.field}.wasm`, { image, exitCode: String(result.exitCode) });
254
+ }
255
+ /**
256
+ * Stores a verified staging directory as the cache entry. A concurrent build may have
257
+ * stored the same digest first; its entry is used when it verifies.
258
+ */
259
+ function storeEntry(staging, entry, image, bytes, file) {
260
+ mkdirSync(join(entry, '..'), { recursive: true });
261
+ try {
262
+ renameSync(staging, entry);
263
+ return bytes;
264
+ }
265
+ catch (error) {
266
+ const winner = readVerifiedEntry(entry, image, file);
267
+ if (winner !== undefined)
268
+ return winner;
269
+ throw failure('WASMCLOUD_PGLITE_CACHE_CONFLICT', `Could not store ${image} in the cache at ${entry} (${error.code ?? 'unknown error'}), ` +
270
+ `and the entry there does not verify; remove ${entry} and retry`, { image, entry });
271
+ }
272
+ }
273
+ /**
274
+ * Pulls the provider by digest with `oras`, verifying the manifest digest and the layer
275
+ * digest, into the cache. A cached entry is re-verified on every use; a corrupt one is
276
+ * pulled again. Returns the verified bytes, so later readers never see a swapped file.
277
+ */
278
+ export async function pullPgliteComponent(image, io, deps, cwd, component = PGLITE_PROVIDER) {
279
+ const { repository, digest } = parseDigestReference(image, component.repository);
280
+ const entry = cacheEntry(deps.env, digest);
281
+ const cached = readVerifiedEntry(entry, image, component.file);
282
+ if (cached !== undefined) {
283
+ io.stdout.write(`Using cached ${image}\n`);
284
+ return { bytes: cached, source: 'cache', image };
285
+ }
286
+ if (existsSync(entry)) {
287
+ io.stderr.write(`Cached ${image} failed verification; pulling it again\n`);
288
+ rmSync(entry, { recursive: true, force: true });
289
+ }
290
+ if (deps.capture('oras', ['version']) === undefined)
291
+ throw failure('WASMCLOUD_ORAS_REQUIRED', `oras is required to pull ${image}; install it from https://oras.land or set ${component.localEnv} to a local build`, { image, tool: 'oras' });
292
+ const root = cacheRoot(deps.env);
293
+ mkdirSync(root, { recursive: true });
294
+ sweepStaleStaging(root, Date.now());
295
+ const staging = mkdtempSync(join(root, '.pull-'));
296
+ try {
297
+ io.stdout.write(`Pulling ${image}...\n`);
298
+ const manifestPath = join(staging, 'manifest.json');
299
+ await oras(deps, ['manifest', 'fetch', '--output', manifestPath, image], image, cwd, component);
300
+ const layerDigest = verifyManifest(readFileSync(manifestPath), image);
301
+ const stagedWasm = join(staging, component.file);
302
+ await oras(deps, ['blob', 'fetch', '--output', stagedWasm, `${repository}@${layerDigest}`], image, cwd, component);
303
+ const bytes = readFileSync(stagedWasm);
304
+ verifyLayer(bytes, image, layerDigest);
305
+ return {
306
+ bytes: storeEntry(staging, entry, image, bytes, component.file),
307
+ source: 'registry',
308
+ image,
309
+ };
310
+ }
311
+ finally {
312
+ rmSync(staging, { recursive: true, force: true });
313
+ }
314
+ }
315
+ /** Set to `1` to let `deploy` or a CI build use a local, unverified provider. */
316
+ export const ALLOW_LOCAL_PGLITE_ENV = 'DI_FRAMEWORK_ALLOW_LOCAL_PGLITE';
317
+ function readLocalProvider(local, origin, config, io, deps, options, component = PGLITE_PROVIDER) {
318
+ if (!existsSync(local))
319
+ throw failure('WASMCLOUD_PGLITE_PROVIDER_MISSING', `${component.label} ${local} (from ${origin}) does not exist`, { path: local });
320
+ let context;
321
+ if (options.deploy)
322
+ context = 'deploy';
323
+ else if (deps.env.CI)
324
+ context = 'CI';
325
+ if (context !== undefined && deps.env[ALLOW_LOCAL_PGLITE_ENV] !== '1')
326
+ throw failure('WASMCLOUD_PGLITE_LOCAL_REFUSED', `Refusing the unverified local ${component.label} ${local} (from ${origin}) in ${context}; ` +
327
+ `pin "${component.field}.image" by digest, or set ${ALLOW_LOCAL_PGLITE_ENV}=1 to use it anyway`, { path: local, context });
328
+ const bytes = readFileSync(local);
329
+ if (!isWasm(bytes))
330
+ throw failure('WASMCLOUD_PGLITE_PROVIDER_INVALID', `${component.label} ${local} (from ${origin}) is not a WebAssembly binary`, { path: local });
331
+ const replaced = config.image ? ` instead of the pinned ${config.image}` : '';
332
+ io.stderr.write(`Warning: using the local, unverified ${component.label} ${local} (from ${origin})${replaced}\n`);
333
+ return { bytes, source: 'local', path: local };
334
+ }
335
+ /**
336
+ * The provider to compose: `DI_FRAMEWORK_PGLITE_WASM`, then `pglite.wasm`, then the
337
+ * digest-pinned `pglite.image`. Local files are only checked to be WebAssembly, and are
338
+ * refused in a deploy or on CI without `DI_FRAMEWORK_ALLOW_LOCAL_PGLITE=1`.
339
+ */
340
+ export async function resolvePgliteComponent(config, io, deps, projectRoot, options = {}) {
341
+ const fromEnv = deps.env[PGLITE_WASM_ENV]?.trim();
342
+ if (fromEnv)
343
+ return readLocalProvider(resolve(deps.cwd(), fromEnv), PGLITE_WASM_ENV, config, io, deps, options);
344
+ if (config.wasm !== undefined)
345
+ return readLocalProvider(config.wasm, 'pglite.wasm', config, io, deps, options);
346
+ return pullPgliteComponent(config.image, io, deps, projectRoot);
347
+ }
348
+ /**
349
+ * The encryption layer to plug into the provider, resolved like the provider:
350
+ * `DI_FRAMEWORK_PGLITE_ENCFS_WASM`, then `pglite.encryption.wasm`, then the digest-pinned
351
+ * `pglite.encryption.image`, with the same local-file refusal in a deploy or on CI.
352
+ */
353
+ export async function resolvePgliteEncryption(config, io, deps, projectRoot, options = {}) {
354
+ const fromEnv = deps.env[PGLITE_ENCFS_WASM_ENV]?.trim();
355
+ if (fromEnv)
356
+ return readLocalProvider(resolve(deps.cwd(), fromEnv), PGLITE_ENCFS_WASM_ENV, config, io, deps, options, PGLITE_ENCFS);
357
+ if (config.wasm !== undefined)
358
+ return readLocalProvider(config.wasm, 'pglite.encryption.wasm', config, io, deps, options, PGLITE_ENCFS);
359
+ return pullPgliteComponent(config.image, io, deps, projectRoot, PGLITE_ENCFS);
360
+ }
361
+ /**
362
+ * Members of one workload share one storage directory, mounted at each member's own
363
+ * `storageMount`. Two members whose `dataDir` is the same path relative to their mount
364
+ * would open the same database from separate instances, which exclusivity cannot stop.
365
+ */
366
+ export function assertDistinctPgliteRoots(workload, members) {
367
+ const owners = new Map();
368
+ for (const member of members) {
369
+ if (member.workload !== workload || member.pglite === undefined)
370
+ continue;
371
+ const root = posix.relative(member.pglite.storageMount, member.pglite.dataDir);
372
+ const previous = owners.get(root);
373
+ if (previous !== undefined)
374
+ throw new CommandFailure('WASMCLOUD_PGLITE_DATA_DIR_CONFLICT', `${workload}: ${previous} and ${member.applicationName} would open the same PGlite database ` +
375
+ `(<workload storage>/${root || '.'}); members share one storage directory, so give each a different dataDir relative to its storageMount`, 2, { workload, root });
376
+ owners.set(root, member.applicationName);
377
+ }
378
+ }
379
+ /** Tag fragment of the tenant host image that honours the exclusive opt-in (#140). */
380
+ export const EXCLUSIVE_HOST_IMAGE_MARKER = '-exclusive';
381
+ function hasExclusiveTag(image) {
382
+ const tag = image.split('@')[0]?.split('/').pop()?.split(':')[1];
383
+ return tag?.includes(EXCLUSIVE_HOST_IMAGE_MARKER) === true;
384
+ }
385
+ async function hostImages(connection, hostgroup, deps, cwd) {
386
+ const runtime = { ...connection, namespace: `di-runtime-${hostgroup.slice('tenant-'.length)}` };
387
+ const result = await captureKubectl(deps, runtime, ['get', 'pods', '-l', `wasmcloud.com/hostgroup=${hostgroup}`, '-o', 'json'], cwd);
388
+ if (result.exitCode !== 0)
389
+ return undefined;
390
+ try {
391
+ const list = JSON.parse(result.stdout);
392
+ return (list.items ?? []).flatMap((pod) => (pod.spec?.containers ?? []).flatMap((container) => typeof container.image === 'string' ? [container.image] : []));
393
+ }
394
+ catch {
395
+ return undefined;
396
+ }
397
+ }
398
+ /**
399
+ * Stock wash ignores `di-framework.dev/exclusive-instance`: when its pool saturates or an
400
+ * instance drains, it builds a second store, which opens the same data directory. Warn when
401
+ * a tenant host group's image is not the exclusive build; elsewhere the CLI cannot see the
402
+ * host, so say what the opt-in depends on.
403
+ */
404
+ export async function warnIfHostIgnoresExclusive(project, connection, io, deps) {
405
+ if (project.pglite === undefined)
406
+ return;
407
+ const risk = 'Without it a second instance can open the same PGlite data directory and corrupt it';
408
+ const hostgroup = connection.hostgroup;
409
+ if (!hostgroup?.startsWith('tenant-')) {
410
+ const group = hostgroup ?? connection.storageHostgroup ?? 'storage';
411
+ io.stderr.write(`Note: ${project.applicationName} embeds PGlite and is marked exclusive; host group ${group} ` +
412
+ `must run a wash image built with the exclusive patch (tagged *${EXCLUSIVE_HOST_IMAGE_MARKER}). ${risk}.\n`);
413
+ return;
414
+ }
415
+ const images = await hostImages(connection, hostgroup, deps, project.projectRoot);
416
+ if (images?.some(hasExclusiveTag))
417
+ return;
418
+ const seen = images === undefined || images.length === 0
419
+ ? 'could not read its host image'
420
+ : `runs ${images[0]}`;
421
+ io.stderr.write(`Warning: ${project.applicationName} embeds PGlite and is marked exclusive, but host group ${hostgroup} ` +
422
+ `${seen}, which does not look like the exclusive build (tagged *${EXCLUSIVE_HOST_IMAGE_MARKER}, set with the platform's tenantHostImage). ${risk}.\n`);
423
+ }
package/dist/project.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type PgliteConfig } from './pglite.js';
1
2
  import { type WorkloadEntry } from './workload-members.js';
2
3
  export declare const CONFIG_FILE_NAME = "di-framework.config.json";
3
4
  export type WasmcloudProject = {
@@ -36,9 +37,26 @@ export type WasmcloudProject = {
36
37
  * `di-framework.dev/logs: "false"` WorkloadDeployment annotation. Absent means on.
37
38
  */
38
39
  logs?: false;
40
+ /**
41
+ * Embedded PostgreSQL provider composed into the guest, from `"pglite"`. The deployed
42
+ * component is exclusive and gets persistent storage at `storageMount`.
43
+ */
44
+ pglite?: PgliteConfig;
45
+ /**
46
+ * App-owned keys of the `<workload>-control` Secret, from `"controlSecretKeys"`. Deploy keeps
47
+ * them and refuses any other key besides the CLI's own `DI_CONTROL_*` (`writeControlSecret`).
48
+ */
49
+ controlSecretKeys?: string[];
39
50
  };
51
+ /** Why `name` cannot be declared in `controlSecretKeys`, or undefined when it can. */
52
+ export declare function controlSecretKeyProblem(name: unknown): string | undefined;
40
53
  export declare function findUp(startDirectory: string, fileName: string): string | undefined;
41
54
  /** Paths from the config must stay inside the project root. */
42
55
  export declare function resolveInside(projectRoot: string, value: string, label: string, configPath: string): string;
56
+ /**
57
+ * {@link resolveInside}, then the same check on the resolved real path, so a symlink inside
58
+ * the project cannot point outside it. A missing file is left for the caller to report.
59
+ */
60
+ export declare function resolveRealInside(projectRoot: string, value: string, label: string, configPath: string): string;
43
61
  export declare function asWitIdentifier(value: string): string;
44
62
  export declare function loadProject(startDirectory: string): WasmcloudProject;
package/dist/project.js CHANGED
@@ -1,9 +1,43 @@
1
- import { accessSync, constants, existsSync, readFileSync } from 'node:fs';
1
+ import { accessSync, constants, existsSync, readFileSync, realpathSync } from 'node:fs';
2
2
  import { isIP } from 'node:net';
3
3
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
4
  import { CommandFailure } from '@di-framework/cli-extension';
5
+ import { RENDERED_ENVIRONMENT_KEYS } from './environment-names.js';
6
+ import { parsePgliteConfig } from './pglite.js';
5
7
  import { discoverWorkloadEntry } from './workload-members.js';
6
8
  export const CONFIG_FILE_NAME = 'di-framework.config.json';
9
+ /** A key the control Secret may carry for the app: an environment variable name. */
10
+ const CONTROL_SECRET_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,252}$/;
11
+ /**
12
+ * The `DI_*` keys a project may declare. Every other `DI_*` name belongs to the framework: the CLI
13
+ * owns it in the control Secret or renders it into the workload's environment config, and a
14
+ * Secret key must not shadow either.
15
+ */
16
+ const DECLARABLE_DI_KEYS = ['DI_PGLITE_KEY', 'DI_PGLITE_KEY_PREVIOUS'];
17
+ /** Why `name` cannot be declared in `controlSecretKeys`, or undefined when it can. */
18
+ export function controlSecretKeyProblem(name) {
19
+ if (typeof name !== 'string' || !CONTROL_SECRET_KEY.test(name))
20
+ return `${JSON.stringify(name)} is not an environment variable name`;
21
+ if (name.startsWith('DI_') && !DECLARABLE_DI_KEYS.includes(name))
22
+ return `${name} is reserved for the framework; of the DI_* names only ${DECLARABLE_DI_KEYS.join(' and ')} may be declared`;
23
+ if (RENDERED_ENVIRONMENT_KEYS.includes(name))
24
+ return `${name} is rendered by the CLI`;
25
+ return undefined;
26
+ }
27
+ function parseControlSecretKeys(value, configPath) {
28
+ if (value === undefined)
29
+ return undefined;
30
+ if (!Array.isArray(value))
31
+ configInvalid(`${CONFIG_FILE_NAME} "controlSecretKeys" must be an array of names`, configPath);
32
+ for (const [index, name] of value.entries()) {
33
+ const problem = controlSecretKeyProblem(name);
34
+ if (problem !== undefined)
35
+ configInvalid(`${CONFIG_FILE_NAME} "controlSecretKeys"[${index}]: ${problem}`, configPath);
36
+ if (value.indexOf(name) !== index)
37
+ configInvalid(`${CONFIG_FILE_NAME} "controlSecretKeys" repeats ${name}`, configPath);
38
+ }
39
+ return value.length > 0 ? [...value] : undefined;
40
+ }
7
41
  export function findUp(startDirectory, fileName) {
8
42
  let previous = '';
9
43
  let current = resolve(startDirectory);
@@ -31,6 +65,16 @@ export function resolveInside(projectRoot, value, label, configPath) {
31
65
  }
32
66
  return absolutePath;
33
67
  }
68
+ /**
69
+ * {@link resolveInside}, then the same check on the resolved real path, so a symlink inside
70
+ * the project cannot point outside it. A missing file is left for the caller to report.
71
+ */
72
+ export function resolveRealInside(projectRoot, value, label, configPath) {
73
+ const absolutePath = resolveInside(projectRoot, value, label, configPath);
74
+ if (existsSync(absolutePath))
75
+ resolveInside(realpathSync(projectRoot), realpathSync(absolutePath), label, configPath);
76
+ return absolutePath;
77
+ }
34
78
  export function asWitIdentifier(value) {
35
79
  const collapsed = value.toLowerCase().replace(/[^a-z0-9-]+/g, '-');
36
80
  let start = 0;
@@ -111,6 +155,8 @@ export function loadProject(startDirectory) {
111
155
  : config.ingress !== false && config.http !== false;
112
156
  const cronMode = config.cronMode === 'external' ? 'external' : undefined;
113
157
  const persistentStorage = config.persistentStorage === true;
158
+ const pglite = parsePgliteConfig(config.pglite, configPath, (path) => resolveRealInside(projectRoot, path, 'pglite.wasm', configPath));
159
+ const controlSecretKeys = parseControlSecretKeys(config.controlSecretKeys, configPath);
114
160
  return {
115
161
  applicationName: config.name,
116
162
  ...(workload ? { workload, workloadEntry } : {}),
@@ -118,6 +164,8 @@ export function loadProject(startDirectory) {
118
164
  ...(cronMode ? { cronMode } : {}),
119
165
  ...(persistentStorage ? { persistentStorage: true } : {}),
120
166
  ...(config.logs === false ? { logs: false } : {}),
167
+ ...(pglite ? { pglite } : {}),
168
+ ...(controlSecretKeys ? { controlSecretKeys } : {}),
121
169
  ...(config.allowedIpNameLookups === undefined
122
170
  ? {}
123
171
  : { allowedIpNameLookups: config.allowedIpNameLookups }),
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Denial messages of the platform's Secret admission policies, matched by substring in kubectl
3
+ * stderr (kubectl prefixes them with the policy and binding names). The source of truth is
4
+ * di-framework/platform `platform/platform/src/tenancy/admission.ts`:
5
+ * `SECRET_UPDATE_KEYS_MESSAGE` and `SECRET_UPDATE_MANAGED_MESSAGE` of the `tenant-secret-update`
6
+ * ValidatingAdmissionPolicy (platform#112, PR #114), and the message of the older
7
+ * `backend-config` policy, which a managed name can trip first. If the platform rewords one,
8
+ * the matching mapping here silently falls through to a generic error, so change both together.
9
+ */
10
+ export declare const SECRET_UPDATE_KEYS_MESSAGE = "tenant users may update a Secret only if it keeps every existing data key";
11
+ export declare const SECRET_UPDATE_MANAGED_MESSAGE = "tenant users cannot update platform-managed di-binding-*/di-bs-* Secrets";
12
+ export declare const BACKEND_CONFIG_MANAGED_MESSAGE = "di-tenant-stock, di-platform-routes, di-bs-*, and di-binding-* ConfigMaps/Secrets are managed by the platform controller";
13
+ export declare const MANAGED_SECRET_DENIALS: readonly ["tenant users cannot update platform-managed di-binding-*/di-bs-* Secrets", "di-tenant-stock, di-platform-routes, di-bs-*, and di-binding-* ConfigMaps/Secrets are managed by the platform controller"];
14
+ /**
15
+ * The Kubernetes Status reason of a failed kubectl request. kubectl prints most failures as
16
+ * `Error from server (<Reason>): …`, but an `Invalid` (422) one as
17
+ * `The <Kind> "<name>" is invalid: …` or `The request is invalid: …`. Matching the reason
18
+ * rather than free text keeps a resource name such as `notfound-creds` from changing how an
19
+ * error is classified.
20
+ */
21
+ export declare function kubectlStatusReason(stderr: string): string | undefined;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Denial messages of the platform's Secret admission policies, matched by substring in kubectl
3
+ * stderr (kubectl prefixes them with the policy and binding names). The source of truth is
4
+ * di-framework/platform `platform/platform/src/tenancy/admission.ts`:
5
+ * `SECRET_UPDATE_KEYS_MESSAGE` and `SECRET_UPDATE_MANAGED_MESSAGE` of the `tenant-secret-update`
6
+ * ValidatingAdmissionPolicy (platform#112, PR #114), and the message of the older
7
+ * `backend-config` policy, which a managed name can trip first. If the platform rewords one,
8
+ * the matching mapping here silently falls through to a generic error, so change both together.
9
+ */
10
+ export const SECRET_UPDATE_KEYS_MESSAGE = 'tenant users may update a Secret only if it keeps every existing data key';
11
+ export const SECRET_UPDATE_MANAGED_MESSAGE = 'tenant users cannot update platform-managed di-binding-*/di-bs-* Secrets';
12
+ export const BACKEND_CONFIG_MANAGED_MESSAGE = 'di-tenant-stock, di-platform-routes, di-bs-*, and di-binding-* ConfigMaps/Secrets are managed by the platform controller';
13
+ export const MANAGED_SECRET_DENIALS = [
14
+ SECRET_UPDATE_MANAGED_MESSAGE,
15
+ BACKEND_CONFIG_MANAGED_MESSAGE,
16
+ ];
17
+ /**
18
+ * The Kubernetes Status reason of a failed kubectl request. kubectl prints most failures as
19
+ * `Error from server (<Reason>): …`, but an `Invalid` (422) one as
20
+ * `The <Kind> "<name>" is invalid: …` or `The request is invalid: …`. Matching the reason
21
+ * rather than free text keeps a resource name such as `notfound-creds` from changing how an
22
+ * error is classified.
23
+ */
24
+ export function kubectlStatusReason(stderr) {
25
+ const reason = /^Error from server \(([A-Za-z]+)\)/m.exec(stderr)?.[1];
26
+ if (reason !== undefined)
27
+ return reason;
28
+ return /^The (?:request|[A-Za-z]+ "[^"]*") is invalid: /m.test(stderr) ? 'Invalid' : undefined;
29
+ }
package/dist/wit.d.ts CHANGED
@@ -24,6 +24,9 @@ export declare const DI_SQLITE_VERSION = "0.1.0";
24
24
  export declare const DI_SQLITE_INTERFACE = "database";
25
25
  export declare const DI_SQLITE_TYPES_INTERFACE = "types";
26
26
  export declare const SQLITE_SOURCE = "sqlite-backend";
27
+ export declare const DI_PGLITE_PACKAGE = "di-framework:pglite";
28
+ export declare const DI_PGLITE_VERSION = "0.2.0";
29
+ export declare const PGLITE_SOURCE = "pglite-backend";
27
30
  export type WitDirection = 'import' | 'export';
28
31
  /**
29
32
  * One adapter or binding's WIT needs. A requirement is an interface group:
package/dist/wit.js CHANGED
@@ -27,6 +27,9 @@ export const DI_SQLITE_VERSION = '0.1.0';
27
27
  export const DI_SQLITE_INTERFACE = 'database';
28
28
  export const DI_SQLITE_TYPES_INTERFACE = 'types';
29
29
  export const SQLITE_SOURCE = 'sqlite-backend';
30
+ export const DI_PGLITE_PACKAGE = 'di-framework:pglite';
31
+ export const DI_PGLITE_VERSION = '0.2.0';
32
+ export const PGLITE_SOURCE = 'pglite-backend';
30
33
  export const HTTP_ADAPTER_REQUIREMENTS = [
31
34
  {
32
35
  package: WASI_HTTP_PACKAGE,
@@ -148,6 +151,15 @@ export function runtimeRequirementsFromJavaScript(source) {
148
151
  source: SQLITE_SOURCE,
149
152
  });
150
153
  }
154
+ if (source.includes(`${DI_PGLITE_PACKAGE}/database@${DI_PGLITE_VERSION}`)) {
155
+ requirements.push({
156
+ package: DI_PGLITE_PACKAGE,
157
+ version: DI_PGLITE_VERSION,
158
+ interfaces: ['types', 'database'],
159
+ direction: 'import',
160
+ source: PGLITE_SOURCE,
161
+ });
162
+ }
151
163
  return requirements;
152
164
  }
153
165
  /** Guest console lines; the host binds its logging plugin only when this is declared. */