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