@di-framework/cli-plugin-platform 6.1.2 → 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.
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Wiring a PGlite encryption layer between the provider and the host filesystem.
3
+ *
4
+ * `wac plug` is best effort: it plugs each export of the layer whose name matches an import of
5
+ * the provider *and* whose type is a subtype of it, silently skips the rest, and exits 0 as soon
6
+ * as one pair plugged. A layer that exports only `wasi:cli/environment`, exports the filesystem
7
+ * at a version wac does not match, or exports it with a different type would compose cleanly and
8
+ * leave PGlite writing plaintext to the host. So the build does not use `wac plug` here: it
9
+ * plans the wiring itself and composes an explicit WAC document with `wac compose`, where every
10
+ * provider import that must go to the layer is a named instantiation argument. wac then
11
+ * type-checks each one and fails loudly instead of skipping it.
12
+ */
13
+ /** An interface a component's world imports or exports, e.g. `wasi:filesystem/types@0.2.9`. */
14
+ export type WitInterface = {
15
+ name: string;
16
+ version?: string;
17
+ };
18
+ /**
19
+ * The interfaces a component's world imports and exports, from `jco wit` output. `unrecognized`
20
+ * holds every other `import`/`export` line, such as a plain-named `import fs: interface {` or a
21
+ * bare function, which the wiring cannot reason about.
22
+ */
23
+ export declare function worldInterfaces(wit: string): {
24
+ imports: WitInterface[];
25
+ exports: WitInterface[];
26
+ unrecognized: string[];
27
+ };
28
+ /**
29
+ * Interfaces the provider may take straight from the host. Everything else it imports must be
30
+ * wired to the layer, so a provider that reached storage some other way (another filesystem
31
+ * package, a plain-named interface) stops the build instead of bypassing the layer.
32
+ */
33
+ export declare const HOST_PASS_THROUGH: string[];
34
+ export declare function formatInterface(item: WitInterface): string;
35
+ /**
36
+ * Whether two versions of an interface are on the same semver track, as wac decides it
37
+ * (wac-types `are_semver_compatible`), in either direction: the same major from 1.0 on, the
38
+ * same minor for 0.x with x ≥ 1, and an exact match for 0.0.z and pre-releases. Unversioned
39
+ * names match only each other.
40
+ */
41
+ export declare function semverCompatible(a?: string, b?: string): boolean;
42
+ /** One provider import wired to one layer export, by their full names. */
43
+ export type Wire = {
44
+ providerImport: string;
45
+ layerExport: string;
46
+ };
47
+ /**
48
+ * Which layer export each provider import is wired to: the export with the same name and
49
+ * version, else the first on the same semver track (wac's own matching). Every
50
+ * `wasi:filesystem/*` import must be wired, or `problem` says why not; other interfaces the
51
+ * layer re-exports (`wasi:io/streams`, `wasi:cli/*`, …) are wired too, since the filesystem
52
+ * types refer to them.
53
+ */
54
+ export declare function planWiring(provider: {
55
+ imports: WitInterface[];
56
+ exports?: WitInterface[];
57
+ unrecognized?: string[];
58
+ }, layer: {
59
+ exports: WitInterface[];
60
+ }): {
61
+ wires: Wire[];
62
+ problem?: string;
63
+ };
64
+ /** WAC package names the composition document refers to (bound with `wac compose --dep`). */
65
+ export declare const LAYER_PACKAGE = "pglite:layer";
66
+ export declare const PROVIDER_PACKAGE = "pglite:provider";
67
+ /**
68
+ * The WAC document that instantiates the layer against the host and the provider with every
69
+ * wired import taken from the layer's instance, re-exporting the provider's exports. Imports of
70
+ * either that are not wired stay imports of the result (`...`).
71
+ */
72
+ export declare function encryptionComposition(wires: readonly Wire[], providerExports: WitInterface[]): string;
73
+ /** Custom section the platform's encryption layer carries (`format=1 codec=aes-256-xts`). */
74
+ export declare const ENCFS_SECTION = "di-framework:pglite-encfs";
75
+ /**
76
+ * The contents of the `di-framework:pglite-encfs` custom section anywhere in a core module or
77
+ * component binary, including nested modules and components, or undefined when there is none.
78
+ */
79
+ export declare function encfsSection(bytes: Uint8Array): string | undefined;
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Wiring a PGlite encryption layer between the provider and the host filesystem.
3
+ *
4
+ * `wac plug` is best effort: it plugs each export of the layer whose name matches an import of
5
+ * the provider *and* whose type is a subtype of it, silently skips the rest, and exits 0 as soon
6
+ * as one pair plugged. A layer that exports only `wasi:cli/environment`, exports the filesystem
7
+ * at a version wac does not match, or exports it with a different type would compose cleanly and
8
+ * leave PGlite writing plaintext to the host. So the build does not use `wac plug` here: it
9
+ * plans the wiring itself and composes an explicit WAC document with `wac compose`, where every
10
+ * provider import that must go to the layer is a named instantiation argument. wac then
11
+ * type-checks each one and fails loudly instead of skipping it.
12
+ */
13
+ const FILESYSTEM = 'wasi:filesystem/';
14
+ const WORLD_ITEM = /^\s*(import|export)\s+([a-z][a-z0-9-]*:[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*)(?:@([^;\s]+))?;\s*$/;
15
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;
16
+ const WORLD_LINE = /^\s*(import|export)\s/;
17
+ /**
18
+ * The interfaces a component's world imports and exports, from `jco wit` output. `unrecognized`
19
+ * holds every other `import`/`export` line, such as a plain-named `import fs: interface {` or a
20
+ * bare function, which the wiring cannot reason about.
21
+ */
22
+ export function worldInterfaces(wit) {
23
+ const imports = [];
24
+ const exports = [];
25
+ const unrecognized = [];
26
+ for (const line of wit.split('\n')) {
27
+ const match = WORLD_ITEM.exec(line);
28
+ if (match === null) {
29
+ if (WORLD_LINE.test(line))
30
+ unrecognized.push(line.trim());
31
+ continue;
32
+ }
33
+ const item = {
34
+ name: match[2],
35
+ ...(match[3] === undefined ? {} : { version: match[3] }),
36
+ };
37
+ (match[1] === 'import' ? imports : exports).push(item);
38
+ }
39
+ return { imports, exports, unrecognized };
40
+ }
41
+ /**
42
+ * Interfaces the provider may take straight from the host. Everything else it imports must be
43
+ * wired to the layer, so a provider that reached storage some other way (another filesystem
44
+ * package, a plain-named interface) stops the build instead of bypassing the layer.
45
+ */
46
+ export const HOST_PASS_THROUGH = ['wasi:io/', 'wasi:clocks/', 'wasi:random/', 'wasi:cli/'];
47
+ export function formatInterface(item) {
48
+ return item.version === undefined ? item.name : `${item.name}@${item.version}`;
49
+ }
50
+ /**
51
+ * Whether two versions of an interface are on the same semver track, as wac decides it
52
+ * (wac-types `are_semver_compatible`), in either direction: the same major from 1.0 on, the
53
+ * same minor for 0.x with x ≥ 1, and an exact match for 0.0.z and pre-releases. Unversioned
54
+ * names match only each other.
55
+ */
56
+ export function semverCompatible(a, b) {
57
+ if (a === b)
58
+ return true;
59
+ if (a === undefined || b === undefined)
60
+ return false;
61
+ const x = SEMVER.exec(a);
62
+ const y = SEMVER.exec(b);
63
+ if (x === null || y === null || x[4] !== undefined || y[4] !== undefined)
64
+ return false;
65
+ const [xMajor, xMinor, xPatch] = [1, 2, 3].map((n) => Number(x[n]));
66
+ const [yMajor, yMinor, yPatch] = [1, 2, 3].map((n) => Number(y[n]));
67
+ if (xMajor !== yMajor)
68
+ return false;
69
+ if (xMajor !== 0)
70
+ return true;
71
+ if (xMinor !== yMinor)
72
+ return false;
73
+ if (xMinor !== 0)
74
+ return true;
75
+ return xPatch === yPatch;
76
+ }
77
+ const isFilesystem = (item) => item.name.startsWith(FILESYSTEM);
78
+ /**
79
+ * Which layer export each provider import is wired to: the export with the same name and
80
+ * version, else the first on the same semver track (wac's own matching). Every
81
+ * `wasi:filesystem/*` import must be wired, or `problem` says why not; other interfaces the
82
+ * layer re-exports (`wasi:io/streams`, `wasi:cli/*`, …) are wired too, since the filesystem
83
+ * types refer to them.
84
+ */
85
+ export function planWiring(provider, layer) {
86
+ if (provider.unrecognized !== undefined && provider.unrecognized.length > 0)
87
+ return {
88
+ wires: [],
89
+ problem: `the provider's world has items the build cannot wire: ${provider.unrecognized.join('; ')}`,
90
+ };
91
+ const required = provider.imports.filter(isFilesystem);
92
+ if (required.length === 0)
93
+ return {
94
+ wires: [],
95
+ problem: 'the provider imports no wasi:filesystem interface, so there is nothing for the layer to encrypt',
96
+ };
97
+ const wires = [];
98
+ const missing = [];
99
+ for (const wanted of provider.imports) {
100
+ const offered = layer.exports.find((item) => item.name === wanted.name && item.version === wanted.version) ??
101
+ layer.exports.find((item) => item.name === wanted.name && semverCompatible(item.version, wanted.version));
102
+ if (offered !== undefined) {
103
+ wires.push({
104
+ providerImport: formatInterface(wanted),
105
+ layerExport: formatInterface(offered),
106
+ });
107
+ continue;
108
+ }
109
+ if (!isFilesystem(wanted)) {
110
+ if (!HOST_PASS_THROUGH.some((prefix) => wanted.name.startsWith(prefix)))
111
+ missing.push(`${formatInterface(wanted)} (neither exported by the layer nor allowed from the host)`);
112
+ continue;
113
+ }
114
+ const found = layer.exports
115
+ .filter((item) => item.name === wanted.name)
116
+ .map((item) => `@${item.version ?? 'unversioned'}`);
117
+ const detail = found.length === 0 ? 'not exported' : `the layer exports ${found.join(', ')}`;
118
+ missing.push(`${formatInterface(wanted)} (${detail})`);
119
+ }
120
+ return missing.length === 0
121
+ ? { wires }
122
+ : {
123
+ wires,
124
+ problem: `the layer does not export what the provider imports: ${missing.join('; ')}`,
125
+ };
126
+ }
127
+ /** WAC package names the composition document refers to (bound with `wac compose --dep`). */
128
+ export const LAYER_PACKAGE = 'pglite:layer';
129
+ export const PROVIDER_PACKAGE = 'pglite:provider';
130
+ /**
131
+ * The WAC document that instantiates the layer against the host and the provider with every
132
+ * wired import taken from the layer's instance, re-exporting the provider's exports. Imports of
133
+ * either that are not wired stay imports of the result (`...`).
134
+ */
135
+ export function encryptionComposition(wires, providerExports) {
136
+ const quote = (name) => JSON.stringify(name);
137
+ return [
138
+ 'package di-framework:pglite-encrypted;',
139
+ '',
140
+ `let layer = new ${LAYER_PACKAGE} { ... };`,
141
+ `let provider = new ${PROVIDER_PACKAGE} {`,
142
+ ...wires.map((wire) => ` ${quote(wire.providerImport)}: layer[${quote(wire.layerExport)}],`),
143
+ ' ...',
144
+ '};',
145
+ '',
146
+ ...providerExports.map((item) => `export provider[${quote(formatInterface(item))}];`),
147
+ '',
148
+ ].join('\n');
149
+ }
150
+ /** Custom section the platform's encryption layer carries (`format=1 codec=aes-256-xts`). */
151
+ export const ENCFS_SECTION = 'di-framework:pglite-encfs';
152
+ /**
153
+ * The contents of the `di-framework:pglite-encfs` custom section anywhere in a core module or
154
+ * component binary, including nested modules and components, or undefined when there is none.
155
+ */
156
+ export function encfsSection(bytes) {
157
+ const decoder = new TextDecoder();
158
+ const walk = (start, end) => {
159
+ if (end - start < 8 || bytes[start] !== 0 || bytes[start + 1] !== 0x61)
160
+ return undefined;
161
+ const component = bytes[start + 6] === 1;
162
+ let offset = start + 8;
163
+ const leb = () => {
164
+ let result = 0;
165
+ let shift = 0;
166
+ for (;;) {
167
+ const byte = bytes[offset++];
168
+ result += (byte & 0x7f) * 2 ** shift;
169
+ if ((byte & 0x80) === 0 || offset >= end)
170
+ return result;
171
+ shift += 7;
172
+ }
173
+ };
174
+ while (offset < end) {
175
+ const id = bytes[offset++];
176
+ const size = leb();
177
+ const body = offset;
178
+ const next = Math.min(end, body + size);
179
+ if (id === 0) {
180
+ offset = body;
181
+ const length = leb();
182
+ const name = decoder.decode(bytes.subarray(offset, offset + length));
183
+ if (name === ENCFS_SECTION)
184
+ return decoder.decode(bytes.subarray(offset + length, next));
185
+ }
186
+ else if (component && (id === 1 || id === 4)) {
187
+ const found = walk(body, next);
188
+ if (found !== undefined)
189
+ return found;
190
+ }
191
+ offset = next;
192
+ }
193
+ return undefined;
194
+ };
195
+ return walk(0, bytes.length);
196
+ }
package/dist/pglite.d.ts CHANGED
@@ -24,6 +24,45 @@ export declare const EXCLUSIVE_INSTANCE_KEY = "di-framework.dev/exclusive-instan
24
24
  export declare const DEFAULT_PGLITE_STORAGE_MOUNT = "/data";
25
25
  /** File name of the provider inside a cache entry. */
26
26
  export declare const PGLITE_WASM_FILE = "di-framework-pglite.wasm";
27
+ /**
28
+ * Encrypting `wasi:filesystem` layer for the provider (`pglite.encryption`), published by
29
+ * di-framework/platform. The build composes it into the provider with an explicit `wac compose`
30
+ * document (`.di-framework/pglite-encryption.wac`, see `encryptProvider`) before the provider is
31
+ * plugged into the guest, so only the engine sees the encrypted view.
32
+ */
33
+ export declare const PGLITE_ENCFS_REPOSITORY = "ghcr.io/di-framework/pglite-encfs";
34
+ /** Absolute (or cwd-relative) path of a local encryption layer build; wins over the config. */
35
+ export declare const PGLITE_ENCFS_WASM_ENV = "DI_FRAMEWORK_PGLITE_ENCFS_WASM";
36
+ /** File name of the encryption layer inside a cache entry. */
37
+ export declare const PGLITE_ENCFS_WASM_FILE = "di-framework-pglite-encfs.wasm";
38
+ /** The provider with the encryption layer plugged in, as the build plugs it into the guest. */
39
+ export declare const PGLITE_ENCRYPTED_WASM_FILE = "di-framework-pglite.encrypted.wasm";
40
+ /**
41
+ * The guest environment variable the encryption layer reads its master key from. It must come
42
+ * from the control Secret, so the project declares it in `controlSecretKeys`.
43
+ */
44
+ export declare const PGLITE_KEY_ENV = "DI_PGLITE_KEY";
45
+ /** A digest-pinned component the CLI pulls: the provider or its encryption layer. */
46
+ export type PinnedComponent = {
47
+ /** How messages name it. */
48
+ label: string;
49
+ /** The config object that pins it: `pglite` or `pglite.encryption`. */
50
+ field: string;
51
+ repository: string;
52
+ /** Environment variable naming a local build. */
53
+ localEnv: string;
54
+ /** File name inside a cache entry. */
55
+ file: string;
56
+ };
57
+ export declare const PGLITE_PROVIDER: PinnedComponent;
58
+ export declare const PGLITE_ENCFS: PinnedComponent;
59
+ /** `pglite.encryption`, resolved: where the encryption layer comes from. */
60
+ export type PgliteEncryptionConfig = {
61
+ /** `<repository>@sha256:<hex>` of the encryption layer. */
62
+ image?: string;
63
+ /** Absolute path of a local encryption layer build, used instead of `image`. */
64
+ wasm?: string;
65
+ };
27
66
  /** `pglite` in di-framework.config.json, resolved. */
28
67
  export type PgliteConfig = {
29
68
  /** `<repository>@sha256:<hex>`; the manifest digest the platform publish job records. */
@@ -34,6 +73,8 @@ export type PgliteConfig = {
34
73
  storageMount: string;
35
74
  /** Database root the guest opens; at or under `storageMount`. */
36
75
  dataDir: string;
76
+ /** Encrypt the data directory at rest with this layer, keyed by `DI_PGLITE_KEY`. */
77
+ encryption?: PgliteEncryptionConfig;
37
78
  };
38
79
  export type ResolvedPglite = {
39
80
  /** Verified provider bytes; the build plugs a private copy of these. */
@@ -44,7 +85,7 @@ export type ResolvedPglite = {
44
85
  /** The local file, when the bytes came from one. */
45
86
  path?: string;
46
87
  };
47
- export declare function parseDigestReference(reference: string): {
88
+ export declare function parseDigestReference(reference: string, repository?: string): {
48
89
  repository: string;
49
90
  digest: string;
50
91
  };
@@ -68,7 +109,7 @@ export declare const STALE_STAGING_MS: number;
68
109
  * digest, into the cache. A cached entry is re-verified on every use; a corrupt one is
69
110
  * pulled again. Returns the verified bytes, so later readers never see a swapped file.
70
111
  */
71
- export declare function pullPgliteComponent(image: string, io: CliIo, deps: WasmcloudDeps, cwd: string): Promise<ResolvedPglite>;
112
+ export declare function pullPgliteComponent(image: string, io: CliIo, deps: WasmcloudDeps, cwd: string, component?: PinnedComponent): Promise<ResolvedPglite>;
72
113
  /** Set to `1` to let `deploy` or a CI build use a local, unverified provider. */
73
114
  export declare const ALLOW_LOCAL_PGLITE_ENV = "DI_FRAMEWORK_ALLOW_LOCAL_PGLITE";
74
115
  export type ResolvePgliteOptions = {
@@ -81,6 +122,12 @@ export type ResolvePgliteOptions = {
81
122
  * refused in a deploy or on CI without `DI_FRAMEWORK_ALLOW_LOCAL_PGLITE=1`.
82
123
  */
83
124
  export declare function resolvePgliteComponent(config: PgliteConfig, io: CliIo, deps: WasmcloudDeps, projectRoot: string, options?: ResolvePgliteOptions): Promise<ResolvedPglite>;
125
+ /**
126
+ * The encryption layer to plug into the provider, resolved like the provider:
127
+ * `DI_FRAMEWORK_PGLITE_ENCFS_WASM`, then `pglite.encryption.wasm`, then the digest-pinned
128
+ * `pglite.encryption.image`, with the same local-file refusal in a deploy or on CI.
129
+ */
130
+ export declare function resolvePgliteEncryption(config: PgliteEncryptionConfig, io: CliIo, deps: WasmcloudDeps, projectRoot: string, options?: ResolvePgliteOptions): Promise<ResolvedPglite>;
84
131
  /**
85
132
  * Members of one workload share one storage directory, mounted at each member's own
86
133
  * `storageMount`. Two members whose `dataDir` is the same path relative to their mount
package/dist/pglite.js CHANGED
@@ -28,18 +28,51 @@ export const EXCLUSIVE_INSTANCE_KEY = 'di-framework.dev/exclusive-instance';
28
28
  export const DEFAULT_PGLITE_STORAGE_MOUNT = '/data';
29
29
  /** File name of the provider inside a cache entry. */
30
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';
31
49
  const WASM_LAYER_MEDIA_TYPE = 'application/wasm';
32
50
  const SHA256_DIGEST = /^sha256:[0-9a-f]{64}$/;
33
51
  const DIGEST_REFERENCE = /^([a-z0-9]+(?:[.:-][a-z0-9]+)*(?:\/[a-z0-9]+(?:[._-][a-z0-9]+)*)+)@(.+)$/;
34
- const CONFIG_KEYS = ['image', 'wasm', 'storageMount', 'dataDir'];
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
+ };
35
68
  function configInvalid(message, configPath) {
36
69
  throw new CommandFailure('WASMCLOUD_CONFIG_INVALID', message, 2, { configPath });
37
70
  }
38
- export function parseDigestReference(reference) {
71
+ export function parseDigestReference(reference, repository = PGLITE_REPOSITORY) {
39
72
  const match = DIGEST_REFERENCE.exec(reference);
40
73
  const digest = match?.[2] ?? '';
41
74
  if (match === null || !SHA256_DIGEST.test(digest)) {
42
- throw new Error(`"${reference}" is not pinned by digest. Use ${PGLITE_REPOSITORY}@sha256:<64 hex>; tags such as :${DI_PGLITE_VERSION} move`);
75
+ throw new Error(`"${reference}" is not pinned by digest. Use ${repository}@sha256:<64 hex>; tags such as :${DI_PGLITE_VERSION} move`);
43
76
  }
44
77
  return { repository: match[1], digest };
45
78
  }
@@ -50,21 +83,37 @@ function absoluteGuestPath(value, label, configPath) {
50
83
  return normalized.length > 1 && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;
51
84
  }
52
85
  /** `image` must be a digest pin and `wasm` a path; at least one of them is required. */
53
- function validateProviderSource(entry, configPath) {
86
+ function validateProviderSource(entry, configPath, component = PGLITE_PROVIDER) {
87
+ const field = component.field;
54
88
  if (entry.image !== undefined) {
55
89
  if (typeof entry.image !== 'string')
56
- configInvalid('pglite.image must be a string', configPath);
90
+ configInvalid(`${field}.image must be a string`, configPath);
57
91
  try {
58
- parseDigestReference(entry.image);
92
+ parseDigestReference(entry.image, component.repository);
59
93
  }
60
94
  catch (error) {
61
- configInvalid(`pglite.image: ${error.message}`, configPath);
95
+ configInvalid(`${field}.image: ${error.message}`, configPath);
62
96
  }
63
97
  }
64
98
  if (entry.wasm !== undefined && (typeof entry.wasm !== 'string' || entry.wasm.trim() === ''))
65
- configInvalid('pglite.wasm must be a non-empty path', configPath);
99
+ configInvalid(`${field}.wasm must be a non-empty path`, configPath);
66
100
  if (entry.image === undefined && entry.wasm === undefined)
67
- configInvalid(`pglite needs "image" (${PGLITE_REPOSITORY}@sha256:<digest>) or a local "wasm" path`, configPath);
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
+ };
68
117
  }
69
118
  /** True when `path` is `directory` or below it (both normalized guest paths). */
70
119
  export function isWithin(path, directory) {
@@ -89,11 +138,21 @@ export function parsePgliteConfig(value, configPath, resolveFile) {
89
138
  : absoluteGuestPath(entry.dataDir, 'dataDir', configPath);
90
139
  if (!isWithin(dataDir, storageMount))
91
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
+ }
92
150
  return {
93
151
  ...(entry.image === undefined ? {} : { image: entry.image }),
94
152
  ...(entry.wasm === undefined ? {} : { wasm: resolveFile(entry.wasm) }),
95
153
  storageMount,
96
154
  dataDir,
155
+ ...(encryption === undefined ? {} : { encryption }),
97
156
  };
98
157
  }
99
158
  export function cacheRoot(env) {
@@ -154,9 +213,9 @@ export function verifyLayer(bytes, image, layerDigest) {
154
213
  throw failure('WASMCLOUD_PGLITE_MANIFEST_INVALID', `Provider layer of ${image} is not a WebAssembly binary`, { image });
155
214
  }
156
215
  /** The verified provider bytes of a cache entry, or undefined when it is absent or stale. */
157
- function readVerifiedEntry(directory, image) {
216
+ function readVerifiedEntry(directory, image, file) {
158
217
  const manifestPath = join(directory, 'manifest.json');
159
- const wasmPath = join(directory, PGLITE_WASM_FILE);
218
+ const wasmPath = join(directory, file);
160
219
  if (!existsSync(manifestPath) || !existsSync(wasmPath))
161
220
  return undefined;
162
221
  try {
@@ -184,27 +243,27 @@ function sweepStaleStaging(root, now) {
184
243
  }
185
244
  }
186
245
  }
187
- async function oras(deps, args, image, cwd) {
246
+ async function oras(deps, args, image, cwd, component) {
188
247
  const result = await deps.runCaptured('oras', args, { cwd });
189
248
  if (result.exitCode === 0)
190
249
  return;
191
250
  const reason = (result.stderr || result.stdout).trim();
192
251
  const detail = reason ? `: ${reason}` : '';
193
252
  throw failure('WASMCLOUD_PGLITE_PULL_FAILED', `oras ${args.slice(0, 2).join(' ')} failed for ${image}${detail}. ` +
194
- `If the package is private, run \`oras login ghcr.io\`; offline, set ${PGLITE_WASM_ENV} or pglite.wasm`, { image, exitCode: String(result.exitCode) });
253
+ `If the package is private, run \`oras login ghcr.io\`; offline, set ${component.localEnv} or ${component.field}.wasm`, { image, exitCode: String(result.exitCode) });
195
254
  }
196
255
  /**
197
256
  * Stores a verified staging directory as the cache entry. A concurrent build may have
198
257
  * stored the same digest first; its entry is used when it verifies.
199
258
  */
200
- function storeEntry(staging, entry, image, bytes) {
259
+ function storeEntry(staging, entry, image, bytes, file) {
201
260
  mkdirSync(join(entry, '..'), { recursive: true });
202
261
  try {
203
262
  renameSync(staging, entry);
204
263
  return bytes;
205
264
  }
206
265
  catch (error) {
207
- const winner = readVerifiedEntry(entry, image);
266
+ const winner = readVerifiedEntry(entry, image, file);
208
267
  if (winner !== undefined)
209
268
  return winner;
210
269
  throw failure('WASMCLOUD_PGLITE_CACHE_CONFLICT', `Could not store ${image} in the cache at ${entry} (${error.code ?? 'unknown error'}), ` +
@@ -216,10 +275,10 @@ function storeEntry(staging, entry, image, bytes) {
216
275
  * digest, into the cache. A cached entry is re-verified on every use; a corrupt one is
217
276
  * pulled again. Returns the verified bytes, so later readers never see a swapped file.
218
277
  */
219
- export async function pullPgliteComponent(image, io, deps, cwd) {
220
- const { repository, digest } = parseDigestReference(image);
278
+ export async function pullPgliteComponent(image, io, deps, cwd, component = PGLITE_PROVIDER) {
279
+ const { repository, digest } = parseDigestReference(image, component.repository);
221
280
  const entry = cacheEntry(deps.env, digest);
222
- const cached = readVerifiedEntry(entry, image);
281
+ const cached = readVerifiedEntry(entry, image, component.file);
223
282
  if (cached !== undefined) {
224
283
  io.stdout.write(`Using cached ${image}\n`);
225
284
  return { bytes: cached, source: 'cache', image };
@@ -229,7 +288,7 @@ export async function pullPgliteComponent(image, io, deps, cwd) {
229
288
  rmSync(entry, { recursive: true, force: true });
230
289
  }
231
290
  if (deps.capture('oras', ['version']) === undefined)
232
- throw failure('WASMCLOUD_ORAS_REQUIRED', `oras is required to pull ${image}; install it from https://oras.land or set ${PGLITE_WASM_ENV} to a local provider build`, { image, tool: 'oras' });
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' });
233
292
  const root = cacheRoot(deps.env);
234
293
  mkdirSync(root, { recursive: true });
235
294
  sweepStaleStaging(root, Date.now());
@@ -237,13 +296,17 @@ export async function pullPgliteComponent(image, io, deps, cwd) {
237
296
  try {
238
297
  io.stdout.write(`Pulling ${image}...\n`);
239
298
  const manifestPath = join(staging, 'manifest.json');
240
- await oras(deps, ['manifest', 'fetch', '--output', manifestPath, image], image, cwd);
299
+ await oras(deps, ['manifest', 'fetch', '--output', manifestPath, image], image, cwd, component);
241
300
  const layerDigest = verifyManifest(readFileSync(manifestPath), image);
242
- const stagedWasm = join(staging, PGLITE_WASM_FILE);
243
- await oras(deps, ['blob', 'fetch', '--output', stagedWasm, `${repository}@${layerDigest}`], image, cwd);
301
+ const stagedWasm = join(staging, component.file);
302
+ await oras(deps, ['blob', 'fetch', '--output', stagedWasm, `${repository}@${layerDigest}`], image, cwd, component);
244
303
  const bytes = readFileSync(stagedWasm);
245
304
  verifyLayer(bytes, image, layerDigest);
246
- return { bytes: storeEntry(staging, entry, image, bytes), source: 'registry', image };
305
+ return {
306
+ bytes: storeEntry(staging, entry, image, bytes, component.file),
307
+ source: 'registry',
308
+ image,
309
+ };
247
310
  }
248
311
  finally {
249
312
  rmSync(staging, { recursive: true, force: true });
@@ -251,22 +314,22 @@ export async function pullPgliteComponent(image, io, deps, cwd) {
251
314
  }
252
315
  /** Set to `1` to let `deploy` or a CI build use a local, unverified provider. */
253
316
  export const ALLOW_LOCAL_PGLITE_ENV = 'DI_FRAMEWORK_ALLOW_LOCAL_PGLITE';
254
- function readLocalProvider(local, origin, config, io, deps, options) {
317
+ function readLocalProvider(local, origin, config, io, deps, options, component = PGLITE_PROVIDER) {
255
318
  if (!existsSync(local))
256
- throw failure('WASMCLOUD_PGLITE_PROVIDER_MISSING', `PGlite provider ${local} (from ${origin}) does not exist`, { path: local });
319
+ throw failure('WASMCLOUD_PGLITE_PROVIDER_MISSING', `${component.label} ${local} (from ${origin}) does not exist`, { path: local });
257
320
  let context;
258
321
  if (options.deploy)
259
322
  context = 'deploy';
260
323
  else if (deps.env.CI)
261
324
  context = 'CI';
262
325
  if (context !== undefined && deps.env[ALLOW_LOCAL_PGLITE_ENV] !== '1')
263
- throw failure('WASMCLOUD_PGLITE_LOCAL_REFUSED', `Refusing the unverified local PGlite provider ${local} (from ${origin}) in ${context}; ` +
264
- `pin "pglite.image" by digest, or set ${ALLOW_LOCAL_PGLITE_ENV}=1 to use it anyway`, { path: local, context });
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 });
265
328
  const bytes = readFileSync(local);
266
329
  if (!isWasm(bytes))
267
- throw failure('WASMCLOUD_PGLITE_PROVIDER_INVALID', `PGlite provider ${local} (from ${origin}) is not a WebAssembly binary`, { path: local });
330
+ throw failure('WASMCLOUD_PGLITE_PROVIDER_INVALID', `${component.label} ${local} (from ${origin}) is not a WebAssembly binary`, { path: local });
268
331
  const replaced = config.image ? ` instead of the pinned ${config.image}` : '';
269
- io.stderr.write(`Warning: using the local, unverified PGlite provider ${local} (from ${origin})${replaced}\n`);
332
+ io.stderr.write(`Warning: using the local, unverified ${component.label} ${local} (from ${origin})${replaced}\n`);
270
333
  return { bytes, source: 'local', path: local };
271
334
  }
272
335
  /**
@@ -282,6 +345,19 @@ export async function resolvePgliteComponent(config, io, deps, projectRoot, opti
282
345
  return readLocalProvider(config.wasm, 'pglite.wasm', config, io, deps, options);
283
346
  return pullPgliteComponent(config.image, io, deps, projectRoot);
284
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
+ }
285
361
  /**
286
362
  * Members of one workload share one storage directory, mounted at each member's own
287
363
  * `storageMount`. Two members whose `dataDir` is the same path relative to their mount
package/dist/project.d.ts CHANGED
@@ -42,7 +42,14 @@ export type WasmcloudProject = {
42
42
  * component is exclusive and gets persistent storage at `storageMount`.
43
43
  */
44
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[];
45
50
  };
51
+ /** Why `name` cannot be declared in `controlSecretKeys`, or undefined when it can. */
52
+ export declare function controlSecretKeyProblem(name: unknown): string | undefined;
46
53
  export declare function findUp(startDirectory: string, fileName: string): string | undefined;
47
54
  /** Paths from the config must stay inside the project root. */
48
55
  export declare function resolveInside(projectRoot: string, value: string, label: string, configPath: string): string;