@brickkit/cli 0.11.0 → 0.13.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 (177) hide show
  1. package/dashboard-dist/CollapsiblePanel-CbUysOp5.js +2 -0
  2. package/dashboard-dist/CompositeRoot-D4sRkYq3.js +1 -0
  3. package/dashboard-dist/Geist-Variable.woff2 +0 -0
  4. package/dashboard-dist/GeistMono-Variable.woff2 +0 -0
  5. package/dashboard-dist/PopoverPopup-CiI2avT_.js +1 -0
  6. package/dashboard-dist/api-reference-mT9VNcPb.js +265 -0
  7. package/dashboard-dist/app.css +2 -2
  8. package/dashboard-dist/app.js +12 -13
  9. package/dashboard-dist/ccount-CcG1m-Yh.js +1 -0
  10. package/dashboard-dist/client-CwATkLJa.js +1 -0
  11. package/dashboard-dist/core-BEUWp6B5.js +1 -0
  12. package/dashboard-dist/docs-BRrtyxDB.js +4 -0
  13. package/dashboard-dist/docs.css +1 -1
  14. package/dashboard-dist/kit.js +1 -1
  15. package/dashboard-dist/popover-Bj9x-88h.js +1 -0
  16. package/dist/bin.d.ts +0 -2
  17. package/dist/bin.js +309 -211
  18. package/dist/bin.js.map +1 -1
  19. package/dist/build.js +463 -0
  20. package/dist/build.js.map +1 -0
  21. package/dist/client-contract-file.js +356 -1
  22. package/dist/client-contract-file.js.map +1 -0
  23. package/dist/compiler.d.ts +12 -3
  24. package/dist/compiler.js +1 -1
  25. package/dist/compiler2.js +13 -7
  26. package/dist/compiler2.js.map +1 -1
  27. package/dist/config.d.ts +3 -0
  28. package/dist/config.js +1 -252
  29. package/dist/config2.d.ts +122 -0
  30. package/dist/config2.js +207 -0
  31. package/dist/config2.js.map +1 -0
  32. package/dist/dashboard-extension.d.ts +3 -2
  33. package/dist/{dev-telemetry-store.js → dashboard-host.js} +1381 -1432
  34. package/dist/dashboard-host.js.map +1 -0
  35. package/dist/dashboard-protocol.js +189 -0
  36. package/dist/dashboard-protocol.js.map +1 -0
  37. package/dist/dashboard.d.ts +8 -135
  38. package/dist/definitions.js +33 -0
  39. package/dist/definitions.js.map +1 -0
  40. package/dist/dev-application.js +34 -0
  41. package/dist/dev-application.js.map +1 -0
  42. package/dist/dev-protocol.js +21 -0
  43. package/dist/dev-protocol.js.map +1 -0
  44. package/dist/dev-reporter.d.ts +0 -2
  45. package/dist/dev-reporter.js +3 -3
  46. package/dist/dev-reporter.js.map +1 -1
  47. package/dist/dev-telemetry.js +8 -24
  48. package/dist/dev-telemetry.js.map +1 -1
  49. package/dist/dev-worker.js +80 -21
  50. package/dist/dev-worker.js.map +1 -1
  51. package/dist/index.d.ts +18 -87
  52. package/dist/index.js +12 -6
  53. package/dist/index.js.map +1 -0
  54. package/dist/lint/oxlint.d.ts +0 -2
  55. package/dist/lint/oxlint.js +6 -5
  56. package/dist/lint/oxlint.js.map +1 -1
  57. package/dist/own-module.js +7 -0
  58. package/dist/own-module.js.map +1 -0
  59. package/dist/plugin.d.ts +6 -11
  60. package/dist/plugin.js +6 -42
  61. package/dist/plugin.js.map +1 -1
  62. package/dist/production-dashboard.d.ts +2 -0
  63. package/dist/production-dashboard.js +51 -0
  64. package/dist/production-dashboard.js.map +1 -0
  65. package/dist/production-dashboard2.d.ts +34 -0
  66. package/dist/{presets.js → project.js} +107 -113
  67. package/dist/project.js.map +1 -0
  68. package/dist/serve.d.ts +24 -0
  69. package/dist/serve.js +1 -0
  70. package/dist/serve2.js +49 -0
  71. package/dist/serve2.js.map +1 -0
  72. package/dist/vite.d.ts +0 -2
  73. package/dist/vite.js +28 -51
  74. package/dist/vite.js.map +1 -1
  75. package/dist/workflows.d.ts +2 -4
  76. package/dist/workflows2.js +60 -39
  77. package/dist/workflows2.js.map +1 -1
  78. package/inspector-dist/client/assets/api.rpc-BvRk9kiK.js +0 -0
  79. package/inspector-dist/client/assets/api.stream._streamId-BvRk9kiK.js +0 -0
  80. package/inspector-dist/client/assets/app-CeSwVsRm.css +2 -0
  81. package/inspector-dist/client/assets/dist-BK8w6xOr.js +3930 -0
  82. package/inspector-dist/client/assets/dist-CG2aVufI.js +197 -0
  83. package/inspector-dist/client/assets/entry.client-D9jbgmTR.js +9391 -0
  84. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-CfRnuITN.js +34 -0
  85. package/inspector-dist/client/assets/home-hwPlkNhv.js +4034 -0
  86. package/inspector-dist/client/assets/jsx-runtime-CPEah4WQ.js +7084 -0
  87. package/inspector-dist/client/assets/manifest-0e76e9ac.js +1 -0
  88. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-ZDR2PNY_.js +1 -0
  89. package/inspector-dist/client/assets/root-ChBNTZd2.css +2 -0
  90. package/inspector-dist/client/assets/root-SLeEf-sT.js +320 -0
  91. package/inspector-dist/client/assets/run-detail-DYbVkIFH.js +1871 -0
  92. package/inspector-dist/client/assets/tabs-CaJisoyb.js +73751 -0
  93. package/inspector-dist/client/assets/tabs-L5XKzOpP.css +1 -0
  94. package/inspector-dist/client/assets/zstd-browser-decoder-D94wmfAU.js +41 -0
  95. package/inspector-dist/server/assets/app-DGlfWVUI.js +99330 -0
  96. package/inspector-dist/server/assets/chunk-RLXIAIE6-F0SJZlei.js +42975 -0
  97. package/inspector-dist/server/assets/dist-BCbwm6jl.js +10325 -0
  98. package/inspector-dist/server/assets/dist-CG2aVufI.js +197 -0
  99. package/inspector-dist/server/assets/dist-Ce0I2PUv.js +1137 -0
  100. package/inspector-dist/server/assets/dist-DY0UlahA.js +1642 -0
  101. package/inspector-dist/server/assets/encryption-DdQgC8Rk.js +886 -0
  102. package/inspector-dist/server/assets/event-metadata-n7E4zEmT.js +145 -0
  103. package/inspector-dist/server/assets/functions-CNVQtbgg.js +1170 -0
  104. package/inspector-dist/server/assets/global-singleton-D8sIN5du.js +80 -0
  105. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-CWRzMxYD.js +34 -0
  106. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-D0v0ngVr.js +1 -0
  107. package/inspector-dist/server/assets/parse-Begau9cA.js +469 -0
  108. package/inspector-dist/server/assets/rolldown-runtime-C1I3wEg2.js +43 -0
  109. package/inspector-dist/server/assets/serialization-format-BbuGfHog.js +476 -0
  110. package/inspector-dist/server/assets/token-BgMmJNP5.js +60 -0
  111. package/inspector-dist/server/assets/token-BrUX0bxz.js +55 -0
  112. package/inspector-dist/server/assets/token-util-DZN32qmT.js +455 -0
  113. package/inspector-dist/server/assets/wrapper-CIC3w0oC.js +3624 -0
  114. package/inspector-dist/server/assets/ws-transport-CxTYB11n.js +29476 -0
  115. package/inspector-dist/server/assets/zstd-browser-decoder-D7bCXbGg.js +38 -0
  116. package/inspector-dist/server/index.js +1 -58
  117. package/package.json +39 -28
  118. package/vite-client.d.ts +1 -1
  119. package/dashboard-dist/CollapsiblePanel-BX79_W-b.js +0 -2
  120. package/dashboard-dist/CompositeRoot-xzybXjnx.js +0 -1
  121. package/dashboard-dist/PopoverPopup-CvlmC7EL.js +0 -1
  122. package/dashboard-dist/api-reference-BcAYVYwJ.js +0 -260
  123. package/dashboard-dist/core-BGO9JZ1r.js +0 -1
  124. package/dashboard-dist/docs-DHikPD2v.js +0 -4
  125. package/dashboard-dist/popover-DG498XHH.js +0 -1
  126. package/dist/app-entry.js +0 -1
  127. package/dist/app-entry2.js +0 -19
  128. package/dist/app-entry2.js.map +0 -1
  129. package/dist/bin.d.ts.map +0 -1
  130. package/dist/client-contract-file2.js +0 -34
  131. package/dist/client-contract-file2.js.map +0 -1
  132. package/dist/client-contract.js +0 -1
  133. package/dist/client-contract2.js +0 -294
  134. package/dist/client-contract2.js.map +0 -1
  135. package/dist/config.js.map +0 -1
  136. package/dist/dashboard-extension.d.ts.map +0 -1
  137. package/dist/dev-reporter.d.ts.map +0 -1
  138. package/dist/dev-telemetry-store.js.map +0 -1
  139. package/dist/emit.d.ts +0 -7
  140. package/dist/emit.d.ts.map +0 -1
  141. package/dist/index.d.ts.map +0 -1
  142. package/dist/lint/oxlint.d.ts.map +0 -1
  143. package/dist/plugin.d.ts.map +0 -1
  144. package/dist/presets.js.map +0 -1
  145. package/dist/runner.js +0 -523
  146. package/dist/runner.js.map +0 -1
  147. package/dist/vite.d.ts.map +0 -1
  148. package/dist/workflows.d.ts.map +0 -1
  149. package/inspector-dist/client/assets/api.rpc-l0sNRNKZ.js +0 -1
  150. package/inspector-dist/client/assets/api.stream._streamId-l0sNRNKZ.js +0 -1
  151. package/inspector-dist/client/assets/app-CvoGgWcV.css +0 -1
  152. package/inspector-dist/client/assets/entry.client-BJ6G3n5t.js +0 -11697
  153. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-C-3wZnxf.js +0 -19
  154. package/inspector-dist/client/assets/home-CSKAS4P2.js +0 -4979
  155. package/inspector-dist/client/assets/index-DECCyMR0.js +0 -4482
  156. package/inspector-dist/client/assets/index-Dot7CgrA.js +0 -9837
  157. package/inspector-dist/client/assets/index-HqNj_XIX.js +0 -200
  158. package/inspector-dist/client/assets/manifest-139c9319.js +0 -1
  159. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-DC0K8uTy.js +0 -58626
  160. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-F88p7PFX.css +0 -1
  161. package/inspector-dist/client/assets/root-BMHd_XHz.css +0 -1
  162. package/inspector-dist/client/assets/root-cbi6iYwg.js +0 -305
  163. package/inspector-dist/client/assets/run-detail-CWoGxu_0.css +0 -1
  164. package/inspector-dist/client/assets/run-detail-Cc7tSGNq.js +0 -6237
  165. package/inspector-dist/client/assets/world-config-context-BAD1QCrR.js +0 -26
  166. package/inspector-dist/client/assets/zstd-browser-decoder-BQoRpP7L.js +0 -28
  167. package/inspector-dist/server/assets/app-DUP5RybL.js +0 -174880
  168. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-D2g4hL2-.js +0 -71
  169. package/inspector-dist/server/assets/index-BfLBLRRi.js +0 -204
  170. package/inspector-dist/server/assets/index-BzrGWk7J.js +0 -1164
  171. package/inspector-dist/server/assets/index-D71yP6AL.js +0 -191
  172. package/inspector-dist/server/assets/index-wGSWRns3.js +0 -1296
  173. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-DsvuKoEV.js +0 -58
  174. package/inspector-dist/server/assets/token-ClUZZwXl.js +0 -95
  175. package/inspector-dist/server/assets/token-util-DSxMZ6nI.js +0 -33
  176. package/inspector-dist/server/assets/wrapper-B3vstpCO.js +0 -67
  177. package/inspector-dist/server/assets/zstd-browser-decoder-Dn82m2BU.js +0 -77
