@stigmer/temporal-codecs 3.12.9
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/LICENSE +190 -0
- package/README.md +48 -0
- package/claimcheck/compressor.d.ts +12 -0
- package/claimcheck/compressor.d.ts.map +1 -0
- package/claimcheck/compressor.js +17 -0
- package/claimcheck/compressor.js.map +1 -0
- package/claimcheck/config.d.ts +17 -0
- package/claimcheck/config.d.ts.map +1 -0
- package/claimcheck/config.js +19 -0
- package/claimcheck/config.js.map +1 -0
- package/claimcheck/payload-codec.d.ts +29 -0
- package/claimcheck/payload-codec.d.ts.map +1 -0
- package/claimcheck/payload-codec.js +110 -0
- package/claimcheck/payload-codec.js.map +1 -0
- package/claimcheck/storage.d.ts +20 -0
- package/claimcheck/storage.d.ts.map +1 -0
- package/claimcheck/storage.js +2 -0
- package/claimcheck/storage.js.map +1 -0
- package/encryption/config.d.ts +82 -0
- package/encryption/config.d.ts.map +1 -0
- package/encryption/config.js +119 -0
- package/encryption/config.js.map +1 -0
- package/encryption/payload-codec.d.ts +46 -0
- package/encryption/payload-codec.d.ts.map +1 -0
- package/encryption/payload-codec.js +134 -0
- package/encryption/payload-codec.js.map +1 -0
- package/index.d.ts +28 -0
- package/index.d.ts.map +1 -0
- package/index.js +25 -0
- package/index.js.map +1 -0
- package/package.json +36 -0
- package/src/__test-utils__/fake-claimcheck-storage.ts +54 -0
- package/src/__tests__/claimcheck-codec.test.ts +256 -0
- package/src/__tests__/encryption-codec.test.ts +292 -0
- package/src/__tests__/fixtures/encrypted-payload-fixture.json +15 -0
- package/src/claimcheck/compressor.ts +19 -0
- package/src/claimcheck/config.ts +30 -0
- package/src/claimcheck/payload-codec.ts +144 -0
- package/src/claimcheck/storage.ts +19 -0
- package/src/encryption/config.ts +174 -0
- package/src/encryption/payload-codec.ts +156 -0
- package/src/index.ts +34 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Temporal PayloadCodec that transparently offloads large payloads to
|
|
3
|
+
* external storage ({@link ClaimcheckStorage}). Payloads below the
|
|
4
|
+
* threshold pass through unchanged. Payloads at or above the threshold
|
|
5
|
+
* are compressed (optional), uploaded, and replaced with a small
|
|
6
|
+
* reference marker.
|
|
7
|
+
*
|
|
8
|
+
* On decode, markers are detected, the original payload is downloaded
|
|
9
|
+
* and decompressed, and the original bytes are restored — transparent
|
|
10
|
+
* to workflow/activity code.
|
|
11
|
+
*
|
|
12
|
+
* Moved from backend/services/runner/src/claimcheck/payload-codec.ts when
|
|
13
|
+
* the codecs became @stigmer/temporal-codecs (one home for the
|
|
14
|
+
* cross-language envelope contract; the TS server is the second consumer).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { randomUUID } from "node:crypto";
|
|
18
|
+
import type { Payload, PayloadCodec } from "@temporalio/common";
|
|
19
|
+
import type { ClaimcheckStorage } from "./storage.js";
|
|
20
|
+
import type { ClaimcheckConfig } from "./config.js";
|
|
21
|
+
import { compress, decompress } from "./compressor.js";
|
|
22
|
+
|
|
23
|
+
const MARKER_METADATA_KEY = "encoding";
|
|
24
|
+
const MARKER_ENCODING_VALUE = "binary/claimcheck";
|
|
25
|
+
|
|
26
|
+
interface ClaimcheckMarker {
|
|
27
|
+
key: string;
|
|
28
|
+
size: number;
|
|
29
|
+
compressed: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* The relocated payload's original metadata, base64-encoded per value.
|
|
32
|
+
* Without it the restored payload would carry the marker's own
|
|
33
|
+
* "binary/claimcheck" encoding and no payload converter could interpret
|
|
34
|
+
* it. Absent on markers written before this field existed; those decode
|
|
35
|
+
* with the legacy (metadata-less) behavior.
|
|
36
|
+
*/
|
|
37
|
+
metadata?: Record<string, string>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export class ClaimcheckPayloadCodec implements PayloadCodec {
|
|
41
|
+
constructor(
|
|
42
|
+
private readonly storage: ClaimcheckStorage,
|
|
43
|
+
private readonly config: ClaimcheckConfig,
|
|
44
|
+
) {}
|
|
45
|
+
|
|
46
|
+
async encode(payloads: Payload[]): Promise<Payload[]> {
|
|
47
|
+
return Promise.all(payloads.map((p) => this.encodePayload(p)));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async decode(payloads: Payload[]): Promise<Payload[]> {
|
|
51
|
+
return Promise.all(payloads.map((p) => this.decodePayload(p)));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private async encodePayload(payload: Payload): Promise<Payload> {
|
|
55
|
+
const data = payload.data;
|
|
56
|
+
if (!data || data.length < this.config.thresholdBytes) {
|
|
57
|
+
return payload;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const originalBuf = Buffer.from(data);
|
|
61
|
+
let uploadBuf = originalBuf;
|
|
62
|
+
let compressed = false;
|
|
63
|
+
|
|
64
|
+
if (this.config.compressionEnabled) {
|
|
65
|
+
const compressedBuf = compress(originalBuf);
|
|
66
|
+
if (compressedBuf.length < originalBuf.length) {
|
|
67
|
+
uploadBuf = compressedBuf;
|
|
68
|
+
compressed = true;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const key = `${this.config.keyPrefix}${randomUUID()}`;
|
|
73
|
+
await this.storage.upload(key, uploadBuf, "application/octet-stream");
|
|
74
|
+
|
|
75
|
+
const marker: ClaimcheckMarker = {
|
|
76
|
+
key,
|
|
77
|
+
size: data.length,
|
|
78
|
+
compressed,
|
|
79
|
+
metadata: serializeMetadata(payload.metadata),
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
metadata: {
|
|
84
|
+
[MARKER_METADATA_KEY]: Buffer.from(MARKER_ENCODING_VALUE),
|
|
85
|
+
},
|
|
86
|
+
data: Buffer.from(JSON.stringify(marker)),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private async decodePayload(payload: Payload): Promise<Payload> {
|
|
91
|
+
if (!this.isClaimcheckPayload(payload)) {
|
|
92
|
+
return payload;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const marker: ClaimcheckMarker = JSON.parse(
|
|
96
|
+
Buffer.from(payload.data!).toString("utf-8"),
|
|
97
|
+
);
|
|
98
|
+
|
|
99
|
+
let rawBuf: Buffer;
|
|
100
|
+
try {
|
|
101
|
+
rawBuf = await this.storage.download(marker.key);
|
|
102
|
+
} catch (err) {
|
|
103
|
+
// Preserve the claimcheck-scoped error contract; the shared download error
|
|
104
|
+
// already carries the HTTP status (proxy) or the miss (local) as the cause.
|
|
105
|
+
const cause = err instanceof Error ? err.message : String(err);
|
|
106
|
+
throw new Error(`Claimcheck retrieve failed for key ${marker.key}: ${cause}`);
|
|
107
|
+
}
|
|
108
|
+
const dataBuf = marker.compressed ? decompress(rawBuf) : rawBuf;
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
metadata: marker.metadata
|
|
112
|
+
? deserializeMetadata(marker.metadata)
|
|
113
|
+
: payload.metadata,
|
|
114
|
+
data: dataBuf,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private isClaimcheckPayload(payload: Payload): boolean {
|
|
119
|
+
const encoding = payload.metadata?.[MARKER_METADATA_KEY];
|
|
120
|
+
if (!encoding) return false;
|
|
121
|
+
return Buffer.from(encoding).toString("utf-8") === MARKER_ENCODING_VALUE;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function serializeMetadata(
|
|
126
|
+
metadata: Payload["metadata"],
|
|
127
|
+
): Record<string, string> | undefined {
|
|
128
|
+
if (!metadata) return undefined;
|
|
129
|
+
const out: Record<string, string> = {};
|
|
130
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
131
|
+
if (value) out[key] = Buffer.from(value).toString("base64");
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function deserializeMetadata(
|
|
137
|
+
metadata: Record<string, string>,
|
|
138
|
+
): Record<string, Uint8Array> {
|
|
139
|
+
const out: Record<string, Uint8Array> = {};
|
|
140
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
141
|
+
out[key] = Buffer.from(value, "base64");
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The blob-store contract the claim-check codec needs — nothing more.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately minimal (upload + download by key) so any consumer's
|
|
5
|
+
* storage client satisfies it structurally: the runner's ArtifactStorage
|
|
6
|
+
* (a richer interface with presigned-URL minting) matches as-is, and the
|
|
7
|
+
* TS server brings its own. Widening this port widens the wire contract's
|
|
8
|
+
* dependency surface for every consumer — do not add methods the codec
|
|
9
|
+
* itself does not call.
|
|
10
|
+
*/
|
|
11
|
+
export interface ClaimcheckStorage {
|
|
12
|
+
/** Store `content` under `key`; resolves once the blob is durable. */
|
|
13
|
+
upload(key: string, content: Buffer, contentType?: string): Promise<string>;
|
|
14
|
+
/**
|
|
15
|
+
* Return the exact bytes stored under `key`, or throw a descriptive,
|
|
16
|
+
* key-scoped `Error` when the object is missing or the transport fails.
|
|
17
|
+
*/
|
|
18
|
+
download(key: string): Promise<Buffer>;
|
|
19
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Payload-encryption configuration (stigmer-cloud#227, 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
|
+
export interface PayloadEncryptionConfig {
|
|
46
|
+
/** Key used to encrypt outgoing payloads (and decrypt its own). */
|
|
47
|
+
readonly primary: EncryptionKey;
|
|
48
|
+
/** Decrypt-only key accepted during rotation windows. */
|
|
49
|
+
readonly secondary?: EncryptionKey;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Reads one secret VALUE by its env-var name. Consumers inject their own
|
|
54
|
+
* custody policy (see the module doc); the *_KEY_ID companions are
|
|
55
|
+
* rotation bookkeeping, not secrets, and stay plain `process.env` reads.
|
|
56
|
+
*/
|
|
57
|
+
export type SecretReader = (name: string) => string | undefined;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Server-managed key material delivered by the runner's
|
|
61
|
+
* getRunnerBootstrapConfig. Structurally mirrors
|
|
62
|
+
* {@link BootstrapPayloadEncryptionKeys} in the runner's stigmer-client.ts
|
|
63
|
+
* — declared here so the library stays free of client imports.
|
|
64
|
+
*/
|
|
65
|
+
export interface BootstrapKeyMaterial {
|
|
66
|
+
readonly key: string;
|
|
67
|
+
readonly keyId?: string;
|
|
68
|
+
readonly secondaryKey?: string;
|
|
69
|
+
readonly secondaryKeyId?: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const KEY_ENV = "STIGMER_PAYLOAD_ENCRYPTION_KEY";
|
|
73
|
+
const KEY_ID_ENV = "STIGMER_PAYLOAD_ENCRYPTION_KEY_ID";
|
|
74
|
+
const SECONDARY_KEY_ENV = "STIGMER_PAYLOAD_ENCRYPTION_SECONDARY_KEY";
|
|
75
|
+
const SECONDARY_KEY_ID_ENV = "STIGMER_PAYLOAD_ENCRYPTION_SECONDARY_KEY_ID";
|
|
76
|
+
|
|
77
|
+
const AES_256_KEY_BYTES = 32;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Returns the encryption config, or undefined when encryption is not
|
|
81
|
+
* configured (the codec is then simply not installed).
|
|
82
|
+
*
|
|
83
|
+
* Source precedence: the env key wins outright; bootstrap-delivered
|
|
84
|
+
* material applies only when no env key is set (see the module doc).
|
|
85
|
+
*
|
|
86
|
+
* @throws when a key is present but malformed, or a key id is missing —
|
|
87
|
+
* key misconfiguration must stop the boot, not degrade to plaintext.
|
|
88
|
+
* This applies equally to bootstrap material: a server that hands out
|
|
89
|
+
* a bad key or omits its id has broken the protocol contract, and
|
|
90
|
+
* running plaintext against a server that manages keys would silently
|
|
91
|
+
* defeat the feature.
|
|
92
|
+
*/
|
|
93
|
+
export function loadPayloadEncryptionConfig(
|
|
94
|
+
readSecret: SecretReader,
|
|
95
|
+
bootstrap?: BootstrapKeyMaterial,
|
|
96
|
+
): PayloadEncryptionConfig | undefined {
|
|
97
|
+
const rawKey = readSecret(KEY_ENV);
|
|
98
|
+
if (rawKey) {
|
|
99
|
+
const primary: EncryptionKey = {
|
|
100
|
+
keyId: requireKeyId(KEY_ID_ENV),
|
|
101
|
+
key: parseKey(rawKey, KEY_ENV),
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const rawSecondary = readSecret(SECONDARY_KEY_ENV);
|
|
105
|
+
const secondary: EncryptionKey | undefined = rawSecondary
|
|
106
|
+
? {
|
|
107
|
+
keyId: requireKeyId(SECONDARY_KEY_ID_ENV),
|
|
108
|
+
key: parseKey(rawSecondary, SECONDARY_KEY_ENV),
|
|
109
|
+
}
|
|
110
|
+
: undefined;
|
|
111
|
+
|
|
112
|
+
return { primary, secondary };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (bootstrap?.key) {
|
|
116
|
+
const primary: EncryptionKey = {
|
|
117
|
+
keyId: requireBootstrapKeyId(bootstrap.keyId, "payload_encryption_key_id"),
|
|
118
|
+
key: parseKey(bootstrap.key, "bootstrap payload_encryption_key"),
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const secondary: EncryptionKey | undefined = bootstrap.secondaryKey
|
|
122
|
+
? {
|
|
123
|
+
keyId: requireBootstrapKeyId(
|
|
124
|
+
bootstrap.secondaryKeyId,
|
|
125
|
+
"payload_encryption_secondary_key_id",
|
|
126
|
+
),
|
|
127
|
+
key: parseKey(bootstrap.secondaryKey, "bootstrap payload_encryption_secondary_key"),
|
|
128
|
+
}
|
|
129
|
+
: undefined;
|
|
130
|
+
|
|
131
|
+
return { primary, secondary };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function requireKeyId(envName: string): string {
|
|
138
|
+
const keyId = process.env[envName];
|
|
139
|
+
// An explicit id is required (no default): during rotation two keys
|
|
140
|
+
// coexist, and payloads must name which one encrypted them.
|
|
141
|
+
if (!keyId) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`Payload encryption misconfigured: ${envName} is required when the ` +
|
|
144
|
+
`corresponding key is set`,
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
return keyId;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function requireBootstrapKeyId(keyId: string | undefined, fieldName: string): string {
|
|
151
|
+
if (!keyId) {
|
|
152
|
+
throw new Error(
|
|
153
|
+
`Runner bootstrap returned a payload encryption key without its ${fieldName} — ` +
|
|
154
|
+
`refusing to encrypt under an unidentified key (server contract violation)`,
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
return keyId;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function parseKey(rawBase64: string, envName: string): Buffer {
|
|
161
|
+
let key: Buffer;
|
|
162
|
+
try {
|
|
163
|
+
key = Buffer.from(rawBase64, "base64");
|
|
164
|
+
} catch {
|
|
165
|
+
throw new Error(`Payload encryption misconfigured: ${envName} is not valid base64`);
|
|
166
|
+
}
|
|
167
|
+
if (key.length !== AES_256_KEY_BYTES) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
`Payload encryption misconfigured: ${envName} must decode to ` +
|
|
170
|
+
`${AES_256_KEY_BYTES} bytes (AES-256), got ${key.length}`,
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
return key;
|
|
174
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Temporal PayloadCodec that encrypts payloads at rest in workflow
|
|
3
|
+
* history (stigmer-cloud#227).
|
|
4
|
+
*
|
|
5
|
+
* Why: the workflow engine runs inside the Temporal deterministic
|
|
6
|
+
* sandbox, so decrypted execution-context values cross the history
|
|
7
|
+
* boundary in many places — the hydrate activity result, the runtime
|
|
8
|
+
* env passed as an input to every per-task activity, and expression
|
|
9
|
+
* results recorded as local-activity markers. Encrypting at the payload
|
|
10
|
+
* codec layer closes the entire class with one mechanism instead of
|
|
11
|
+
* chasing each crossing.
|
|
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
|
+
* Moved from backend/services/runner/src/encryption/payload-codec.ts when
|
|
32
|
+
* the codecs became @stigmer/temporal-codecs (one home for the
|
|
33
|
+
* cross-language envelope contract; the TS server is the second consumer).
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
|
37
|
+
import type { Payload, PayloadCodec } from "@temporalio/common";
|
|
38
|
+
// Default-import + destructure, NOT `import { temporal } from …`:
|
|
39
|
+
// @temporalio/proto is CommonJS and its `temporal` export defeats Node's
|
|
40
|
+
// cjs-module-lexer named-export detection, so the named form loads under
|
|
41
|
+
// tsx/vitest (their interop is looser) but crashes plain `node dist/main.js`
|
|
42
|
+
// at startup with "Named export 'temporal' not found" (stigmer/stigmer#399
|
|
43
|
+
// boot regression). Pinned by scripts/verify-dist-boot.mjs in CI.
|
|
44
|
+
import proto from "@temporalio/proto";
|
|
45
|
+
import type { EncryptionKey, PayloadEncryptionConfig } from "./config.js";
|
|
46
|
+
|
|
47
|
+
const { temporal } = proto;
|
|
48
|
+
|
|
49
|
+
const ENCODING_METADATA_KEY = "encoding";
|
|
50
|
+
const ENCRYPTED_ENCODING_VALUE = "binary/encrypted";
|
|
51
|
+
const KEY_ID_METADATA_KEY = "encryption-key-id";
|
|
52
|
+
|
|
53
|
+
/** AES-GCM parameters shared with the Java implementation. */
|
|
54
|
+
const IV_BYTES = 12;
|
|
55
|
+
const AUTH_TAG_BYTES = 16;
|
|
56
|
+
|
|
57
|
+
export class EncryptionPayloadCodec implements PayloadCodec {
|
|
58
|
+
private readonly decryptKeysById: Map<string, Buffer>;
|
|
59
|
+
|
|
60
|
+
constructor(private readonly config: PayloadEncryptionConfig) {
|
|
61
|
+
this.decryptKeysById = new Map([[config.primary.keyId, config.primary.key]]);
|
|
62
|
+
if (config.secondary) {
|
|
63
|
+
this.decryptKeysById.set(config.secondary.keyId, config.secondary.key);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async encode(payloads: Payload[]): Promise<Payload[]> {
|
|
68
|
+
return payloads.map((p) => this.encodePayload(p));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async decode(payloads: Payload[]): Promise<Payload[]> {
|
|
72
|
+
return payloads.map((p) => this.decodePayload(p));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
private encodePayload(payload: Payload): Payload {
|
|
76
|
+
// Data-less payloads (binary/null from void results) stay as-is:
|
|
77
|
+
// there is nothing to protect, and the cross-language parents that
|
|
78
|
+
// await our workflows as void must be able to read them without a key.
|
|
79
|
+
if (!payload.data || payload.data.length === 0) {
|
|
80
|
+
return payload;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const plaintext = temporal.api.common.v1.Payload.encode(payload).finish();
|
|
84
|
+
return {
|
|
85
|
+
metadata: {
|
|
86
|
+
[ENCODING_METADATA_KEY]: Buffer.from(ENCRYPTED_ENCODING_VALUE),
|
|
87
|
+
[KEY_ID_METADATA_KEY]: Buffer.from(this.config.primary.keyId),
|
|
88
|
+
},
|
|
89
|
+
data: encrypt(plaintext, this.config.primary),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private decodePayload(payload: Payload): Payload {
|
|
94
|
+
if (!isEncryptedPayload(payload)) {
|
|
95
|
+
return payload;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const keyIdBytes = payload.metadata?.[KEY_ID_METADATA_KEY];
|
|
99
|
+
if (!keyIdBytes) {
|
|
100
|
+
throw new Error(
|
|
101
|
+
"Encrypted payload is missing its encryption-key-id metadata — refusing to decode",
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
const keyId = Buffer.from(keyIdBytes).toString("utf-8");
|
|
105
|
+
const key = this.decryptKeysById.get(keyId);
|
|
106
|
+
if (!key) {
|
|
107
|
+
throw new Error(
|
|
108
|
+
`Encrypted payload uses unknown key id '${keyId}' — configure it as the ` +
|
|
109
|
+
`primary or secondary payload encryption key (rotation window?)`,
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const plaintext = decrypt(payload.data!, key, keyId);
|
|
114
|
+
return temporal.api.common.v1.Payload.decode(plaintext);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function isEncryptedPayload(payload: Payload): boolean {
|
|
119
|
+
const encoding = payload.metadata?.[ENCODING_METADATA_KEY];
|
|
120
|
+
if (!encoding) return false;
|
|
121
|
+
return Buffer.from(encoding).toString("utf-8") === ENCRYPTED_ENCODING_VALUE;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function encrypt(plaintext: Uint8Array, key: EncryptionKey): Buffer {
|
|
125
|
+
const iv = randomBytes(IV_BYTES);
|
|
126
|
+
const cipher = createCipheriv("aes-256-gcm", key.key, iv);
|
|
127
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
128
|
+
// Layout iv ‖ ciphertext ‖ tag matches Java's AES/GCM/NoPadding, whose
|
|
129
|
+
// doFinal() output is ciphertext ‖ tag.
|
|
130
|
+
return Buffer.concat([iv, ciphertext, cipher.getAuthTag()]);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function decrypt(data: Uint8Array, key: Buffer, keyId: string): Buffer {
|
|
134
|
+
if (data.length < IV_BYTES + AUTH_TAG_BYTES) {
|
|
135
|
+
throw new Error(
|
|
136
|
+
`Encrypted payload under key id '${keyId}' is truncated (${data.length} bytes)`,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
const buf = Buffer.from(data);
|
|
140
|
+
const iv = buf.subarray(0, IV_BYTES);
|
|
141
|
+
const ciphertext = buf.subarray(IV_BYTES, buf.length - AUTH_TAG_BYTES);
|
|
142
|
+
const tag = buf.subarray(buf.length - AUTH_TAG_BYTES);
|
|
143
|
+
|
|
144
|
+
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
|
145
|
+
decipher.setAuthTag(tag);
|
|
146
|
+
try {
|
|
147
|
+
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
148
|
+
} catch {
|
|
149
|
+
// GCM auth failure: tampered ciphertext or a key that does not match
|
|
150
|
+
// its advertised id. Never surface partially decrypted bytes.
|
|
151
|
+
throw new Error(
|
|
152
|
+
`Failed to decrypt payload under key id '${keyId}' — ciphertext is ` +
|
|
153
|
+
`corrupt or the configured key does not match`,
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @stigmer/temporal-codecs — Temporal payload codecs shared by Stigmer's
|
|
3
|
+
* TypeScript Temporal processes (the runner today; the TS server at its
|
|
4
|
+
* cutover). The encryption envelope is a cross-language wire contract
|
|
5
|
+
* (the Java decode-only codec in stigmer-cloud's temporal-starter must
|
|
6
|
+
* match it byte-for-byte, pinned by the fixture in
|
|
7
|
+
* src/__tests__/fixtures/), which is why the codecs live in one library
|
|
8
|
+
* instead of per-consumer copies that could fork.
|
|
9
|
+
*
|
|
10
|
+
* This is the package's ONLY public boundary. Codec order at the consumer
|
|
11
|
+
* is a correctness property: install [encryption, claimcheck] so encode
|
|
12
|
+
* encrypts before relocating (object storage only ever sees ciphertext)
|
|
13
|
+
* and decode restores the blob before decrypting.
|
|
14
|
+
*
|
|
15
|
+
* Dependency policy: @temporalio/common and @temporalio/proto are pinned
|
|
16
|
+
* exact and identical to the runner's pins, bumped in lockstep with it —
|
|
17
|
+
* the runner's consumer-install gate (stigmer#786) fails any version mix
|
|
18
|
+
* because a split @temporalio/proto tree registers the core-sdk protobuf
|
|
19
|
+
* namespace twice and crashes worker init.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export { EncryptionPayloadCodec } from "./encryption/payload-codec.js";
|
|
23
|
+
export { loadPayloadEncryptionConfig } from "./encryption/config.js";
|
|
24
|
+
export type {
|
|
25
|
+
BootstrapKeyMaterial,
|
|
26
|
+
EncryptionKey,
|
|
27
|
+
PayloadEncryptionConfig,
|
|
28
|
+
SecretReader,
|
|
29
|
+
} from "./encryption/config.js";
|
|
30
|
+
|
|
31
|
+
export { ClaimcheckPayloadCodec } from "./claimcheck/payload-codec.js";
|
|
32
|
+
export { loadClaimcheckConfig } from "./claimcheck/config.js";
|
|
33
|
+
export type { ClaimcheckConfig } from "./claimcheck/config.js";
|
|
34
|
+
export type { ClaimcheckStorage } from "./claimcheck/storage.js";
|