@stigmer/temporal-codecs 0.1.0-dev.20261017020314.g644422724c27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +194 -0
  2. package/README.md +48 -0
  3. package/claimcheck/compressor.d.ts +12 -0
  4. package/claimcheck/compressor.d.ts.map +1 -0
  5. package/claimcheck/compressor.js +17 -0
  6. package/claimcheck/compressor.js.map +1 -0
  7. package/claimcheck/config.d.ts +17 -0
  8. package/claimcheck/config.d.ts.map +1 -0
  9. package/claimcheck/config.js +19 -0
  10. package/claimcheck/config.js.map +1 -0
  11. package/claimcheck/payload-codec.d.ts +29 -0
  12. package/claimcheck/payload-codec.d.ts.map +1 -0
  13. package/claimcheck/payload-codec.js +110 -0
  14. package/claimcheck/payload-codec.js.map +1 -0
  15. package/claimcheck/storage.d.ts +20 -0
  16. package/claimcheck/storage.d.ts.map +1 -0
  17. package/claimcheck/storage.js +2 -0
  18. package/claimcheck/storage.js.map +1 -0
  19. package/connection/config.d.ts +100 -0
  20. package/connection/config.d.ts.map +1 -0
  21. package/connection/config.js +171 -0
  22. package/connection/config.js.map +1 -0
  23. package/encryption/config.d.ts +100 -0
  24. package/encryption/config.d.ts.map +1 -0
  25. package/encryption/config.js +119 -0
  26. package/encryption/config.js.map +1 -0
  27. package/encryption/payload-codec.d.ts +60 -0
  28. package/encryption/payload-codec.d.ts.map +1 -0
  29. package/encryption/payload-codec.js +163 -0
  30. package/encryption/payload-codec.js.map +1 -0
  31. package/index.d.ts +32 -0
  32. package/index.d.ts.map +1 -0
  33. package/index.js +28 -0
  34. package/index.js.map +1 -0
  35. package/package.json +42 -0
  36. package/src/claimcheck/compressor.ts +19 -0
  37. package/src/claimcheck/config.ts +30 -0
  38. package/src/claimcheck/payload-codec.ts +144 -0
  39. package/src/claimcheck/storage.ts +19 -0
  40. package/src/connection/config.ts +217 -0
  41. package/src/encryption/config.ts +204 -0
  42. package/src/encryption/payload-codec.ts +186 -0
  43. package/src/index.ts +49 -0
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Payload-encryption configuration (stigmer#398).
3
+ *
4
+ * Two key sources, strict precedence:
5
+ *
6
+ * 1. Environment (STIGMER_PAYLOAD_ENCRYPTION_KEY(_ID)) — the operator's
7
+ * explicit choice: self-hosted deployments sharing one key with their
8
+ * server, and cloud sandboxes injected with the platform key. When the
9
+ * env key is set, bootstrap-delivered material is ignored entirely.
10
+ * 2. Bootstrap-delivered — server-managed per-identity keys handed to
11
+ * desktop-class runners by getRunnerBootstrapConfig. Held in memory
12
+ * only; persistence lives server-side, which is what makes Temporal
13
+ * replay work across runner restarts (every boot re-fetches the SAME
14
+ * key).
15
+ *
16
+ * Encryption is enabled iff a key is present from either source — the same
17
+ * enabled-iff-configured pattern as the claim-check codec. A malformed key
18
+ * fails the boot rather than silently running plaintext: an operator who set
19
+ * the key (or a server that minted one) intended history to be encrypted.
20
+ *
21
+ * Key rotation: payloads carry the id of the key that encrypted them.
22
+ * During a rotation window the previous key stays readable via the
23
+ * secondary pair while new payloads are written under the primary key.
24
+ * Workers capture keys at construction, so a rotated bootstrap key lands
25
+ * on the next runner boot — there is no live re-key.
26
+ *
27
+ * Moved from backend/services/runner/src/encryption/config.ts when the
28
+ * codecs became @stigmer/temporal-codecs (one home for the cross-language
29
+ * envelope contract; the TS server is the second consumer). Key VALUES are
30
+ * read through an injected {@link SecretReader} because secret custody is
31
+ * consumer policy, not codec policy: the runner routes reads through its
32
+ * boot-capture credential store (stigmer#508 — secrets must not live in
33
+ * process.env where agent shells could read them), while other consumers
34
+ * read their own stores. No process.env default is provided for the
35
+ * VALUES: a forgotten injection must fail to compile, not silently bypass
36
+ * a consumer's secret custody.
37
+ */
38
+
39
+ export interface EncryptionKey {
40
+ readonly keyId: string;
41
+ /** 32-byte AES-256 key. */
42
+ readonly key: Buffer;
43
+ }
44
+
45
+ /**
46
+ * Resolves decrypt-key material for a key id absent from the static
47
+ * config (a hosting server may decode desktop-runner histories written
48
+ * under server-managed per-identity `rpk_` keys, whose material lives in
49
+ * a database, not the environment).
50
+ * Returns undefined when the id is unknown — the codec then fails closed
51
+ * with its pinned unknown-key-id error. Implementations own their lookup
52
+ * and unsealing; the codec caches every RESOLVED key for the process
53
+ * lifetime (key material per id is immutable — rotation mints a new id),
54
+ * and never caches misses (the key may be minted moments later).
55
+ */
56
+ export type PayloadKeyResolver = (keyId: string) => Promise<Buffer | undefined>;
57
+
58
+ export interface PayloadEncryptionConfig {
59
+ /** Key used to encrypt outgoing payloads (and decrypt its own). */
60
+ readonly primary: EncryptionKey;
61
+ /** Decrypt-only key accepted during rotation windows. */
62
+ readonly secondary?: EncryptionKey;
63
+ /**
64
+ * Decrypt-only fallback consulted when a payload names a key id the
65
+ * static pair does not cover ({@link PayloadKeyResolver}). Encode never
66
+ * consults it — outgoing payloads are always written under `primary`.
67
+ */
68
+ readonly resolveKey?: PayloadKeyResolver;
69
+ }
70
+
71
+ /**
72
+ * Reads one secret VALUE by its env-var name. Consumers inject their own
73
+ * custody policy (see the module doc); the *_KEY_ID companions are
74
+ * rotation bookkeeping, not secrets, and stay plain `process.env` reads.
75
+ */
76
+ export type SecretReader = (name: string) => string | undefined;
77
+
78
+ /**
79
+ * Server-managed key material delivered by the runner's
80
+ * getRunnerBootstrapConfig. Structurally mirrors
81
+ * {@link BootstrapPayloadEncryptionKeys} in the runner's stigmer-client.ts
82
+ * — declared here so the library stays free of client imports.
83
+ */
84
+ export interface BootstrapKeyMaterial {
85
+ readonly key: string;
86
+ readonly keyId?: string;
87
+ readonly secondaryKey?: string;
88
+ readonly secondaryKeyId?: string;
89
+ }
90
+
91
+ const KEY_ENV = "STIGMER_PAYLOAD_ENCRYPTION_KEY";
92
+ const KEY_ID_ENV = "STIGMER_PAYLOAD_ENCRYPTION_KEY_ID";
93
+ const SECONDARY_KEY_ENV = "STIGMER_PAYLOAD_ENCRYPTION_SECONDARY_KEY";
94
+ const SECONDARY_KEY_ID_ENV = "STIGMER_PAYLOAD_ENCRYPTION_SECONDARY_KEY_ID";
95
+
96
+ const AES_256_KEY_BYTES = 32;
97
+
98
+ /**
99
+ * Returns the encryption config, or undefined when encryption is not
100
+ * configured (the codec is then simply not installed).
101
+ *
102
+ * Source precedence: the env key wins outright; bootstrap-delivered
103
+ * material applies only when no env key is set (see the module doc).
104
+ *
105
+ * @throws when a key is present but malformed, or a key id is missing —
106
+ * key misconfiguration must stop the boot, not degrade to plaintext.
107
+ * This applies equally to bootstrap material: a server that hands out
108
+ * a bad key or omits its id has broken the protocol contract, and
109
+ * running plaintext against a server that manages keys would silently
110
+ * defeat the feature.
111
+ */
112
+ export function loadPayloadEncryptionConfig(
113
+ readSecret: SecretReader,
114
+ bootstrap?: BootstrapKeyMaterial,
115
+ ): PayloadEncryptionConfig | undefined {
116
+ const rawKey = readSecret(KEY_ENV);
117
+ if (rawKey) {
118
+ const primary: EncryptionKey = {
119
+ keyId: requireKeyId(KEY_ID_ENV),
120
+ key: parseKey(rawKey, KEY_ENV),
121
+ };
122
+
123
+ const rawSecondary = readSecret(SECONDARY_KEY_ENV);
124
+ const secondary: EncryptionKey | undefined = rawSecondary
125
+ ? {
126
+ keyId: requireKeyId(SECONDARY_KEY_ID_ENV),
127
+ key: parseKey(rawSecondary, SECONDARY_KEY_ENV),
128
+ }
129
+ : undefined;
130
+
131
+ return { primary, secondary };
132
+ }
133
+
134
+ if (bootstrap?.key) {
135
+ const primary: EncryptionKey = {
136
+ keyId: requireBootstrapKeyId(
137
+ bootstrap.keyId,
138
+ "payload_encryption_key_id",
139
+ ),
140
+ key: parseKey(bootstrap.key, "bootstrap payload_encryption_key"),
141
+ };
142
+
143
+ const secondary: EncryptionKey | undefined = bootstrap.secondaryKey
144
+ ? {
145
+ keyId: requireBootstrapKeyId(
146
+ bootstrap.secondaryKeyId,
147
+ "payload_encryption_secondary_key_id",
148
+ ),
149
+ key: parseKey(
150
+ bootstrap.secondaryKey,
151
+ "bootstrap payload_encryption_secondary_key",
152
+ ),
153
+ }
154
+ : undefined;
155
+
156
+ return { primary, secondary };
157
+ }
158
+
159
+ return undefined;
160
+ }
161
+
162
+ function requireKeyId(envName: string): string {
163
+ const keyId = process.env[envName];
164
+ // An explicit id is required (no default): during rotation two keys
165
+ // coexist, and payloads must name which one encrypted them.
166
+ if (!keyId) {
167
+ throw new Error(
168
+ `Payload encryption misconfigured: ${envName} is required when the ` +
169
+ `corresponding key is set`,
170
+ );
171
+ }
172
+ return keyId;
173
+ }
174
+
175
+ function requireBootstrapKeyId(
176
+ keyId: string | undefined,
177
+ fieldName: string,
178
+ ): string {
179
+ if (!keyId) {
180
+ throw new Error(
181
+ `Runner bootstrap returned a payload encryption key without its ${fieldName} — ` +
182
+ `refusing to encrypt under an unidentified key (server contract violation)`,
183
+ );
184
+ }
185
+ return keyId;
186
+ }
187
+
188
+ function parseKey(rawBase64: string, envName: string): Buffer {
189
+ let key: Buffer;
190
+ try {
191
+ key = Buffer.from(rawBase64, "base64");
192
+ } catch {
193
+ throw new Error(
194
+ `Payload encryption misconfigured: ${envName} is not valid base64`,
195
+ );
196
+ }
197
+ if (key.length !== AES_256_KEY_BYTES) {
198
+ throw new Error(
199
+ `Payload encryption misconfigured: ${envName} must decode to ` +
200
+ `${AES_256_KEY_BYTES} bytes (AES-256), got ${key.length}`,
201
+ );
202
+ }
203
+ return key;
204
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Temporal PayloadCodec that encrypts payloads at rest in workflow
3
+ * history.
4
+ *
5
+ * Why: Temporal history is durable, and an agent run puts customer data
6
+ * there at every crossing — the run credential on each runner activity's
7
+ * input, and each activity result carrying the run's status (its errors,
8
+ * its pending approvals, what the run said and did). A run's vault values
9
+ * never ride history (the runner fetches them when the work starts), but
10
+ * the rest is still a customer's. Encrypting at the payload codec layer
11
+ * covers every crossing with one mechanism instead of chasing each one.
12
+ *
13
+ * Envelope (cross-SDK contract — the Java decode-only codec in
14
+ * stigmer-cloud's temporal-starter must match it byte-for-byte, pinned
15
+ * by the conformance fixture in __tests__/fixtures/):
16
+ *
17
+ * metadata: encoding = "binary/encrypted"
18
+ * encryption-key-id = <key id that encrypted this payload>
19
+ * data: iv (12 bytes) ‖ AES-256-GCM(ciphertext ‖ tag (16 bytes))
20
+ *
21
+ * The plaintext is the serialized ORIGINAL Payload proto (metadata AND
22
+ * data), so decode restores the payload exactly — including its
23
+ * original encoding — with no side channel.
24
+ *
25
+ * Decode passes through payloads it did not encode. This is what keeps
26
+ * plaintext signals from the Java/Go orchestrators and pre-rollout
27
+ * in-flight histories working with zero migration. Everything else
28
+ * fails closed: unknown key id, missing key id, and ciphertext tampering
29
+ * all throw rather than surfacing bogus payloads.
30
+ *
31
+ * Key ids outside the static primary/secondary pair may be resolved
32
+ * through the config's optional resolveKey seam (a hosting server may
33
+ * decode desktop-runner histories under database-resident `rpk_` keys).
34
+ * Resolution is decode-only, resolved keys are cached for the process
35
+ * lifetime (an id's material is immutable — rotation mints a new id),
36
+ * misses are never cached, and an unresolvable id keeps the pinned
37
+ * fail-closed throw.
38
+ *
39
+ * Moved from backend/services/runner/src/encryption/payload-codec.ts when
40
+ * the codecs became @stigmer/temporal-codecs (one home for the
41
+ * cross-language envelope contract; the TS server is the second consumer).
42
+ */
43
+
44
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
45
+ import type { Payload, PayloadCodec } from "@temporalio/common";
46
+ // Default-import + destructure, NOT `import { temporal } from …`:
47
+ // @temporalio/proto is CommonJS and its `temporal` export defeats Node's
48
+ // cjs-module-lexer named-export detection, so the named form loads under
49
+ // tsx/vitest (their interop is looser) but crashes plain `node dist/main.js`
50
+ // at startup with "Named export 'temporal' not found" (stigmer/stigmer#399
51
+ // boot regression). Pinned by scripts/verify-dist-boot.mjs in CI.
52
+ import proto from "@temporalio/proto";
53
+ import type { EncryptionKey, PayloadEncryptionConfig } from "./config.js";
54
+
55
+ const { temporal } = proto;
56
+
57
+ const ENCODING_METADATA_KEY = "encoding";
58
+ const ENCRYPTED_ENCODING_VALUE = "binary/encrypted";
59
+ const KEY_ID_METADATA_KEY = "encryption-key-id";
60
+
61
+ /** AES-GCM parameters shared with the Java implementation. */
62
+ const IV_BYTES = 12;
63
+ const AUTH_TAG_BYTES = 16;
64
+
65
+ export class EncryptionPayloadCodec implements PayloadCodec {
66
+ private readonly decryptKeysById: Map<string, Buffer>;
67
+
68
+ constructor(private readonly config: PayloadEncryptionConfig) {
69
+ this.decryptKeysById = new Map([
70
+ [config.primary.keyId, config.primary.key],
71
+ ]);
72
+ if (config.secondary) {
73
+ this.decryptKeysById.set(config.secondary.keyId, config.secondary.key);
74
+ }
75
+ }
76
+
77
+ async encode(payloads: Payload[]): Promise<Payload[]> {
78
+ return payloads.map((p) => this.encodePayload(p));
79
+ }
80
+
81
+ async decode(payloads: Payload[]): Promise<Payload[]> {
82
+ return Promise.all(payloads.map((p) => this.decodePayload(p)));
83
+ }
84
+
85
+ private encodePayload(payload: Payload): Payload {
86
+ // Data-less payloads (binary/null from void results) stay as-is:
87
+ // there is nothing to protect, and the cross-language parents that
88
+ // await our workflows as void must be able to read them without a key.
89
+ if (!payload.data || payload.data.length === 0) {
90
+ return payload;
91
+ }
92
+
93
+ const plaintext = temporal.api.common.v1.Payload.encode(payload).finish();
94
+ return {
95
+ metadata: {
96
+ [ENCODING_METADATA_KEY]: Buffer.from(ENCRYPTED_ENCODING_VALUE),
97
+ [KEY_ID_METADATA_KEY]: Buffer.from(this.config.primary.keyId),
98
+ },
99
+ data: encrypt(plaintext, this.config.primary),
100
+ };
101
+ }
102
+
103
+ private async decodePayload(payload: Payload): Promise<Payload> {
104
+ if (!isEncryptedPayload(payload)) {
105
+ return payload;
106
+ }
107
+
108
+ const keyIdBytes = payload.metadata?.[KEY_ID_METADATA_KEY];
109
+ if (!keyIdBytes) {
110
+ throw new Error(
111
+ "Encrypted payload is missing its encryption-key-id metadata — refusing to decode",
112
+ );
113
+ }
114
+ const keyId = Buffer.from(keyIdBytes).toString("utf-8");
115
+ const key = await this.decryptKeyFor(keyId);
116
+ if (!key) {
117
+ throw new Error(
118
+ `Encrypted payload uses unknown key id '${keyId}' — configure it as the ` +
119
+ `primary or secondary payload encryption key (rotation window?)`,
120
+ );
121
+ }
122
+
123
+ const plaintext = decrypt(payload.data!, key, keyId);
124
+ return temporal.api.common.v1.Payload.decode(plaintext);
125
+ }
126
+
127
+ /**
128
+ * The static map first; on a miss, the config's resolver (when present),
129
+ * caching the RESOLVED key only — a miss stays unresolved so a key
130
+ * minted after this process booted is found on the next decode.
131
+ */
132
+ private async decryptKeyFor(keyId: string): Promise<Buffer | undefined> {
133
+ const known = this.decryptKeysById.get(keyId);
134
+ if (known !== undefined) {
135
+ return known;
136
+ }
137
+ if (this.config.resolveKey === undefined) {
138
+ return undefined;
139
+ }
140
+ const resolved = await this.config.resolveKey(keyId);
141
+ if (resolved !== undefined) {
142
+ this.decryptKeysById.set(keyId, resolved);
143
+ }
144
+ return resolved;
145
+ }
146
+ }
147
+
148
+ function isEncryptedPayload(payload: Payload): boolean {
149
+ const encoding = payload.metadata?.[ENCODING_METADATA_KEY];
150
+ if (!encoding) return false;
151
+ return Buffer.from(encoding).toString("utf-8") === ENCRYPTED_ENCODING_VALUE;
152
+ }
153
+
154
+ function encrypt(plaintext: Uint8Array, key: EncryptionKey): Buffer {
155
+ const iv = randomBytes(IV_BYTES);
156
+ const cipher = createCipheriv("aes-256-gcm", key.key, iv);
157
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
158
+ // Layout iv ‖ ciphertext ‖ tag matches Java's AES/GCM/NoPadding, whose
159
+ // doFinal() output is ciphertext ‖ tag.
160
+ return Buffer.concat([iv, ciphertext, cipher.getAuthTag()]);
161
+ }
162
+
163
+ function decrypt(data: Uint8Array, key: Buffer, keyId: string): Buffer {
164
+ if (data.length < IV_BYTES + AUTH_TAG_BYTES) {
165
+ throw new Error(
166
+ `Encrypted payload under key id '${keyId}' is truncated (${data.length} bytes)`,
167
+ );
168
+ }
169
+ const buf = Buffer.from(data);
170
+ const iv = buf.subarray(0, IV_BYTES);
171
+ const ciphertext = buf.subarray(IV_BYTES, buf.length - AUTH_TAG_BYTES);
172
+ const tag = buf.subarray(buf.length - AUTH_TAG_BYTES);
173
+
174
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
175
+ decipher.setAuthTag(tag);
176
+ try {
177
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
178
+ } catch {
179
+ // GCM auth failure: tampered ciphertext or a key that does not match
180
+ // its advertised id. Never surface partially decrypted bytes.
181
+ throw new Error(
182
+ `Failed to decrypt payload under key id '${keyId}' — ciphertext is ` +
183
+ `corrupt or the configured key does not match`,
184
+ );
185
+ }
186
+ }
package/src/index.ts ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @stigmer/temporal-codecs — the Temporal plumbing Stigmer's TypeScript
3
+ * Temporal processes (the server and the runner) share: payload codecs,
4
+ * and the connection-security settings every Temporal connection reads
5
+ * (`connection/config.ts`). The encryption envelope is a cross-language
6
+ * wire contract (the Java decode-only codec in stigmer-cloud's
7
+ * temporal-starter must match it byte-for-byte, pinned by the fixture in
8
+ * src/__tests__/fixtures/), and the connection settings must mean the same
9
+ * on every connection, which is why both live in one library instead of
10
+ * per-consumer copies that could fork.
11
+ *
12
+ * This is the package's ONLY public boundary. Codec order at the consumer
13
+ * is a correctness property: install [encryption, claimcheck] so encode
14
+ * encrypts before relocating (object storage only ever sees ciphertext)
15
+ * and decode restores the blob before decrypting.
16
+ *
17
+ * Dependency policy: @temporalio/common and @temporalio/proto are pinned
18
+ * exact and identical to the runner's pins, bumped in lockstep with it —
19
+ * the runner's consumer-install gate (stigmer#786) fails any version mix
20
+ * because a split @temporalio/proto tree registers the core-sdk protobuf
21
+ * namespace twice and crashes worker init.
22
+ */
23
+
24
+ export { EncryptionPayloadCodec } from "./encryption/payload-codec.js";
25
+ export { loadPayloadEncryptionConfig } from "./encryption/config.js";
26
+ export type {
27
+ BootstrapKeyMaterial,
28
+ EncryptionKey,
29
+ PayloadEncryptionConfig,
30
+ PayloadKeyResolver,
31
+ SecretReader,
32
+ } from "./encryption/config.js";
33
+
34
+ export {
35
+ loadTemporalConnectionConfig,
36
+ temporalConnectionEnv,
37
+ TEMPORAL_API_KEY_ENV,
38
+ TEMPORAL_CONNECTION_ENV_NAMES,
39
+ TEMPORAL_TLS_CLIENT_KEY_DATA_ENV,
40
+ } from "./connection/config.js";
41
+ export type {
42
+ TemporalConnectionConfig,
43
+ TemporalTls,
44
+ } from "./connection/config.js";
45
+
46
+ export { ClaimcheckPayloadCodec } from "./claimcheck/payload-codec.js";
47
+ export { loadClaimcheckConfig } from "./claimcheck/config.js";
48
+ export type { ClaimcheckConfig } from "./claimcheck/config.js";
49
+ export type { ClaimcheckStorage } from "./claimcheck/storage.js";