@@ -0,0 +1,886 @@
1
+ import { r as __exportAll } from "./rolldown-runtime-C1I3wEg2.js";
2
+ import { k as WorkflowRuntimeError, m as RuntimeDecryptionError } from "./dist-Ce0I2PUv.js";
3
+ var KEY_LENGTH = 32;
4
+ /**
5
+ * Import a raw AES-256 key as a `CryptoKey` for use with `encrypt()`/`decrypt()`.
6
+ *
7
+ * Callers should call this once per run (after `getEncryptionKeyForRun()`)
8
+ * and pass the resulting `CryptoKey` to all subsequent encrypt/decrypt calls.
9
+ *
10
+ * Pass `usages: ['encrypt']` (or `['decrypt']`) for cross-run scenarios
11
+ * where the caller should not be able to perform the inverse operation
12
+ * with the key. For example, a child workflow writing into a parent
13
+ * run's forwarded WritableStream only needs to encrypt, never decrypt.
14
+ *
15
+ * @param raw - Raw 32-byte AES-256 key (from World.getEncryptionKeyForRun)
16
+ * @param usages - Key usages. Defaults to `['encrypt', 'decrypt']`.
17
+ * @returns CryptoKey ready for AES-GCM operations
18
+ */
19
+ async function importKey(raw, usages = ["encrypt", "decrypt"]) {
20
+ if (raw.byteLength !== KEY_LENGTH) throw new WorkflowRuntimeError(`Encryption key must be exactly ${KEY_LENGTH} bytes, got ${raw.byteLength}`);
21
+ return globalThis.crypto.subtle.importKey("raw", raw, "AES-GCM", false, usages);
22
+ }
23
+ /**
24
+ * Encrypt data using AES-256-GCM.
25
+ *
26
+ * @param key - CryptoKey from `importKey()`
27
+ * @param data - Plaintext to encrypt
28
+ * @param aad - Optional additional authenticated data. Not encrypted, but
29
+ * covered by the GCM auth tag: decryption fails unless the exact same
30
+ * bytes are supplied. Used by the sealed-box layer to bind ciphertext to
31
+ * a `projectId|runId` context. Omit for no AAD (the legacy behavior).
32
+ * @returns `[nonce (12 bytes)][ciphertext + GCM auth tag]`
33
+ */
34
+ async function encrypt$1(key, data, aad) {
35
+ const nonce = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
36
+ let ciphertext;
37
+ try {
38
+ ciphertext = await globalThis.crypto.subtle.encrypt({
39
+ name: "AES-GCM",
40
+ iv: nonce,
41
+ tagLength: 128,
42
+ ...aad ? { additionalData: aad } : {}
43
+ }, key, data);
44
+ } catch (cause) {
45
+ throw new RuntimeDecryptionError(`AES-256-GCM encryption failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
46
+ cause,
47
+ context: {
48
+ operation: "encrypt",
49
+ byteLength: data.byteLength
50
+ }
51
+ });
52
+ }
53
+ const result = new Uint8Array(12 + ciphertext.byteLength);
54
+ result.set(nonce, 0);
55
+ result.set(new Uint8Array(ciphertext), 12);
56
+ return result;
57
+ }
58
+ /**
59
+ * Decrypt data using AES-256-GCM.
60
+ *
61
+ * Any failure inside the Web Crypto layer (most commonly an
62
+ * `OperationError: The operation failed for an operation-specific reason`
63
+ * raised by `AESCipherJob.onDone` when the GCM authentication tag does
64
+ * not verify) is rewrapped as {@link RuntimeDecryptionError}. The
65
+ * wrapped error carries the original DOMException as `cause`, plus a
66
+ * small diagnostic context (`operation`, input `byteLength`) to help
67
+ * disambiguate ciphertext corruption from key mismatch from truncated
68
+ * transport reads.
69
+ *
70
+ * Note: `data` is the raw AES payload (`[nonce][ciphertext + tag]`), not a
71
+ * format-prefixed envelope: callers strip the `encr` marker via
72
+ * `decodeFormatPrefix()` before reaching this function. The outer
73
+ * envelope's format prefix is therefore attached by the serialization
74
+ * layer (`serialization/encryption.ts`), which is the layer that has it.
75
+ *
76
+ * @param key - CryptoKey from `importKey()`
77
+ * @param data - `[nonce (12 bytes)][ciphertext + GCM auth tag]`
78
+ * @param aad - Optional additional authenticated data. Must match the bytes
79
+ * passed to {@link encrypt} exactly, otherwise the GCM tag fails to verify
80
+ * and a {@link RuntimeDecryptionError} is thrown.
81
+ * @returns Decrypted plaintext
82
+ */
83
+ async function decrypt$1(key, data, aad) {
84
+ const minLength = 28;
85
+ if (data.byteLength < minLength) throw new RuntimeDecryptionError(`Encrypted data too short: expected at least ${minLength} bytes, got ${data.byteLength}`, { context: {
86
+ operation: "decrypt",
87
+ byteLength: data.byteLength
88
+ } });
89
+ const nonce = data.subarray(0, 12);
90
+ const ciphertext = data.subarray(12);
91
+ let plaintext;
92
+ try {
93
+ plaintext = await globalThis.crypto.subtle.decrypt({
94
+ name: "AES-GCM",
95
+ iv: nonce,
96
+ tagLength: 128,
97
+ ...aad ? { additionalData: aad } : {}
98
+ }, key, ciphertext);
99
+ } catch (cause) {
100
+ const causeMsg = cause instanceof Error ? cause.message : String(cause);
101
+ throw new RuntimeDecryptionError(`AES-256-GCM decryption failed: ${causeMsg}`, {
102
+ cause,
103
+ context: {
104
+ operation: "decrypt",
105
+ byteLength: data.byteLength
106
+ }
107
+ });
108
+ }
109
+ return new Uint8Array(plaintext);
110
+ }
111
+ // ../../node_modules/.bun/@workflow+core@5.3.0+eefe5d4a997ff1ee/node_modules/@workflow/core/dist/sealed-box.js
112
+ /**
113
+ * Browser-compatible sealed-box (asymmetric) encryption for cross-run writes.
114
+ *
115
+ * ## Why this exists
116
+ *
117
+ * The symmetric `encr` path requires the writer to hold the recipient run's
118
+ * key, which also grants decrypt capability. For *cross-run* writes (a hook
119
+ * resumption targeting another run, or a child workflow writing into a
120
+ * parent's forwarded `WritableStream`) that is more authority than the writer
121
+ * needs, and obtaining the symmetric key across a deployment boundary costs a
122
+ * round trip to the Vercel API.
123
+ *
124
+ * A sealed box fixes both: the writer needs only the recipient's **public**
125
+ * key, which is not secret and therefore travels on the run entity (and in
126
+ * stream descriptors) at no cost. "Encrypt-only" stops being an honor-system
127
+ * convention enforced by `importKey(raw, ['encrypt'])` and becomes a
128
+ * cryptographic guarantee: a writer holding only the public key provably
129
+ * cannot read anything.
130
+ *
131
+ * ## Key hierarchy
132
+ *
133
+ * Both keys descend from the same per-run key material `K` that
134
+ * `World.getEncryptionKeyForRun()` already returns today, so nothing about
135
+ * key acquisition, the World interface, or the Vercel API changes:
136
+ *
137
+ * ```
138
+ * K (32 bytes, per-run, = HKDF(VERCEL_DEPLOYMENT_KEY, "projectId|runId"))
139
+ * ├── AES-256 key = K used directly → 'encr' envelopes (unchanged)
140
+ * └── X25519 scalar = HKDF(K, SCALAR_INFO) → 'encp' envelopes
141
+ * └── public key = X25519 basepoint · scalar (published, not secret)
142
+ * ```
143
+ *
144
+ * `K` is therefore both an AEAD key and a key-derivation key. This is sound:
145
+ * AES-GCM never exposes its key, and HKDF-SHA256 output is computationally
146
+ * independent of the AES keystream. A strict reading of NIST SP 800-108
147
+ * prefers these roles be separated, but `K`'s direct AES use is fixed by
148
+ * backward compatibility with every `encr` payload already written.
149
+ *
150
+ * ## Construction
151
+ *
152
+ * An ECIES-style sealed box using the same primitives as HPKE (RFC 9180)
153
+ * base mode with DHKEM(X25519, HKDF-SHA256) and AES-256-GCM, but without the
154
+ * full `LabeledExtract`/`LabeledExpand` suite-ID ceremony:
155
+ *
156
+ * ```
157
+ * ephemeral = X25519 keypair, freshly generated per encryption context
158
+ * sharedSecret = X25519(ephemeralPrivate, recipientPublic)
159
+ * contentKey = HKDF-SHA256(
160
+ * ikm = sharedSecret,
161
+ * salt = zeros(32),
162
+ * info = CONTENT_KEY_INFO ‖ ephemeralPublic ‖ recipientPublic,
163
+ * )
164
+ * ```
165
+ *
166
+ * Binding both public keys into `info` is the security-critical part (it is
167
+ * HPKE's `kem_context`): it prevents key-substitution/unknown-key-share
168
+ * attacks in which an adversary replays a ciphertext as though it had been
169
+ * sealed to a different recipient. Deviating from strict RFC 9180 framing is
170
+ * a deliberate, documented choice: the envelope is versioned via its format
171
+ * prefix and the HKDF labels below, so a conformant profile can be added
172
+ * later as a new version without touching existing payloads.
173
+ *
174
+ * Wire format (the `encp` format prefix is attached by the serialization
175
+ * layer, not by this module):
176
+ *
177
+ * ```
178
+ * [ephemeral public key (32 bytes)][nonce (12 bytes)][ciphertext + GCM tag (16 bytes)]
179
+ * ```
180
+ *
181
+ * ## Nonce discipline
182
+ *
183
+ * One-shot {@link seal} generates a fresh ephemeral keypair (and therefore a
184
+ * fresh content key) for every call, so nonce reuse is impossible.
185
+ *
186
+ * Callers that amortize the KEM across many frames via {@link encapsulate}
187
+ * take on nonce discipline themselves, because the content key then outlives a
188
+ * single message. Two rules apply:
189
+ *
190
+ * 1. Every frame MUST use a fresh random nonce (which `aesGcmEncrypt` does).
191
+ * Never a counter: a counter restarts at zero after a stream reconnect or a
192
+ * durable replay, reusing `(contentKey, nonce)`, which under AES-GCM leaks
193
+ * the plaintext XOR of the two frames and the GCM auth subkey.
194
+ * 2. A writer must not inherit a previous incarnation's content key, so
195
+ * {@link encapsulate} is re-run per writer instance.
196
+ *
197
+ * Nothing in this module enforces either rule; it is the streaming caller's
198
+ * contract.
199
+ */
200
+ /** Length of an X25519 private scalar and public key, in bytes. */
201
+ var X25519_KEY_LENGTH = 32;
202
+ /** Length of the AES-256 content key derived from the shared secret. */
203
+ var CONTENT_KEY_LENGTH = 32;
204
+ /**
205
+ * HKDF `info` label for deriving the per-run X25519 scalar from the per-run
206
+ * key material.
207
+ *
208
+ * Versioned and namespaced so that any future derivation from the same `K`
209
+ * (a second keypair, a MAC key, a different curve) can never collide with
210
+ * this one.
211
+ */
212
+ var SCALAR_INFO = "workflow/encp/x25519/v1";
213
+ /**
214
+ * HKDF `info` prefix for deriving the AES-256-GCM content key from an X25519
215
+ * shared secret. The ephemeral and recipient public keys are appended to this
216
+ * label to form the full `info` (HPKE's `kem_context`).
217
+ */
218
+ var CONTENT_KEY_INFO = "workflow/encp/aes256gcm/v1";
219
+ /**
220
+ * DER prefix for an RFC 8410 `PrivateKeyInfo` wrapping a raw X25519 scalar.
221
+ *
222
+ * Web Crypto cannot import a raw X25519 private key (`importKey('raw', ...)`
223
+ * is only defined for public keys on the Secure Curves algorithms), so a
224
+ * derived scalar has to be wrapped in PKCS#8 before it can be used. The
225
+ * structure is fully determined for a 32-byte X25519 key:
226
+ *
227
+ * ```
228
+ * SEQUENCE (46 bytes) 30 2e
229
+ * INTEGER 0 02 01 00
230
+ * SEQUENCE (5 bytes) 30 05
231
+ * OBJECT IDENTIFIER 1.3.101.110 (X25519) 06 03 2b 65 6e
232
+ * OCTET STRING (34 bytes) 04 22
233
+ * OCTET STRING (32 bytes) 04 20
234
+ * <scalar>
235
+ * ```
236
+ */
237
+ var PKCS8_X25519_PREFIX = new Uint8Array([
238
+ 48,
239
+ 46,
240
+ 2,
241
+ 1,
242
+ 0,
243
+ 48,
244
+ 5,
245
+ 6,
246
+ 3,
247
+ 43,
248
+ 101,
249
+ 110,
250
+ 4,
251
+ 34,
252
+ 4,
253
+ 32
254
+ ]);
255
+ var infoEncoder = new TextEncoder();
256
+ function assertKeyMaterialLength(runKeyMaterial) {
257
+ if (runKeyMaterial.byteLength !== CONTENT_KEY_LENGTH) throw new WorkflowRuntimeError(`Run key material must be exactly ${CONTENT_KEY_LENGTH} bytes, got ${runKeyMaterial.byteLength}`);
258
+ }
259
+ function assertPublicKeyLength(publicKey, label) {
260
+ if (publicKey.byteLength !== X25519_KEY_LENGTH) throw new WorkflowRuntimeError(`${label} must be exactly ${X25519_KEY_LENGTH} bytes, got ${publicKey.byteLength}`);
261
+ }
262
+ /**
263
+ * Derive the per-run X25519 keypair from the run's 32-byte key material.
264
+ *
265
+ * Deterministic: the same key material always yields the same keypair, which
266
+ * is what lets the owning deployment re-derive its private scalar on demand
267
+ * (from `VERCEL_DEPLOYMENT_KEY`) instead of storing it anywhere.
268
+ *
269
+ * @param runKeyMaterial - The 32 bytes returned by `World.getEncryptionKeyForRun()`
270
+ * @returns The run's X25519 scalar and public key
271
+ */
272
+ async function deriveRunKeyPair(runKeyMaterial) {
273
+ assertKeyMaterialLength(runKeyMaterial);
274
+ const hkdfKey = await globalThis.crypto.subtle.importKey("raw", runKeyMaterial, "HKDF", false, ["deriveBits"]);
275
+ const scalarBits = await globalThis.crypto.subtle.deriveBits({
276
+ name: "HKDF",
277
+ hash: "SHA-256",
278
+ salt: /* @__PURE__ */ new Uint8Array(32),
279
+ info: infoEncoder.encode(SCALAR_INFO)
280
+ }, hkdfKey, 256);
281
+ const scalar = new Uint8Array(scalarBits);
282
+ return {
283
+ scalar,
284
+ publicKey: await derivePublicKeyFromScalar(scalar)
285
+ };
286
+ }
287
+ /**
288
+ * Recover the raw public key for a scalar.
289
+ *
290
+ * Web Crypto exposes no scalar-multiplication primitive, so the scalar is
291
+ * imported as a PKCS#8 private key and its public half read back out of the
292
+ * JWK export (`x`), which the Secure Curves spec defines as the base64url
293
+ * raw public key.
294
+ */
295
+ async function derivePublicKeyFromScalar(scalar) {
296
+ const privateKey = await importScalar(scalar, true);
297
+ const jwk = await globalThis.crypto.subtle.exportKey("jwk", privateKey);
298
+ if (!jwk.x) throw new WorkflowRuntimeError("X25519 JWK export did not include a public key component (\"x\")");
299
+ const publicKey = base64UrlToBytes(jwk.x);
300
+ if (publicKey.byteLength !== X25519_KEY_LENGTH) throw new WorkflowRuntimeError(`X25519 JWK export produced a ${publicKey.byteLength}-byte public key, expected ${X25519_KEY_LENGTH}`);
301
+ return publicKey;
302
+ }
303
+ async function importScalar(scalar, extractable) {
304
+ const pkcs8 = new Uint8Array(PKCS8_X25519_PREFIX.length + scalar.byteLength);
305
+ pkcs8.set(PKCS8_X25519_PREFIX, 0);
306
+ pkcs8.set(scalar, PKCS8_X25519_PREFIX.length);
307
+ return globalThis.crypto.subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, extractable, ["deriveBits"]);
308
+ }
309
+ function importPublicKey(publicKey) {
310
+ return globalThis.crypto.subtle.importKey("raw", publicKey, { name: "X25519" }, true, []);
311
+ }
312
+ var BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
313
+ var BASE64URL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
314
+ /**
315
+ * Encode bytes as standard (padded) base64.
316
+ *
317
+ * Hand-rolled for the same reason as {@link base64UrlToBytes}: this module
318
+ * runs in the browser (o11y decryption) and inside the workflow VM, so neither
319
+ * `Buffer` nor `btoa` can be assumed. Used for the wire encoding of run public
320
+ * keys, matching the base64 convention already used for `VERCEL_DEPLOYMENT_KEY`
321
+ * and the `run-key` API response.
322
+ */
323
+ function bytesToBase64(bytes) {
324
+ let out = "";
325
+ for (let i = 0; i < bytes.length; i += 3) {
326
+ const b0 = bytes[i];
327
+ const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
328
+ const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
329
+ out += BASE64_CHARS[b0 >> 2 & 63];
330
+ out += BASE64_CHARS[(b0 & 3) << 4 | b1 >> 4 & 15];
331
+ out += i + 1 < bytes.length ? BASE64_CHARS[(b1 & 15) << 2 | b2 >> 6 & 3] : "=";
332
+ out += i + 2 < bytes.length ? BASE64_CHARS[b2 & 63] : "=";
333
+ }
334
+ return out;
335
+ }
336
+ /**
337
+ * Decode standard base64 (padding optional) to bytes.
338
+ *
339
+ * Returns `undefined` for malformed input rather than throwing: callers decode
340
+ * public keys that arrive from storage or over the wire, where a corrupt value
341
+ * should degrade to "this run has no usable public key" (and fall back to the
342
+ * symmetric path) rather than crash a resumption.
343
+ *
344
+ * Validation is strict, because a lenient decoder is worse than a throwing one
345
+ * here: silently returning a short or truncated key makes a corrupt value look
346
+ * *present*, so the caller seals to garbage instead of taking the fallback.
347
+ * Rejected: characters outside the alphabet, a length that cannot describe a
348
+ * whole number of bytes (`length % 4 === 1`), padding anywhere but the end, and
349
+ * a final quantum whose unused low bits are not zero.
350
+ */
351
+ function base64ToBytes(value) {
352
+ let end = value.length;
353
+ while (end > 0 && value[end - 1] === "=") end--;
354
+ const body = value.slice(0, end);
355
+ if (body.includes("=")) return void 0;
356
+ if (body.length % 4 === 1) return void 0;
357
+ if (end !== value.length && value.length % 4 !== 0) return void 0;
358
+ let accumulator = 0;
359
+ let bitCount = 0;
360
+ const bytes = [];
361
+ for (let i = 0; i < body.length; i++) {
362
+ const index = BASE64_CHARS.indexOf(body[i]);
363
+ if (index === -1) return void 0;
364
+ accumulator = accumulator << 6 | index;
365
+ bitCount += 6;
366
+ if (bitCount >= 8) {
367
+ bitCount -= 8;
368
+ bytes.push(accumulator >> bitCount & 255);
369
+ }
370
+ }
371
+ if (bitCount > 0 && (accumulator & (1 << bitCount) - 1) !== 0) return;
372
+ return new Uint8Array(bytes);
373
+ }
374
+ /**
375
+ * Decode a base64url string (JWK encoding) to bytes.
376
+ *
377
+ * Hand-rolled rather than using `atob` or `Buffer`: this module also runs
378
+ * inside the workflow VM, whose global surface is deliberately minimal and
379
+ * does not include either. The inputs here are fixed-size JWK key components,
380
+ * so a compact decoder is sufficient: it accepts unpadded base64url only,
381
+ * which is what RFC 7515 §2 mandates for JWK members.
382
+ */
383
+ function base64UrlToBytes(value) {
384
+ let accumulator = 0;
385
+ let bitCount = 0;
386
+ const bytes = [];
387
+ for (let i = 0; i < value.length; i++) {
388
+ const char = value[i];
389
+ if (char === "=") break;
390
+ const index = BASE64URL_CHARS.indexOf(char);
391
+ if (index === -1) throw new WorkflowRuntimeError(`Invalid base64url character "${char}" in X25519 JWK key component`);
392
+ accumulator = accumulator << 6 | index;
393
+ bitCount += 6;
394
+ if (bitCount >= 8) {
395
+ bitCount -= 8;
396
+ bytes.push(accumulator >> bitCount & 255);
397
+ }
398
+ }
399
+ return new Uint8Array(bytes);
400
+ }
401
+ /**
402
+ * Derive the AES-256-GCM content key from an X25519 shared secret, binding
403
+ * it to both public keys (HPKE's `kem_context`).
404
+ */
405
+ async function deriveContentKey(sharedSecret, ephemeralPublicKey, recipientPublicKey, usages) {
406
+ const label = infoEncoder.encode(CONTENT_KEY_INFO);
407
+ const info = new Uint8Array(label.length + ephemeralPublicKey.length + recipientPublicKey.length);
408
+ info.set(label, 0);
409
+ info.set(ephemeralPublicKey, label.length);
410
+ info.set(recipientPublicKey, label.length + ephemeralPublicKey.length);
411
+ const hkdfKey = await globalThis.crypto.subtle.importKey("raw", sharedSecret, "HKDF", false, ["deriveBits"]);
412
+ const contentKeyBits = await globalThis.crypto.subtle.deriveBits({
413
+ name: "HKDF",
414
+ hash: "SHA-256",
415
+ salt: /* @__PURE__ */ new Uint8Array(32),
416
+ info
417
+ }, hkdfKey, 256);
418
+ return globalThis.crypto.subtle.importKey("raw", new Uint8Array(contentKeyBits), "AES-GCM", false, usages);
419
+ }
420
+ /**
421
+ * The writer half of the KEM: generate an ephemeral keypair and derive a
422
+ * content key for a recipient's public key.
423
+ *
424
+ * Use this when many payloads share one KEM operation, i.e. stream frames.
425
+ * The returned `contentKey` can only encrypt, so a stream writer provably
426
+ * cannot read the recipient run's data even by mistake.
427
+ *
428
+ * **Callers own nonce discipline.** Encrypt each frame with a fresh random
429
+ * nonce, and call this function again for every new connection attempt or
430
+ * replay so that a restarted writer never reuses a content key. For one-shot
431
+ * payloads prefer {@link seal}, which handles this automatically.
432
+ *
433
+ * @param recipientPublicKey - The recipient run's raw 32-byte X25519 public key
434
+ * @returns The ephemeral public key to publish alongside the ciphertext, and
435
+ * the encrypt-only content key
436
+ */
437
+ async function encapsulate(recipientPublicKey) {
438
+ assertPublicKeyLength(recipientPublicKey, "Recipient public key");
439
+ let recipientKey;
440
+ try {
441
+ recipientKey = await importPublicKey(recipientPublicKey);
442
+ } catch (cause) {
443
+ throw new WorkflowRuntimeError(`Invalid X25519 recipient public key: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
444
+ }
445
+ const ephemeral = await globalThis.crypto.subtle.generateKey({ name: "X25519" }, true, ["deriveBits"]);
446
+ const ephemeralPublicKey = new Uint8Array(await globalThis.crypto.subtle.exportKey("raw", ephemeral.publicKey));
447
+ let sharedSecretBits;
448
+ try {
449
+ sharedSecretBits = await globalThis.crypto.subtle.deriveBits({
450
+ name: "X25519",
451
+ public: recipientKey
452
+ }, ephemeral.privateKey, 256);
453
+ } catch (cause) {
454
+ throw new WorkflowRuntimeError("X25519 key agreement failed: the recipient public key is not a valid curve point (low-order point or corrupted key material)", { cause });
455
+ }
456
+ return {
457
+ ephemeralPublicKey,
458
+ contentKey: await deriveContentKey(new Uint8Array(sharedSecretBits), ephemeralPublicKey, recipientPublicKey, ["encrypt"])
459
+ };
460
+ }
461
+ /**
462
+ * The recipient half of the KEM: recover the content key for a sealed
463
+ * payload from the run's own keypair and the sender's ephemeral public key.
464
+ *
465
+ * @param keyPair - The recipient run's keypair, from {@link deriveRunKeyPair}
466
+ * @param ephemeralPublicKey - The sender's raw 32-byte X25519 public key,
467
+ * read from the head of the sealed envelope
468
+ * @returns A decrypt-only content key
469
+ */
470
+ async function decapsulate(keyPair, ephemeralPublicKey) {
471
+ if (ephemeralPublicKey.byteLength !== X25519_KEY_LENGTH) throw new RuntimeDecryptionError(`Sealed payload has a malformed ephemeral public key: expected ${X25519_KEY_LENGTH} bytes, got ${ephemeralPublicKey.byteLength}`, { context: {
472
+ operation: "decrypt",
473
+ byteLength: ephemeralPublicKey.byteLength
474
+ } });
475
+ let sharedSecretBits;
476
+ try {
477
+ const [privateKey, senderKey] = await Promise.all([importScalar(keyPair.scalar, false), importPublicKey(ephemeralPublicKey)]);
478
+ sharedSecretBits = await globalThis.crypto.subtle.deriveBits({
479
+ name: "X25519",
480
+ public: senderKey
481
+ }, privateKey, 256);
482
+ } catch (cause) {
483
+ throw new RuntimeDecryptionError(`X25519 key agreement failed while opening a sealed payload: ${cause instanceof Error ? cause.message : String(cause)}`, {
484
+ cause,
485
+ context: {
486
+ operation: "decrypt",
487
+ byteLength: ephemeralPublicKey.byteLength
488
+ }
489
+ });
490
+ }
491
+ return deriveContentKey(new Uint8Array(sharedSecretBits), ephemeralPublicKey, keyPair.publicKey, ["decrypt"]);
492
+ }
493
+ /**
494
+ * Seal a payload to a run's public key.
495
+ *
496
+ * Each call performs its own KEM operation, so every sealed payload gets an
497
+ * independent content key: nonce reuse across calls is impossible by
498
+ * construction.
499
+ *
500
+ * @param recipientPublicKey - The recipient run's raw 32-byte X25519 public key
501
+ * @param data - Plaintext to seal
502
+ * @param aad - Optional additional authenticated data, covered by the GCM tag
503
+ * but not encrypted. Callers pass the recipient's `projectId|runId` so a
504
+ * sealed payload cannot be replayed against a different run.
505
+ * @returns `[ephemeral public key (32)][nonce (12)][ciphertext + tag]`
506
+ */
507
+ async function seal(recipientPublicKey, data, aad) {
508
+ const { ephemeralPublicKey, contentKey } = await encapsulate(recipientPublicKey);
509
+ const encrypted = await encrypt$1(contentKey, data, aad);
510
+ const result = new Uint8Array(ephemeralPublicKey.byteLength + encrypted.byteLength);
511
+ result.set(ephemeralPublicKey, 0);
512
+ result.set(encrypted, ephemeralPublicKey.byteLength);
513
+ return result;
514
+ }
515
+ /**
516
+ * Open a payload sealed to this run's public key.
517
+ *
518
+ * @param keyPair - The recipient run's keypair, from {@link deriveRunKeyPair}
519
+ * @param sealed - `[ephemeral public key (32)][nonce (12)][ciphertext + tag]`
520
+ * @param aad - The exact additional authenticated data passed to {@link seal}
521
+ * @returns The decrypted plaintext
522
+ */
523
+ async function open(keyPair, sealed, aad) {
524
+ const minLength = X25519_KEY_LENGTH + 12 + 16;
525
+ if (sealed.byteLength < minLength) throw new RuntimeDecryptionError(`Sealed payload too short: expected at least ${minLength} bytes, got ${sealed.byteLength}`, { context: {
526
+ operation: "decrypt",
527
+ byteLength: sealed.byteLength
528
+ } });
529
+ const ephemeralPublicKey = sealed.subarray(0, X25519_KEY_LENGTH);
530
+ const encrypted = sealed.subarray(X25519_KEY_LENGTH);
531
+ return decrypt$1(await decapsulate(keyPair, ephemeralPublicKey), encrypted, aad);
532
+ }
533
+ /**
534
+ * A writer-side session that amortizes one KEM operation across many sealed
535
+ * payloads. Use it for streams, where one-shot {@link seal} would perform a
536
+ * fresh keygen + ECDH + HKDF for every frame.
537
+ *
538
+ * Safety rests on two properties:
539
+ *
540
+ * - Every payload still gets a **fresh random nonce** from `aesGcmEncrypt`, so
541
+ * sharing the content key does not risk `(key, nonce)` reuse. (A counter
542
+ * would: it restarts at zero whenever a writer restarts.)
543
+ * - The session is bound to one writer instance. A reconnect or a durable
544
+ * replay constructs a new session, so a restarted writer never inherits a
545
+ * previous incarnation's content key.
546
+ *
547
+ * The envelope layout is byte-identical to {@link seal}, so a reader cannot
548
+ * tell which was used and needs no matching session.
549
+ */
550
+ function createSealSession(recipientPublicKey, aad) {
551
+ let encapsulation;
552
+ return { async seal(data) {
553
+ encapsulation ??= encapsulate(recipientPublicKey);
554
+ const { ephemeralPublicKey, contentKey } = await encapsulation;
555
+ const encrypted = await encrypt$1(contentKey, data, aad);
556
+ const result = new Uint8Array(ephemeralPublicKey.byteLength + encrypted.byteLength);
557
+ result.set(ephemeralPublicKey, 0);
558
+ result.set(encrypted, ephemeralPublicKey.byteLength);
559
+ return result;
560
+ } };
561
+ }
562
+ /**
563
+ * A reader-side session that caches decapsulation per sender.
564
+ *
565
+ * The mirror of {@link createSealSession}: because every frame from one writer
566
+ * carries the same ephemeral public key, this turns an ECDH per frame into an
567
+ * ECDH per writer. Correctness does not depend on the writer having used a
568
+ * session: a stream of independently sealed payloads misses the cache
569
+ * on each new ephemeral key.
570
+ *
571
+ * The cache is keyed by the ephemeral public key and holds one entry, which is
572
+ * the common case (one writer per stream). A second writer evicts the first
573
+ * rather than growing without bound.
574
+ */
575
+ function createOpenSession(keyPair, aad) {
576
+ let cachedSender;
577
+ let cachedKey;
578
+ return { async open(sealed) {
579
+ const minLength = X25519_KEY_LENGTH + 12 + 16;
580
+ if (sealed.byteLength < minLength) throw new RuntimeDecryptionError(`Sealed payload too short: expected at least ${minLength} bytes, got ${sealed.byteLength}`, { context: {
581
+ operation: "decrypt",
582
+ byteLength: sealed.byteLength
583
+ } });
584
+ const ephemeralPublicKey = sealed.subarray(0, X25519_KEY_LENGTH);
585
+ const encrypted = sealed.subarray(X25519_KEY_LENGTH);
586
+ const sender = keyCacheId(ephemeralPublicKey);
587
+ if (sender !== cachedSender || !cachedKey) {
588
+ cachedSender = sender;
589
+ cachedKey = decapsulate(keyPair, ephemeralPublicKey);
590
+ }
591
+ let contentKey;
592
+ try {
593
+ contentKey = await cachedKey;
594
+ } catch (error) {
595
+ cachedSender = void 0;
596
+ cachedKey = void 0;
597
+ throw error;
598
+ }
599
+ return decrypt$1(contentKey, encrypted, aad);
600
+ } };
601
+ }
602
+ /** Stable cache key for a 32-byte public key. */
603
+ function keyCacheId(publicKey) {
604
+ let id = "";
605
+ for (let i = 0; i < publicKey.length; i++) id += publicKey[i].toString(16).padStart(2, "0");
606
+ return id;
607
+ }
608
+ /**
609
+ * Decode a run's published public key, validating both encoding and length.
610
+ *
611
+ * Returns `undefined` when the value is absent, not valid base64, or not
612
+ * exactly 32 bytes. Callers treat that as "this run has no usable public key"
613
+ * and fall back to the symmetric path, so a corrupt or truncated stored value
614
+ * degrades to the pre-existing behavior instead of failing a resumption.
615
+ */
616
+ function decodeRunPublicKey(value) {
617
+ if (!value) return void 0;
618
+ const bytes = base64ToBytes(value);
619
+ if (!bytes || bytes.byteLength !== X25519_KEY_LENGTH) return void 0;
620
+ return bytes;
621
+ }
622
+ // ../../node_modules/.bun/@workflow+core@5.3.0+eefe5d4a997ff1ee/node_modules/@workflow/core/dist/serialization/types.js
623
+ /**
624
+ * Shared types for the serialization system.
625
+ */
626
+ /**
627
+ * Runtime type guard for format prefix strings.
628
+ *
629
+ * Validates that a string is exactly 4 characters of [a-z0-9].
630
+ */
631
+ function isFormatPrefix(value) {
632
+ return value.length === 4 && /^[a-z0-9]{4}$/.test(value);
633
+ }
634
+ /**
635
+ * Well-known format prefix constants. Codecs may define additional ones.
636
+ */
637
+ var SerializationFormat = {
638
+ /** devalue stringify/parse with TextEncoder/TextDecoder */
639
+ DEVALUE_V1: "devl",
640
+ /** Encrypted payload (inner payload has its own format prefix) */
641
+ ENCRYPTED: "encr",
642
+ /**
643
+ * Sealed payload: asymmetrically encrypted to a run's X25519 public key
644
+ * (inner payload has its own format prefix).
645
+ *
646
+ * Used for *cross-run* writes (hook payloads, forwarded stream frames),
647
+ * where the writer holds only the recipient run's public key and therefore
648
+ * cannot decrypt. A run's own payloads continue to use {@link ENCRYPTED}.
649
+ * See `sealed-box.ts` for the construction.
650
+ */
651
+ SEALED: "encp",
652
+ /** Gzip-compressed payload (inner payload has its own format prefix) */
653
+ GZIP: "gzip",
654
+ /** Zstandard-compressed payload (inner payload has its own format prefix) */
655
+ ZSTD: "zstd"
656
+ };
657
+ // ../../node_modules/.bun/@workflow+core@5.3.0+eefe5d4a997ff1ee/node_modules/@workflow/core/dist/serialization/format.js
658
+ /**
659
+ * Format prefix system for serialized payloads.
660
+ *
661
+ * All serialized payloads are prefixed with a 4-byte format identifier that
662
+ * allows the deserializer to determine how to decode the payload. This enables:
663
+ *
664
+ * 1. Self-describing payloads: the World layer is agnostic to serialization format
665
+ * 2. Gradual migration: old runs keep working, new runs can use new formats
666
+ * 3. Composability: encryption can wrap any format ("encr" wrapping "devl")
667
+ * 4. Debugging: raw data inspection immediately reveals the format
668
+ *
669
+ * Format: [4 bytes: format identifier][payload]
670
+ *
671
+ * The format prefix is open-ended: any 4-character [a-z0-9] string is valid.
672
+ * This allows new codecs to be added without modifying this module.
673
+ */
674
+ /** Length of the format prefix in bytes */
675
+ var FORMAT_PREFIX_LENGTH = 4;
676
+ var formatEncoder = new TextEncoder();
677
+ var formatDecoder = new TextDecoder();
678
+ /**
679
+ * Encode a payload with a format prefix.
680
+ *
681
+ * @param format - The format identifier (4 chars, [a-z0-9])
682
+ * @param payload - The serialized payload bytes
683
+ * @returns A new Uint8Array with format prefix prepended
684
+ */
685
+ function encodeWithFormatPrefix(format, payload) {
686
+ if (!(payload instanceof Uint8Array)) return payload;
687
+ const prefixBytes = formatEncoder.encode(format);
688
+ const result = new Uint8Array(FORMAT_PREFIX_LENGTH + payload.length);
689
+ result.set(prefixBytes, 0);
690
+ result.set(payload, FORMAT_PREFIX_LENGTH);
691
+ return result;
692
+ }
693
+ /**
694
+ * Peek at the format prefix without consuming it.
695
+ *
696
+ * Returns the prefix if it's a valid format prefix ([a-z0-9]{4}),
697
+ * or null if the data is legacy/non-binary or doesn't start with a
698
+ * valid prefix.
699
+ *
700
+ * @param data - The format-prefixed data
701
+ * @returns The format prefix, or null
702
+ */
703
+ function peekFormatPrefix(data) {
704
+ if (!(data instanceof Uint8Array) || data.length < FORMAT_PREFIX_LENGTH) return null;
705
+ const prefixBytes = data.subarray(0, FORMAT_PREFIX_LENGTH);
706
+ const str = formatDecoder.decode(prefixBytes);
707
+ return isFormatPrefix(str) ? str : null;
708
+ }
709
+ /**
710
+ * Decode a format-prefixed payload.
711
+ *
712
+ * Unlike the legacy implementation which only accepted known formats
713
+ * (`devl`, `encr`), this function accepts any valid format prefix
714
+ * (`[a-z0-9]{4}`). This is intentional for forward compatibility, so
715
+ * new codecs (e.g. `cbor`) can be added without modifying this module.
716
+ * Callers are responsible for checking whether they support the returned
717
+ * format and throwing an appropriate error if not (e.g. "Unsupported
718
+ * serialization format").
719
+ *
720
+ * @param data - The format-prefixed data
721
+ * @returns An object with the format prefix and payload
722
+ * @throws Error if the data is too short or has an invalid prefix
723
+ */
724
+ function decodeFormatPrefix(data) {
725
+ if (!(data instanceof Uint8Array)) return {
726
+ format: SerializationFormat.DEVALUE_V1,
727
+ payload: new TextEncoder().encode(JSON.stringify(data))
728
+ };
729
+ if (data.length < FORMAT_PREFIX_LENGTH) throw new Error(`Data too short to contain format prefix: expected at least ${FORMAT_PREFIX_LENGTH} bytes, got ${data.length}`);
730
+ const prefixBytes = data.subarray(0, FORMAT_PREFIX_LENGTH);
731
+ const str = formatDecoder.decode(prefixBytes);
732
+ if (!isFormatPrefix(str)) throw new Error(`Invalid format prefix: "${str}". Must be 4 characters of [a-z0-9].`);
733
+ return {
734
+ format: str,
735
+ payload: data.subarray(FORMAT_PREFIX_LENGTH)
736
+ };
737
+ }
738
+ // ../../node_modules/.bun/@workflow+core@5.3.0+eefe5d4a997ff1ee/node_modules/@workflow/core/dist/serialization/encryption.js
739
+ /**
740
+ * Composable encryption layer for serialized data.
741
+ *
742
+ * Wraps/unwraps serialized payloads with either symmetric AES-256-GCM
743
+ * encryption (`encr`) or an asymmetric sealed box (`encp`), using the format
744
+ * prefix system to mark which. See {@link PayloadKey} for how a caller
745
+ * declares which capabilities it holds.
746
+ */
747
+ var encryption_exports = /* @__PURE__ */ __exportAll({
748
+ decrypt: () => decrypt,
749
+ isRunPayloadKeys: () => isRunPayloadKeys
750
+ });
751
+ /**
752
+ * Brands distinguishing the structured key variants from a bare `CryptoKey`.
753
+ *
754
+ * `Symbol.for` rather than `Symbol()` because these values cross realm
755
+ * boundaries (host ↔ workflow VM), and the global symbol registry is shared
756
+ * across realms while unique symbols are not.
757
+ */
758
+ var SEAL_TARGET_BRAND = Symbol.for("workflow.serialization.sealTarget");
759
+ var RUN_KEYS_BRAND = Symbol.for("workflow.serialization.runKeys");
760
+ /**
761
+ * Build a write-only seal capability for a recipient run's public key.
762
+ *
763
+ * @param recipientPublicKey - The recipient run's raw 32-byte X25519 public key
764
+ * @param aad - Additional authenticated data, conventionally `runAad(projectId, runId)`
765
+ */
766
+ function sealTo(recipientPublicKey, aad) {
767
+ return {
768
+ [SEAL_TARGET_BRAND]: true,
769
+ recipientPublicKey,
770
+ aad
771
+ };
772
+ }
773
+ /**
774
+ * Bundle a run's symmetric key with the keypair that opens payloads sealed
775
+ * to it.
776
+ */
777
+ function runPayloadKeys(aes, keyPair, aad) {
778
+ return {
779
+ [RUN_KEYS_BRAND]: true,
780
+ aes,
781
+ keyPair,
782
+ aad
783
+ };
784
+ }
785
+ /**
786
+ * Build the full key capability for a run from its raw 32-byte key material,
787
+ * the value `World.getEncryptionKeyForRun()` returns.
788
+ *
789
+ * Use this anywhere a run reads its own event log: it yields a key that opens
790
+ * both its own symmetric (`encr`) payloads and sealed (`encp`) payloads other
791
+ * runs wrote to it. Resolving only `importKey(material)` would leave the
792
+ * reader unable to open sealed writes.
793
+ */
794
+ async function deriveRunPayloadKeys(runKeyMaterial) {
795
+ const [aes, keyPair] = await Promise.all([importKey(runKeyMaterial), deriveRunKeyPair(runKeyMaterial)]);
796
+ return runPayloadKeys(aes, keyPair);
797
+ }
798
+ function isSealTarget(value) {
799
+ return typeof value === "object" && value !== null && value[SEAL_TARGET_BRAND] === true;
800
+ }
801
+ function isRunPayloadKeys(value) {
802
+ return typeof value === "object" && value !== null && value[RUN_KEYS_BRAND] === true;
803
+ }
804
+ /**
805
+ * The symmetric key to use for `encr` operations, or undefined when this key
806
+ * has no symmetric capability (i.e. it is a seal-only target).
807
+ */
808
+ function aesKeyOf(key) {
809
+ if (!key) return void 0;
810
+ if (isRunPayloadKeys(key)) return key.aes;
811
+ if (isSealTarget(key)) return void 0;
812
+ return key;
813
+ }
814
+ async function resolveEncryptionKey(key) {
815
+ return typeof key === "function" ? key() : key;
816
+ }
817
+ /**
818
+ * Encrypt a format-prefixed payload if a key is provided.
819
+ *
820
+ * Wraps the data with the `encr` prefix for symmetric keys, or the `encp`
821
+ * prefix when handed a {@link SealTarget}, a cross-run writer that holds
822
+ * only the recipient's public key.
823
+ *
824
+ * @param data - The format-prefixed serialized data
825
+ * @param key - Encryption key (undefined to skip encryption)
826
+ * @returns The encrypted data with its format prefix, or the original data if no key
827
+ */
828
+ async function encrypt(data, key) {
829
+ if (!key || !(data instanceof Uint8Array)) return data;
830
+ if (isSealTarget(key)) {
831
+ const sealed = await seal(key.recipientPublicKey, data, key.aad);
832
+ return encodeWithFormatPrefix(SerializationFormat.SEALED, sealed);
833
+ }
834
+ const encrypted = await encrypt$1(isRunPayloadKeys(key) ? key.aes : key, data);
835
+ return encodeWithFormatPrefix(SerializationFormat.ENCRYPTED, encrypted);
836
+ }
837
+ /**
838
+ * Decrypt a format-prefixed payload if it's encrypted or sealed.
839
+ *
840
+ * Strips the `encr`/`encp` format prefix and recovers the inner payload.
841
+ * Opening a sealed (`encp`) payload requires the run's X25519 keypair, so the
842
+ * caller must supply {@link RunPayloadKeys}; a bare symmetric key cannot do
843
+ * it, and neither can a {@link SealTarget} (which is write-only by design).
844
+ *
845
+ * @param data - The potentially encrypted data
846
+ * @param key - Encryption key (undefined to skip decryption)
847
+ * @returns The decrypted inner payload, or the original data if not encrypted
848
+ */
849
+ /**
850
+ * Open a sealed (`encp`) envelope. Split out from {@link decrypt} to keep
851
+ * each scheme's error handling readable on its own.
852
+ */
853
+ async function openSealedEnvelope(data, key) {
854
+ if (!isRunPayloadKeys(key)) throw new RuntimeDecryptionError("Sealed data encountered but no run keypair is available. Opening a sealed payload requires the run's own encryption key material; a symmetric key or a seal-only target cannot decrypt it.", { context: {
855
+ operation: "decrypt",
856
+ byteLength: data.byteLength,
857
+ formatPrefix: "encp"
858
+ } });
859
+ const { payload } = decodeFormatPrefix(data);
860
+ try {
861
+ return await open(key.keyPair, payload, key.aad);
862
+ } catch (error) {
863
+ if (RuntimeDecryptionError.is(error) && error.context) error.context.formatPrefix = SerializationFormat.SEALED;
864
+ throw error;
865
+ }
866
+ }
867
+ async function decrypt(data, key) {
868
+ if (!(data instanceof Uint8Array)) return data;
869
+ const format = peekFormatPrefix(data);
870
+ if (format === SerializationFormat.SEALED) return openSealedEnvelope(data, key);
871
+ if (format !== SerializationFormat.ENCRYPTED) return data;
872
+ const aesKey = aesKeyOf(key);
873
+ if (!aesKey) throw new RuntimeDecryptionError("Encrypted data encountered but no encryption key is available. Encryption is not configured or no key was provided for this run.", { context: {
874
+ operation: "decrypt",
875
+ byteLength: data.byteLength,
876
+ formatPrefix: "encr"
877
+ } });
878
+ const { payload } = decodeFormatPrefix(data);
879
+ try {
880
+ return await decrypt$1(aesKey, payload);
881
+ } catch (error) {
882
+ if (RuntimeDecryptionError.is(error) && error.context) error.context.formatPrefix = format;
883
+ throw error;
884
+ }
885
+ }
886
+ export { decodeRunPublicKey as _, encryption_exports as a, resolveEncryptionKey as c, encodeWithFormatPrefix as d, peekFormatPrefix as f, createSealSession as g, createOpenSession as h, encrypt as i, sealTo as l, bytesToBase64 as m, decrypt as n, isRunPayloadKeys as o, SerializationFormat as p, deriveRunPayloadKeys as r, isSealTarget as s, aesKeyOf as t, decodeFormatPrefix as u, deriveRunKeyPair as v, importKey as y };