@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.
package/README.md CHANGED
@@ -306,18 +306,79 @@ Application `destroy` never runs `pulumi destroy`.
306
306
  ### Control Secret
307
307
 
308
308
  An application that serves HTTP, cron, queues or actors gets a Secret
309
- `<deployment>-control` holding `DI_CONTROL_TOKEN` and `DI_CONTROL_IDENTITY`. Tenant
310
- developers may create, update and delete Secrets but not read, list, watch or patch them,
311
- so the CLI never reads it back:
312
-
313
- - `deploy` writes a new random token every time: it creates the Secret and, if it already
314
- exists, replaces the whole Secret with an unconditional update. If keys were added to it
315
- by hand, the platform's `tenant-secret-update` admission policy denies that update (it
316
- refuses any update that drops a key), and deploy stops with "the control Secret
317
- `<deployment>-control` has keys this CLI didn't write"; delete it with
318
- `kubectl delete secret <deployment>-control` and redeploy. Other failed writes show
319
- kubectl's reason, scrubbed of the token.
320
- - The token rotates at that Secret write, before `kubectl apply`. The WorkloadDeployment
309
+ `<deployment>-control` holding `DI_CONTROL_TOKEN` and `DI_CONTROL_IDENTITY`. The workload gets
310
+ the whole Secret as environment variables, and a workload without an environment label may
311
+ reference no other Secret, so it is also where an app keeps its own runtime secrets. Declare
312
+ those keys in `di-framework.config.json`:
313
+
314
+ ```json
315
+ {
316
+ "controlSecretKeys": ["ISSUER_URL", "AUTH_ACTIVE_PRIVATE_JWK", "DI_PGLITE_KEY"]
317
+ }
318
+ ```
319
+
320
+ A declared key must be an environment variable name. `DI_*` names belong to the framework, so
321
+ of those only `DI_PGLITE_KEY` and `DI_PGLITE_KEY_PREVIOUS` may be declared, and so may none of
322
+ the names the CLI renders into the workload's environment (`ACTOR_STORAGE_DIR`,
323
+ `QUEUE_DB_PATH`, `MIGRATION_DB_PATH`). Deploy never writes or reads values for these keys, and
324
+ refuses any key that is neither the CLI's nor declared.
325
+
326
+ **Once app keys exist, the app's tooling owns the control token.** A tenant developer cannot
327
+ read the Secret, so the tooling cannot keep the CLI's token value. It replaces the whole Secret
328
+ with:
329
+ - its own values;
330
+ - a freshly minted, non-empty `DI_CONTROL_TOKEN` (for example 32 random bytes, base64url);
331
+ - `DI_CONTROL_IDENTITY` set to the workload name.
332
+
333
+ It then rolls the workload, for example by setting a revision entry in the WorkloadDeployment's
334
+ environment config, as identity-server's `runtime-secrets.ts apply` does. From then on deploy
335
+ keeps that Secret, and token included, never rotates it. Rotate by re-running the tooling. The
336
+ platform issue
337
+ [di-framework/platform#203](https://github.com/di-framework/platform/issues/203) proposes a
338
+ separate `<workload>-secrets` so the control Secret can go back to being CLI-owned and rotated
339
+ on every deploy.
340
+
341
+ - A new Secret is created with the CLI's keys and a new random token.
342
+ - Tenant developers may create, update and delete Secrets but not read, list, watch or patch
343
+ them. The CLI never reads the Secret back for them; `kubectl auth can-i get` decides this
344
+ without sending a read. Every check below is a dry-run update (`?dryRun=All`, nothing
345
+ stored). It asks the platform's `tenant-secret-update` admission policy, which refuses an
346
+ update that drops a key, about key names only. With app keys declared, deploy:
347
+ 1. Checks that the policy protects the Secret. A dry run keeping only `DI_CONTROL_IDENTITY`
348
+ must be refused. If it is accepted, the policy does not apply to this caller (a write-only
349
+ identity that is not `di-user-*`, or a namespace outside the policy), or the Secret has no
350
+ token. A blind replace could then drop the app keys for good, so deploy stops with
351
+ `WASMCLOUD_CONTROL_SECRET_UNGUARDED` and writes nothing. As a result, a write-only caller
352
+ outside `di-user-*` (for example a CI ServiceAccount bound to the developer role) cannot
353
+ deploy a project that declares app keys. Deploy it as a tenant developer, or with an
354
+ identity that may read Secrets.
355
+ 2. Replaces the whole Secret with the CLI's keys and a new token. That succeeds, and rotates
356
+ the token, only while the Secret holds nothing else.
357
+ 3. If the replace is refused, sends a dry run with the CLI's keys and every declared key. If
358
+ the policy refuses that too, an undeclared key exists: deploy stops with "the control
359
+ Secret `<deployment>-control` has keys this CLI didn't write". Declare the keys, or
360
+ delete the Secret with `kubectl delete secret <deployment>-control` and redeploy.
361
+ 4. Leaves out `DI_CONTROL_TOKEN`, then `DI_CONTROL_IDENTITY`, in two more dry runs. Each must
362
+ be refused, which proves the key is stored. Otherwise the app tooling dropped it, and
363
+ deploy stops with `WASMCLOUD_CONTROL_SECRET_INCOMPLETE` rather than run a workload
364
+ without control credentials. The checks see key names only, so a present but empty
365
+ `DI_CONTROL_TOKEN` passes them. The deployed workload then has no usable token and
366
+ answers every control request (cron, queue and actor endpoints) with 401; it never falls
367
+ back to unauthenticated access. Make sure the tooling writes a non-empty token.
368
+ 5. Keeps the Secret as it is, token included, says "Kept control Secret
369
+ `<deployment>-control`", and renders no `DI_CONTROL_TOKEN_REVISION`.
370
+
371
+ These checks rely on `tenant-secret-update` having no dry-run exemption
372
+ ([di-framework/platform#204](https://github.com/di-framework/platform/issues/204)). Without
373
+ declared keys, deploy only replaces, as before.
374
+ - A caller who may read Secrets (a cluster admin) gets the Secret read. Deploy stops, naming
375
+ the keys, when one is neither the CLI's nor declared, instead of dropping it. Otherwise it
376
+ writes a new token with the declared keys carried over, conditional on the version it read,
377
+ and a concurrent change stops deploy with "changed while deploy was updating it; re-run
378
+ deploy". Nothing read is printed. Failures are scrubbed of every value read: values of four
379
+ characters or more wherever they appear, and shorter ones as whole tokens.
380
+ - Other failed writes show kubectl's reason, scrubbed of the token.
381
+ - When deploy writes a token, it rotates at that Secret write, before `kubectl apply`. The WorkloadDeployment
321
382
  carries `DI_CONTROL_TOKEN_REVISION` (a digest of the token), so the deploy rolls the
322
383
  workload onto the new token, but not at the same moment as its cron invokers: a CronJob
323
384
  pod reads the Secret when it starts, so the invokers switch first and can get 401 from
@@ -579,6 +640,7 @@ const db = open(process.env.DI_PGLITE_DATA_DIR ?? '/data/pglite', undefined);
579
640
  | `wasm` | none | A local provider build inside the project (symlinks resolved), used instead of `image` for offline development. Unverified; see below. |
580
641
  | `storageMount` | `/data` | Guest preopen of the workload's persistent directory. Tenant targets accept `/data` or `/data/actors`. |
581
642
  | `dataDir` | `<storageMount>/pglite` | Database root, at or under `storageMount`. The guest receives it as `DI_PGLITE_DATA_DIR`. |
643
+ | `encryption` | none | `{ "image": "ghcr.io/di-framework/pglite-encfs@sha256:<digest>" }` (or a local `wasm`): encrypt the data directory at rest; see [Encryption at rest](#encryption-at-rest). |
582
644
 
583
645
  The build pulls the provider with `oras`: `oras manifest fetch`, then `oras blob fetch` of the
584
646
  manifest's single `application/wasm` layer. It checks that the manifest hashes to the pinned
@@ -615,6 +677,76 @@ entry has no matching import, because the deploy renders the following from the
615
677
  when `storageMount` is not `/data`. Other targets get a host path volume on the `storage` pool.
616
678
  - `replicas: 1` and `deployPolicy: Recreate`. Other replica counts are refused.
617
679
 
680
+ #### Encryption at rest
681
+
682
+ `pglite.encryption` plugs an encrypting `wasi:filesystem` layer between the provider and the
683
+ host, so the data directory holds only ciphertext. The layer is composed into the provider
684
+ first, with an explicit `wac compose` (see below). That result is then plugged into the guest
685
+ exactly as an unencrypted provider is. The guest's own WASI imports still go straight to the
686
+ host.
687
+
688
+ ```json
689
+ {
690
+ "controlSecretKeys": ["DI_PGLITE_KEY"],
691
+ "pglite": {
692
+ "image": "ghcr.io/di-framework/pglite-component@sha256:<64 hex>",
693
+ "encryption": { "image": "ghcr.io/di-framework/pglite-encfs@sha256:<64 hex>" }
694
+ }
695
+ }
696
+ ```
697
+
698
+ - `encryption.image` is pinned by digest and pulled, verified and cached like the provider
699
+ (`oci/sha256/<digest>/di-framework-pglite-encfs.wasm`); the build plugs a private copy,
700
+ `.di-framework/di-framework-pglite-encfs.wasm`. `encryption.wasm` (a local build inside the
701
+ project) and `DI_FRAMEWORK_PGLITE_ENCFS_WASM` override it under the same rules as a local
702
+ provider: unverified, warned about, and refused by `platform deploy` and on CI unless
703
+ `DI_FRAMEWORK_ALLOW_LOCAL_PGLITE=1`.
704
+ - The layer reads its master key from `DI_PGLITE_KEY` (and, while rotating,
705
+ `DI_PGLITE_KEY_PREVIOUS`). The key reaches the guest only through the workload's control
706
+ Secret, so the build fails with `WASMCLOUD_PGLITE_KEY_UNDECLARED` unless `DI_PGLITE_KEY` is in
707
+ `controlSecretKeys` (see [Control Secret](#control-secret)). That check runs first, before
708
+ bundling or any pull. The CLI never writes or reads the
709
+ key: put it in `<deployment>-control` with your own tooling, and keep a copy, since losing it
710
+ loses the database.
711
+ - The layer must sit between the provider and the host, and `wac plug` cannot prove that.
712
+ `wac plug` silently skips an export whose type does not fit, and it exits 0 as long as
713
+ anything plugged. So the build does this instead:
714
+ 1. Reads both worlds with `jco wit`.
715
+ 2. Takes, for each provider import the layer exports, the export with the same name and
716
+ version, or else one on the same semver track the way `wac` matches them. That means the
717
+ same major from 1.0 on, the same minor for 0.x, and an exact match for 0.0.z and
718
+ pre-releases. Every `wasi:filesystem/*` import must get one.
719
+ 3. Writes `.di-framework/pglite-encryption.wac`. It instantiates the layer against the host
720
+ and passes each of those exports to the provider as a named instantiation argument.
721
+ 4. Composes it with `wac compose`, which type-checks every argument.
722
+
723
+ The build stops with `WASMCLOUD_PGLITE_ENCRYPTION_NOT_INTERPOSED`, carrying `wac`'s message
724
+ when there is one, if any of these holds:
725
+ - the layer misses a filesystem interface, is on another version track, or exports a type
726
+ the provider cannot use;
727
+ - the provider's world has an item the build cannot read as a versioned interface (such as a
728
+ plain-named `import fs: interface { … }`);
729
+ - the provider imports something that is neither wired to the layer nor on the host
730
+ pass-through allowlist (`wasi:io/*`, `wasi:clocks/*`, `wasi:random/*`, `wasi:cli/*`).
731
+
732
+ Build the layer for the WASI versions the pinned provider imports (`wasi:filesystem/*@0.2.9`
733
+ for provider 6.0.11). A missing `wac` or `jco` fails with `WASMCLOUD_WAC_REQUIRED` or
734
+ `WASMCLOUD_JCO_REQUIRED`.
735
+ - The layer must carry the platform's `di-framework:pglite-encfs` custom section
736
+ (`format=1 codec=aes-256-xts`). Without it the build stops with
737
+ `WASMCLOUD_PGLITE_ENCRYPTION_LAYER_UNMARKED`, which catches a no-op or debug layer pinned by
738
+ mistake or a stale local build. The build proves the wiring and the layer's identity, not the
739
+ cipher: the marker can be forged, so trust in what the layer actually does comes from the
740
+ digest pin of `encryption.image`.
741
+ - Only the engine has `DI_PGLITE_KEY` hidden. The layer filters it from the provider's
742
+ environment, but the guest's own `wasi:cli/environment` still comes from the host, so your
743
+ application code can read the key.
744
+ - The composed provider is `.di-framework/di-framework-pglite.encrypted.wasm`. The deployment
745
+ digest hashes the raw provider and layer bytes, not `wac`'s output, so changing either one
746
+ redeploys. The build and deploy results report the layer
747
+ (`PGlite: <image>, encrypted at rest by <layer>`).
748
+ - `encryption.image` must not pin the provider's repository or digest.
749
+
618
750
  Give each database one owner. Members of one implicit workload share one storage directory,
619
751
  mounted at each member's own `storageMount`. So `/data/pglite` under a `/data` mount and
620
752
  `/data/actors/pglite` under a `/data/actors` mount are the same database. Members that both embed
@@ -34,7 +34,10 @@ function parseIdentities() {
34
34
  return { identities: singleTokenIdentities(), configured: true };
35
35
  }
36
36
  const identities = singleTokenIdentities();
37
- return { identities, configured: identities.length > 0 };
37
+ return { identities, configured: identities.length > 0 || isDeployed() };
38
+ }
39
+ function isDeployed() {
40
+ return process.env.DI_CONTROL_REJECT_FORWARDED === "1" || (process.env.DI_CONTROL_HTTP_HOST ?? "").trim() !== "" || process.env.DI_CONTROL_IDENTITY !== undefined || process.env.DI_CONTROL_TOKEN !== undefined;
38
41
  }
39
42
  function hasRequiredRole(identity, requiredRoles) {
40
43
  return !requiredRoles.some((role) => !identity.roles.includes(role) && !identity.roles.includes("admin"));
@@ -1,6 +1,6 @@
1
1
  component: di-framework:sqlite@0.1.0
2
2
  profile: release
3
- built: 2026-10-12T03:40:28Z
3
+ built: 2026-10-12T20:41:07Z
4
4
  rustc: rustc 1.97.1 (8bab26f4f 2026-07-14)
5
5
  target: wasm32-wasip2
6
6
  wasi-sdk: 34.0
package/dist/build.d.ts CHANGED
@@ -17,13 +17,36 @@ export type BuildSummary = {
17
17
  profile: string;
18
18
  actors?: string[];
19
19
  /** The composed PGlite provider: where it came from and, when pulled, its pinned image. */
20
- pglite?: {
21
- source: ResolvedPglite['source'];
22
- image?: string;
23
- path?: string;
20
+ pglite?: ComponentOrigin & {
21
+ /** The encryption layer plugged into the provider, from `pglite.encryption`. */
22
+ encryption?: ComponentOrigin;
24
23
  };
25
24
  };
25
+ /** Where a composed component came from: a digest pin (pulled or cached) or a local file. */
26
+ export type ComponentOrigin = {
27
+ source: ResolvedPglite['source'];
28
+ image?: string;
29
+ path?: string;
30
+ };
26
31
  export declare function requirementsForProject(project: WasmcloudProject, deps?: WasmcloudDeps): WitRequirement[];
32
+ /**
33
+ * Composes the encryption layer into the provider and writes the result to `output`, which the
34
+ * build then plugs into the guest instead of the provider.
35
+ *
36
+ * `wac plug` silently skips a layer export whose name matches but whose type is not a subtype of
37
+ * the provider's import, and exits 0 when anything else plugged, so it cannot prove the layer is
38
+ * in the path. Instead the build reads both worlds with `jco wit`, plans which layer export each
39
+ * provider import takes (every `wasi:filesystem/*` import must have one), and composes a WAC
40
+ * document that passes each of them as a named instantiation argument (`wac compose`). wac
41
+ * type-checks every argument, so a layer that does not fit fails the build here rather than
42
+ * being bypassed. The document is kept at `.di-framework/pglite-encryption.wac`.
43
+ *
44
+ * Wiring cannot show that the layer encrypts: a pass-through layer wires the same way. So the
45
+ * layer must also carry the platform's `di-framework:pglite-encfs` custom section. That marker
46
+ * catches the wrong artifact (a no-op or debug layer, a stale local build); it is forgeable, so
47
+ * what the layer actually does rests on the digest pin.
48
+ */
49
+ export declare function encryptProvider(project: Pick<WasmcloudProject, 'projectRoot' | 'applicationName'>, deps: WasmcloudDeps, io: CliIo, provider: string, layer: string, output: string): Promise<void>;
27
50
  /** The disposable `.di-framework/` build directory: WIT world, bundle, and manifests. */
28
51
  export declare function buildComponent(project: WasmcloudProject, io: CliIo, deps: WasmcloudDeps, options?: {
29
52
  guestLogging?: boolean;
package/dist/build.js CHANGED
@@ -10,7 +10,8 @@ import { discoverScheduledJobs, renderCronAdapterModule, renderCronInvokerModule
10
10
  import { DEFAULT_DEPS } from './deps.js';
11
11
  import { renderGuestsModule } from './guests.js';
12
12
  import { OCI_ARTIFACT_PLATFORM } from './oci.js';
13
- import { DI_PGLITE_PACKAGE, DI_PGLITE_VERSION, PGLITE_WASM_FILE, resolvePgliteComponent, } from './pglite.js';
13
+ import { DI_PGLITE_PACKAGE, DI_PGLITE_VERSION, PGLITE_ENCFS_WASM_FILE, PGLITE_ENCRYPTED_WASM_FILE, PGLITE_KEY_ENV, PGLITE_WASM_FILE, resolvePgliteComponent, resolvePgliteEncryption, } from './pglite.js';
14
+ import { ENCFS_SECTION, encfsSection, encryptionComposition, LAYER_PACKAGE, PROVIDER_PACKAGE, planWiring, worldInterfaces, } from './pglite-encryption.js';
14
15
  import { loadProject } from './project.js';
15
16
  import { discoverQueueHandlers, isQueueWorkerProject } from './queues.js';
16
17
  import { renderQueuesModule } from './queues-module.js';
@@ -21,6 +22,13 @@ export { COMPONENT_MODEL, WASI_HTTP_INTERFACE, WASI_HTTP_VERSION };
21
22
  export const BUILD_PROFILE_NAME = 'wasmcloud-http';
22
23
  export const CRON_BUILD_PROFILE_NAME = 'wasmcloud-cron';
23
24
  export { BUILD_PROFILE_NAME as BUILD_PROFILE };
25
+ function originOf(component) {
26
+ return {
27
+ source: component.source,
28
+ ...(component.image === undefined ? {} : { image: component.image }),
29
+ ...(component.path === undefined ? {} : { path: component.path }),
30
+ };
31
+ }
24
32
  export function requirementsForProject(project, deps = DEFAULT_DEPS) {
25
33
  const bindings = discoverBindings(project, deps);
26
34
  const queueHandlers = discoverQueueHandlers(project);
@@ -130,12 +138,8 @@ async function composeComponentProvider(project, deps, io, provider, namedImport
130
138
  failureCode: 'WASMCLOUD_COMPONENT_COMPOSE_FAILED',
131
139
  });
132
140
  }
133
- /**
134
- * Plugs one provider component into the built guest: `wac plug`, or the
135
- * componentize-qjs composer when the guest has named imports to preserve.
136
- */
137
- async function composeProvider(project, deps, io, options) {
138
- const composed = `${project.outputPath}.composed`;
141
+ /** `wac` on PATH, else the SQLite toolchain's, and the PATH to run it with. */
142
+ function wacTool(deps) {
139
143
  const toolsBin = sqliteToolsBin();
140
144
  const envPath = [toolsBin, process.env.PATH ?? ''].filter(Boolean).join(':');
141
145
  const wac = deps.capture('wac', ['--version']) !== undefined
@@ -143,13 +147,43 @@ async function composeProvider(project, deps, io, options) {
143
147
  : toolsBin
144
148
  ? join(toolsBin, 'wac')
145
149
  : 'wac';
150
+ return { wac, envPath };
151
+ }
152
+ /** Whether `error` is a spawn failure because the executable does not exist. */
153
+ function isMissingExecutable(error) {
154
+ const code = error?.code;
155
+ return (code === 'ENOENT' ||
156
+ (error instanceof Error && /ENOENT|Executable not found/i.test(error.message)));
157
+ }
158
+ /** Runs `wac` (or `command`), mapping a missing `wac` binary to `WASMCLOUD_WAC_REQUIRED`. */
159
+ async function runWac(project, deps, args, command) {
160
+ const { wac, envPath } = wacTool(deps);
161
+ try {
162
+ return await deps.runCaptured(command ?? wac, args, {
163
+ cwd: project.projectRoot,
164
+ env: { ...process.env, PATH: envPath },
165
+ });
166
+ }
167
+ catch (error) {
168
+ // A missing componentize-qjs compiler surfaces as it is; only wac has an install hint here.
169
+ if (command !== undefined || !isMissingExecutable(error))
170
+ throw error;
171
+ throw new CommandFailure('WASMCLOUD_WAC_REQUIRED', 'wac is required to compose components; install it (https://github.com/bytecodealliance/wac/releases, or `scripts/install-tools.sh --wac-only` in di-framework/platform `platform/sqlite-component`) and put it on PATH', 3, { application: project.applicationName, tool: 'wac' });
172
+ }
173
+ }
174
+ /**
175
+ * Plugs one provider component into the built guest: `wac plug`, or the
176
+ * componentize-qjs composer when the guest has named imports to preserve.
177
+ */
178
+ async function composeProvider(project, deps, io, options) {
179
+ const composed = `${project.outputPath}.composed`;
146
180
  io.stdout.write(`Composing ${options.label} provider...\n`);
147
181
  const compiler = options.namedImports ? deps.componentizeQjsPath() : undefined;
148
182
  if (options.namedImports && !compiler)
149
183
  throw new CommandFailure('WASMCLOUD_COMPILER_REQUIRED', 'Managed PostgreSQL needs componentize-qjs 0.4.4-di.3 or newer for named-import composition', 3);
150
- const result = await deps.runCaptured(compiler ?? wac, compiler
184
+ const result = await runWac(project, deps, compiler
151
185
  ? ['compose', project.outputPath, '--definition', options.wasm, '-o', composed]
152
- : ['plug', '--plug', options.wasm, project.outputPath, '-o', composed], { cwd: project.projectRoot, env: { ...process.env, PATH: envPath } });
186
+ : ['plug', '--plug', options.wasm, project.outputPath, '-o', composed], compiler);
153
187
  if (result.exitCode !== 0) {
154
188
  throw new CommandFailure(options.failureCode, `Composition of ${options.label} failed: ${result.stderr || result.stdout}`, 3, { application: project.applicationName, exitCode: result.exitCode });
155
189
  }
@@ -180,6 +214,81 @@ async function inspectComponentImports(project, requirements, deps, composedAway
180
214
  }
181
215
  }
182
216
  }
217
+ /** The world of a component, as `jco wit` prints it. */
218
+ async function componentWorld(project, deps, path, label) {
219
+ const captured = await deps.runCaptured(requireNodeBinary(deps.nodeBinaryPath()), [deps.jcoCliPath(), 'wit', path], { cwd: project.projectRoot });
220
+ if (captured.exitCode !== 0 && /Cannot find module/.test(captured.stderr)) {
221
+ throw new CommandFailure('WASMCLOUD_JCO_REQUIRED', `jco is required to read the WIT world of the ${label}, but ${deps.jcoCliPath()} could not be loaded; reinstall @di-framework/cli-plugin-platform (it depends on @bytecodealliance/jco)`, 3, { application: project.applicationName, tool: 'jco' });
222
+ }
223
+ if (captured.exitCode !== 0) {
224
+ throw new CommandFailure('WASMCLOUD_COMPONENT_IMPORTS_UNREADABLE', `Could not read the WIT world of the ${label}: ${(captured.stderr || captured.stdout).trim()}`, 3, { application: project.applicationName, path });
225
+ }
226
+ return worldInterfaces(captured.stdout);
227
+ }
228
+ function notInterposed(project, problem) {
229
+ return new CommandFailure('WASMCLOUD_PGLITE_ENCRYPTION_NOT_INTERPOSED', `The PGlite encryption layer would not sit between the provider and the host filesystem: ` +
230
+ `${problem}. PGlite would write its data directory in plaintext, so the build stops. ` +
231
+ 'Use a layer built for the WASI versions the pinned provider imports.', 3, { application: project.applicationName });
232
+ }
233
+ /**
234
+ * Composes the encryption layer into the provider and writes the result to `output`, which the
235
+ * build then plugs into the guest instead of the provider.
236
+ *
237
+ * `wac plug` silently skips a layer export whose name matches but whose type is not a subtype of
238
+ * the provider's import, and exits 0 when anything else plugged, so it cannot prove the layer is
239
+ * in the path. Instead the build reads both worlds with `jco wit`, plans which layer export each
240
+ * provider import takes (every `wasi:filesystem/*` import must have one), and composes a WAC
241
+ * document that passes each of them as a named instantiation argument (`wac compose`). wac
242
+ * type-checks every argument, so a layer that does not fit fails the build here rather than
243
+ * being bypassed. The document is kept at `.di-framework/pglite-encryption.wac`.
244
+ *
245
+ * Wiring cannot show that the layer encrypts: a pass-through layer wires the same way. So the
246
+ * layer must also carry the platform's `di-framework:pglite-encfs` custom section. That marker
247
+ * catches the wrong artifact (a no-op or debug layer, a stale local build); it is forgeable, so
248
+ * what the layer actually does rests on the digest pin.
249
+ */
250
+ export async function encryptProvider(project, deps, io, provider, layer, output) {
251
+ if (encfsSection(readFileSync(layer)) === undefined) {
252
+ throw new CommandFailure('WASMCLOUD_PGLITE_ENCRYPTION_LAYER_UNMARKED', `The PGlite encryption layer ${layer} has no ${ENCFS_SECTION} custom section, so it is not ` +
253
+ "the platform's pglite-encfs component; pin the published ghcr.io/di-framework/pglite-encfs image", 3, { application: project.applicationName, path: layer });
254
+ }
255
+ const providerWorld = await componentWorld(project, deps, provider, 'PGlite provider');
256
+ const layerWorld = await componentWorld(project, deps, layer, 'PGlite encryption layer');
257
+ const plan = planWiring(providerWorld, layerWorld);
258
+ if (plan.problem !== undefined)
259
+ throw notInterposed(project, plan.problem);
260
+ const document = join(dirname(output), 'pglite-encryption.wac');
261
+ writeFileSync(document, encryptionComposition(plan.wires, providerWorld.exports));
262
+ rmSync(output, { force: true });
263
+ io.stdout.write('Composing the PGlite encryption layer into the provider...\n');
264
+ const result = await runWac(project, deps, [
265
+ 'compose',
266
+ document,
267
+ '--dep',
268
+ `${LAYER_PACKAGE}=${layer}`,
269
+ '--dep',
270
+ `${PROVIDER_PACKAGE}=${provider}`,
271
+ '-o',
272
+ output,
273
+ ]);
274
+ if (result.exitCode !== 0 || !existsSync(output)) {
275
+ const reason = (result.stderr || result.stdout).trim() || 'wac wrote no component';
276
+ throw notInterposed(project, `wac compose refused the wiring: ${reason}`);
277
+ }
278
+ }
279
+ /**
280
+ * The encryption layer reads its key from `DI_PGLITE_KEY`, which reaches the guest only through
281
+ * the control Secret, and deploy keeps only the keys the project declares there.
282
+ */
283
+ function assertPgliteKeyDeclared(project) {
284
+ if (project.pglite?.encryption === undefined)
285
+ return;
286
+ if (project.controlSecretKeys?.includes(PGLITE_KEY_ENV))
287
+ return;
288
+ throw new CommandFailure('WASMCLOUD_PGLITE_KEY_UNDECLARED', `${project.applicationName} turns on "pglite.encryption", whose layer reads its key from ` +
289
+ `${PGLITE_KEY_ENV} in the workload's control Secret; add "${PGLITE_KEY_ENV}" to ` +
290
+ `"controlSecretKeys" in di-framework.config.json`, 2, { application: project.applicationName });
291
+ }
183
292
  /**
184
293
  * The PGlite provider for a guest that imports `di-framework:pglite/database`. The config
185
294
  * and the import must agree: the deploy marks the component exclusive and gives it storage
@@ -196,8 +305,17 @@ async function resolvePglite(project, imported, io, deps, deploy) {
196
305
  }
197
306
  return resolvePgliteComponent(project.pglite, io, deps, project.projectRoot, { deploy });
198
307
  }
308
+ /** The encryption layer for the provider, when `pglite.encryption` is set. */
309
+ async function resolveEncryption(project, io, deps, deploy) {
310
+ const encryption = project.pglite?.encryption;
311
+ if (encryption === undefined)
312
+ return undefined;
313
+ return resolvePgliteEncryption(encryption, io, deps, project.projectRoot, { deploy });
314
+ }
199
315
  /** The disposable `.di-framework/` build directory: WIT world, bundle, and manifests. */
200
316
  export async function buildComponent(project, io, deps, options = {}) {
317
+ // A config check: before bundling and before anything is pulled.
318
+ assertPgliteKeyDeclared(project);
201
319
  const generatedDirectory = join(project.projectRoot, '.di-framework');
202
320
  const generatedWit = join(generatedDirectory, 'wit');
203
321
  const bundledJavaScript = join(generatedDirectory, 'component.js');
@@ -305,10 +423,17 @@ export async function buildComponent(project, io, deps, options = {}) {
305
423
  }
306
424
  const needsPglite = finalRequirements.some((requirement) => requirement.package === DI_PGLITE_PACKAGE && requirement.direction === 'import');
307
425
  const pglite = await resolvePglite(project, needsPglite, io, deps, options.deploy === true);
308
- // Plug a private copy of the verified bytes: the shared cache may change after verification.
426
+ const encryption = pglite === undefined
427
+ ? undefined
428
+ : await resolveEncryption(project, io, deps, options.deploy === true);
429
+ // Plug private copies of the verified bytes: the shared cache may change after verification.
309
430
  const pgliteWasm = join(generatedDirectory, PGLITE_WASM_FILE);
431
+ const encfsWasm = join(generatedDirectory, PGLITE_ENCFS_WASM_FILE);
432
+ const encryptedWasm = join(generatedDirectory, PGLITE_ENCRYPTED_WASM_FILE);
310
433
  if (pglite !== undefined)
311
434
  writeFileSync(pgliteWasm, pglite.bytes);
435
+ if (encryption !== undefined)
436
+ writeFileSync(encfsWasm, encryption.bytes);
312
437
  const componentize = await runComponentize(project, generatedWit, bundledJavaScript, deps);
313
438
  if (componentize.exitCode !== 0) {
314
439
  throw toolFailed(componentize.tool, componentize.exitCode);
@@ -323,9 +448,11 @@ export async function buildComponent(project, io, deps, options = {}) {
323
448
  await composeComponentProvider(project, deps, io, provider, namedImports);
324
449
  }
325
450
  if (pglite !== undefined) {
451
+ if (encryption !== undefined)
452
+ await encryptProvider(project, deps, io, pgliteWasm, encfsWasm, encryptedWasm);
326
453
  await composeProvider(project, deps, io, {
327
454
  label: `${DI_PGLITE_PACKAGE}@${DI_PGLITE_VERSION}`,
328
- wasm: pgliteWasm,
455
+ wasm: encryption === undefined ? pgliteWasm : encryptedWasm,
329
456
  namedImports,
330
457
  failureCode: 'WASMCLOUD_PGLITE_COMPOSE_FAILED',
331
458
  });
@@ -342,7 +469,9 @@ export async function buildComponent(project, io, deps, options = {}) {
342
469
  ? join(deps.assetsDirectory(), 'sqlite', 'di-framework-sqlite.wasm')
343
470
  : undefined, [
344
471
  ...composedProviders.map((provider) => provider.wasm),
472
+ // The raw provider and layer bytes, never wac's output, so only the inputs set the key.
345
473
  ...(pglite === undefined ? [] : [pgliteWasm]),
474
+ ...(encryption === undefined ? [] : [encfsWasm]),
346
475
  ]);
347
476
  const artifactDigest = digestBytes(readFileSync(project.outputPath));
348
477
  const summary = {
@@ -358,9 +487,8 @@ export async function buildComponent(project, io, deps, options = {}) {
358
487
  ? {}
359
488
  : {
360
489
  pglite: {
361
- source: pglite.source,
362
- ...(pglite.image === undefined ? {} : { image: pglite.image }),
363
- ...(pglite.path === undefined ? {} : { path: pglite.path }),
490
+ ...originOf(pglite),
491
+ ...(encryption === undefined ? {} : { encryption: originOf(encryption) }),
364
492
  },
365
493
  }),
366
494
  };
@@ -1,3 +1,4 @@
1
+ import { RENDERED_ENVIRONMENT_KEYS } from '../environment-names.js';
1
2
  import { STORAGE_HOSTGROUP } from '../workload.js';
2
3
  import { ConsoleError, platformSentence, sanitizePublicText } from './errors.js';
3
4
  const RESOURCE_NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/;
@@ -5,7 +6,7 @@ const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
5
6
  const HOST_NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/i;
6
7
  const SENSITIVE_KEY = /(TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|PRIVATE|API_KEY|_KEY$)/i;
7
8
  const USERINFO = /:\/\/[^/\s:]+:[^/\s@]+@/;
8
- const HIDDEN_CONFIG = /^(DI_CONTROL_|DI_QUEUE_|DI_CRON_|DI_SQLITE_|DI_STORAGE_)|^(ACTOR_STORAGE_DIR|QUEUE_DB_PATH|MIGRATION_DB_PATH)$/;
9
+ const HIDDEN_CONFIG = new RegExp(`^(DI_CONTROL_|DI_QUEUE_|DI_CRON_|DI_SQLITE_|DI_STORAGE_)|^(${RENDERED_ENVIRONMENT_KEYS.join('|')})$`);
9
10
  const PLATFORM_CONTRACTS = new Set([
10
11
  'wasi:http',
11
12
  'wasi:cli',
@@ -1,5 +1,5 @@
1
1
  /** Cluster-private control-plane authentication for cron/queue/actor admin APIs. */
2
- /** Unconfigured local/dev only. Never includes `admin`. */
2
+ /** Unconfigured local/dev only (never a deployed workload). Never includes `admin`. */
3
3
  const ANONYMOUS_IDENTITY = { id: 'anonymous', token: '', roles: ['invoke'] };
4
4
  function isIdentityEntry(entry) {
5
5
  if (entry === null || typeof entry !== 'object')
@@ -46,7 +46,19 @@ function parseIdentities() {
46
46
  return { identities: singleTokenIdentities(), configured: true };
47
47
  }
48
48
  const identities = singleTokenIdentities();
49
- return { identities, configured: identities.length > 0 };
49
+ return { identities, configured: identities.length > 0 || isDeployed() };
50
+ }
51
+ /**
52
+ * A deployed workload: deploy renders the control host settings, and the control Secret supplies
53
+ * `DI_CONTROL_IDENTITY`. Such a workload without a usable token fails closed instead of falling
54
+ * back to anonymous invoke, so a control Secret that lost `DI_CONTROL_TOKEN` (for example one
55
+ * rewritten by app tooling) cannot open cron, queue and actor endpoints.
56
+ */
57
+ function isDeployed() {
58
+ return (process.env.DI_CONTROL_REJECT_FORWARDED === '1' ||
59
+ (process.env.DI_CONTROL_HTTP_HOST ?? '').trim() !== '' ||
60
+ process.env.DI_CONTROL_IDENTITY !== undefined ||
61
+ process.env.DI_CONTROL_TOKEN !== undefined);
50
62
  }
51
63
  function hasRequiredRole(identity, requiredRoles) {
52
64
  return !requiredRoles.some((role) => !identity.roles.includes(role) && !identity.roles.includes('admin'));
package/dist/deploy.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { CliIo, CommandResult } from '@di-framework/cli-extension';
2
+ import { type BuildSummary } from './build.js';
2
3
  import { type WasmcloudDeps } from './deps.js';
3
4
  import type { RegistryLocation } from './registry.js';
4
5
  export type WasmcloudDeployData = {
@@ -21,12 +22,11 @@ export type WasmcloudDeployData = {
21
22
  host: string;
22
23
  };
23
24
  endpoints?: Record<string, string>;
24
- /** Where the composed PGlite provider came from: a digest pin or a local file. */
25
- pglite?: {
26
- source: 'local' | 'cache' | 'registry';
27
- image?: string;
28
- path?: string;
29
- };
25
+ /**
26
+ * Where the composed PGlite provider came from (a digest pin or a local file) and, when
27
+ * `pglite.encryption` is set, its encryption layer.
28
+ */
29
+ pglite?: BuildSummary['pglite'];
30
30
  };
31
31
  export type WasmcloudDeployResult = Omit<CommandResult, 'data' | 'text'> & {
32
32
  data: WasmcloudDeployData;
package/dist/deploy.js CHANGED
@@ -66,10 +66,14 @@ export async function runWasmcloudDeploy(args, io, deps = DEFAULT_DEPS) {
66
66
  ].join(''),
67
67
  };
68
68
  }
69
+ function originText(origin) {
70
+ return origin.path === undefined ? `${origin.image}` : `local ${origin.path} (unverified)`;
71
+ }
69
72
  function pgliteText(pglite) {
70
73
  if (pglite === undefined)
71
74
  return '';
72
- return pglite.path === undefined
73
- ? ` PGlite: ${pglite.image}.`
74
- : ` PGlite: local ${pglite.path} (unverified).`;
75
+ const encryption = pglite.encryption === undefined
76
+ ? ''
77
+ : `, encrypted at rest by ${originText(pglite.encryption)}`;
78
+ return ` PGlite: ${originText(pglite)}${encryption}.`;
75
79
  }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Environment names the CLI renders into a workload's `localResources.environment.config`
3
+ * without a `DI_` prefix (every `DI_*` name is the framework's as well). The console hides them,
4
+ * and `controlSecretKeys` may not declare them, so a Secret key never shadows one.
5
+ */
6
+ export declare const RENDERED_ENVIRONMENT_KEYS: readonly string[];
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Environment names the CLI renders into a workload's `localResources.environment.config`
3
+ * without a `DI_` prefix (every `DI_*` name is the framework's as well). The console hides them,
4
+ * and `controlSecretKeys` may not declare them, so a Secret key never shadows one.
5
+ */
6
+ export const RENDERED_ENVIRONMENT_KEYS = [
7
+ 'ACTOR_STORAGE_DIR',
8
+ 'QUEUE_DB_PATH',
9
+ 'MIGRATION_DB_PATH',
10
+ ];
package/dist/index.d.ts CHANGED
@@ -29,6 +29,6 @@ export { BACKING_SERVICE_API_VERSION, BACKING_SERVICE_KIND, BACKING_SERVICE_RESO
29
29
  export { resolveConnection, resolveTarget } from './target.js';
30
30
  export { renderWashDevYaml, writeWashDevConfig } from './wash-dev.js';
31
31
  export { aggregateRequirements, COMPONENT_MODEL, DI_QUEUES_INTERFACE, DI_QUEUES_PACKAGE, DI_QUEUES_VERSION, defaultProjectRequirements, HTTP_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_SOURCE, queueProjectRequirements, renderWorldWit, runtimeRequirementsFromJavaScript, socketRequirementsFromJavaScript, type WitRequirement, } from './wit.js';
32
- export { applyWorkload, type ControlSecretWrite, CRON_INVOKER_IMAGE, controlSecretDocument, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteControlSecret, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, type WorkloadManifestOptions, writeControlSecret, } from './workload.js';
32
+ export { applyWorkload, CONTROL_SECRET_CLI_KEYS, type ControlSecretWrite, CRON_INVOKER_IMAGE, controlSecretDocument, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteControlSecret, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, type WorkloadManifestOptions, writeControlSecret, } from './workload.js';
33
33
  declare const _default: import("@di-framework/cli-extension").ExtensionManifest;
34
34
  export default _default;
package/dist/index.js CHANGED
@@ -31,7 +31,7 @@ export { BACKING_SERVICE_API_VERSION, BACKING_SERVICE_KIND, BACKING_SERVICE_RESO
31
31
  export { resolveConnection, resolveTarget } from './target.js';
32
32
  export { renderWashDevYaml, writeWashDevConfig } from './wash-dev.js';
33
33
  export { aggregateRequirements, COMPONENT_MODEL, DI_QUEUES_INTERFACE, DI_QUEUES_PACKAGE, DI_QUEUES_VERSION, defaultProjectRequirements, HTTP_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_SOURCE, queueProjectRequirements, renderWorldWit, runtimeRequirementsFromJavaScript, socketRequirementsFromJavaScript, } from './wit.js';
34
- export { applyWorkload, CRON_INVOKER_IMAGE, controlSecretDocument, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteControlSecret, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, writeControlSecret, } from './workload.js';
34
+ export { applyWorkload, CONTROL_SECRET_CLI_KEYS, CRON_INVOKER_IMAGE, controlSecretDocument, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteControlSecret, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, writeControlSecret, } from './workload.js';
35
35
  export default defineExtension({
36
36
  schemaVersion: 1,
37
37
  name: 'platform',