@stigmer/runner 3.12.7 → 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.
Files changed (79) hide show
  1. package/dist/.build-fingerprint +1 -1
  2. package/dist/activities/execute-cursor/fetch-interceptor.js +29 -16
  3. package/dist/activities/execute-cursor/fetch-interceptor.js.map +1 -1
  4. package/dist/activities/execute-cursor/index.d.ts +14 -0
  5. package/dist/activities/execute-cursor/index.js +76 -5
  6. package/dist/activities/execute-cursor/index.js.map +1 -1
  7. package/dist/activities/execute-cursor/message-translator.d.ts +15 -9
  8. package/dist/activities/execute-cursor/message-translator.js +15 -9
  9. package/dist/activities/execute-cursor/message-translator.js.map +1 -1
  10. package/dist/activities/execute-deep-agent/index.js +9 -0
  11. package/dist/activities/execute-deep-agent/index.js.map +1 -1
  12. package/dist/activities/execute-deep-agent/mcp-gate.d.ts +2 -0
  13. package/dist/activities/execute-deep-agent/mcp-gate.js +2 -1
  14. package/dist/activities/execute-deep-agent/mcp-gate.js.map +1 -1
  15. package/dist/activities/execute-deep-agent/setup.d.ts +10 -1
  16. package/dist/activities/execute-deep-agent/setup.js +45 -3
  17. package/dist/activities/execute-deep-agent/setup.js.map +1 -1
  18. package/dist/payload-codecs.d.ts +1 -1
  19. package/dist/payload-codecs.js +6 -4
  20. package/dist/payload-codecs.js.map +1 -1
  21. package/dist/shared/memory-attachment.d.ts +97 -0
  22. package/dist/shared/memory-attachment.js +136 -0
  23. package/dist/shared/memory-attachment.js.map +1 -0
  24. package/dist/shared/memory-retrieval.d.ts +126 -0
  25. package/dist/shared/memory-retrieval.js +293 -0
  26. package/dist/shared/memory-retrieval.js.map +1 -0
  27. package/dist/shared/runner-credential-keys.js +2 -1
  28. package/dist/shared/runner-credential-keys.js.map +1 -1
  29. package/dist/shared/tool-kind.js +9 -0
  30. package/dist/shared/tool-kind.js.map +1 -1
  31. package/package.json +3 -2
  32. package/src/__tests__/history-encryption-e2e.test.ts +1 -1
  33. package/src/activities/execute-cursor/__tests__/build-prompt.test.ts +40 -1
  34. package/src/activities/execute-cursor/__tests__/fetch-interceptor.test.ts +49 -15
  35. package/src/activities/execute-cursor/fetch-interceptor.ts +37 -16
  36. package/src/activities/execute-cursor/index.ts +86 -5
  37. package/src/activities/execute-cursor/message-translator.ts +15 -9
  38. package/src/activities/execute-deep-agent/__tests__/mcp-gate.test.ts +7 -0
  39. package/src/activities/execute-deep-agent/index.ts +10 -0
  40. package/src/activities/execute-deep-agent/mcp-gate.ts +4 -1
  41. package/src/activities/execute-deep-agent/setup.ts +70 -6
  42. package/src/payload-codecs.ts +12 -9
  43. package/src/shared/__tests__/memory-attachment.test.ts +167 -0
  44. package/src/shared/__tests__/memory-retrieval.test.ts +310 -0
  45. package/src/shared/memory-attachment.ts +167 -0
  46. package/src/shared/memory-retrieval.ts +383 -0
  47. package/src/shared/runner-credential-keys.ts +2 -1
  48. package/src/shared/tool-kind.ts +10 -0
  49. package/dist/claimcheck/compressor.d.ts +0 -2
  50. package/dist/claimcheck/compressor.js +0 -8
  51. package/dist/claimcheck/compressor.js.map +0 -1
  52. package/dist/claimcheck/config.d.ts +0 -7
  53. package/dist/claimcheck/config.js +0 -10
  54. package/dist/claimcheck/config.js.map +0 -1
  55. package/dist/claimcheck/index.d.ts +0 -3
  56. package/dist/claimcheck/index.js +0 -4
  57. package/dist/claimcheck/index.js.map +0 -1
  58. package/dist/claimcheck/payload-codec.d.ts +0 -23
  59. package/dist/claimcheck/payload-codec.js +0 -105
  60. package/dist/claimcheck/payload-codec.js.map +0 -1
  61. package/dist/encryption/config.d.ts +0 -64
  62. package/dist/encryption/config.js +0 -113
  63. package/dist/encryption/config.js.map +0 -1
  64. package/dist/encryption/index.d.ts +0 -3
  65. package/dist/encryption/index.js +0 -3
  66. package/dist/encryption/index.js.map +0 -1
  67. package/dist/encryption/payload-codec.d.ts +0 -41
  68. package/dist/encryption/payload-codec.js +0 -130
  69. package/dist/encryption/payload-codec.js.map +0 -1
  70. package/src/__tests__/claimcheck-codec.test.ts +0 -256
  71. package/src/__tests__/encryption-codec.test.ts +0 -287
  72. package/src/__tests__/fixtures/encrypted-payload-fixture.json +0 -15
  73. package/src/claimcheck/compressor.ts +0 -9
  74. package/src/claimcheck/config.ts +0 -20
  75. package/src/claimcheck/index.ts +0 -3
  76. package/src/claimcheck/payload-codec.ts +0 -139
  77. package/src/encryption/config.ts +0 -161
  78. package/src/encryption/index.ts +0 -3
  79. package/src/encryption/payload-codec.ts +0 -152
@@ -1,113 +0,0 @@
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
- import { getRunnerSecret } from "../shared/runner-credential-store.js";
28
- const KEY_ENV = "STIGMER_PAYLOAD_ENCRYPTION_KEY";
29
- const KEY_ID_ENV = "STIGMER_PAYLOAD_ENCRYPTION_KEY_ID";
30
- const SECONDARY_KEY_ENV = "STIGMER_PAYLOAD_ENCRYPTION_SECONDARY_KEY";
31
- const SECONDARY_KEY_ID_ENV = "STIGMER_PAYLOAD_ENCRYPTION_SECONDARY_KEY_ID";
32
- const AES_256_KEY_BYTES = 32;
33
- /**
34
- * Returns the encryption config, or undefined when encryption is not
35
- * configured (the codec is then simply not installed).
36
- *
37
- * Source precedence: the env key wins outright; bootstrap-delivered
38
- * material applies only when no env key is set (see the module doc).
39
- *
40
- * @throws when a key is present but malformed, or a key id is missing —
41
- * key misconfiguration must stop the boot, not degrade to plaintext.
42
- * This applies equally to bootstrap material: a server that hands out
43
- * a bad key or omits its id has broken the protocol contract, and
44
- * running plaintext against a server that manages keys would silently
45
- * defeat the feature.
46
- */
47
- export function loadPayloadEncryptionConfig(bootstrap) {
48
- // Key VALUES resolve through the credential store (the #508 boot capture
49
- // moves them out of process.env — agent shells must not read them); the
50
- // *_KEY_ID companions are rotation bookkeeping, not secrets, and stay
51
- // plain env reads.
52
- const rawKey = getRunnerSecret(KEY_ENV);
53
- if (rawKey) {
54
- const primary = {
55
- keyId: requireKeyId(KEY_ID_ENV),
56
- key: parseKey(rawKey, KEY_ENV),
57
- };
58
- const rawSecondary = getRunnerSecret(SECONDARY_KEY_ENV);
59
- const secondary = rawSecondary
60
- ? {
61
- keyId: requireKeyId(SECONDARY_KEY_ID_ENV),
62
- key: parseKey(rawSecondary, SECONDARY_KEY_ENV),
63
- }
64
- : undefined;
65
- return { primary, secondary };
66
- }
67
- if (bootstrap?.key) {
68
- const primary = {
69
- keyId: requireBootstrapKeyId(bootstrap.keyId, "payload_encryption_key_id"),
70
- key: parseKey(bootstrap.key, "bootstrap payload_encryption_key"),
71
- };
72
- const secondary = bootstrap.secondaryKey
73
- ? {
74
- keyId: requireBootstrapKeyId(bootstrap.secondaryKeyId, "payload_encryption_secondary_key_id"),
75
- key: parseKey(bootstrap.secondaryKey, "bootstrap payload_encryption_secondary_key"),
76
- }
77
- : undefined;
78
- return { primary, secondary };
79
- }
80
- return undefined;
81
- }
82
- function requireKeyId(envName) {
83
- const keyId = process.env[envName];
84
- // An explicit id is required (no default): during rotation two keys
85
- // coexist, and payloads must name which one encrypted them.
86
- if (!keyId) {
87
- throw new Error(`Payload encryption misconfigured: ${envName} is required when the ` +
88
- `corresponding key is set`);
89
- }
90
- return keyId;
91
- }
92
- function requireBootstrapKeyId(keyId, fieldName) {
93
- if (!keyId) {
94
- throw new Error(`Runner bootstrap returned a payload encryption key without its ${fieldName} — ` +
95
- `refusing to encrypt under an unidentified key (server contract violation)`);
96
- }
97
- return keyId;
98
- }
99
- function parseKey(rawBase64, envName) {
100
- let key;
101
- try {
102
- key = Buffer.from(rawBase64, "base64");
103
- }
104
- catch {
105
- throw new Error(`Payload encryption misconfigured: ${envName} is not valid base64`);
106
- }
107
- if (key.length !== AES_256_KEY_BYTES) {
108
- throw new Error(`Payload encryption misconfigured: ${envName} must decode to ` +
109
- `${AES_256_KEY_BYTES} bytes (AES-256), got ${key.length}`);
110
- }
111
- return key;
112
- }
113
- //# sourceMappingURL=config.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/encryption/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,sCAAsC,CAAC;AA4BvE,MAAM,OAAO,GAAG,gCAAgC,CAAC;AACjD,MAAM,UAAU,GAAG,mCAAmC,CAAC;AACvD,MAAM,iBAAiB,GAAG,0CAA0C,CAAC;AACrE,MAAM,oBAAoB,GAAG,6CAA6C,CAAC;AAE3E,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAE7B;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,2BAA2B,CACzC,SAAgC;IAEhC,yEAAyE;IACzE,wEAAwE;IACxE,sEAAsE;IACtE,mBAAmB;IACnB,MAAM,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;IACxC,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,OAAO,GAAkB;YAC7B,KAAK,EAAE,YAAY,CAA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ED,SAAS,qBAAqB,CAAC,KAAyB,EAAE,SAAiB;IACzE,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CACb,kEAAkE,SAAS,KAAK;YAC9E,2EAA2E,CAC9E,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,QAAQ,CAAC,SAAiB,EAAE,OAAe;IAClD,IAAI,GAAW,CAAC;IAChB,IAAI,CAAC;QACH,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IACzC,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CAAC,qCAAqC,OAAO,sBAAsB,CAAC,CAAC;IACtF,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,KAAK,iBAAiB,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CACb,qCAAqC,OAAO,kBAAkB;YAC5D,GAAG,iBAAiB,yBAAyB,GAAG,CAAC,MAAM,EAAE,CAC5D,CAAC;IACJ,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -1,3 +0,0 @@
1
- export { EncryptionPayloadCodec } from "./payload-codec.js";
2
- export { loadPayloadEncryptionConfig } from "./config.js";
3
- export type { PayloadEncryptionConfig, EncryptionKey } from "./config.js";
@@ -1,3 +0,0 @@
1
- export { EncryptionPayloadCodec } from "./payload-codec.js";
2
- export { loadPayloadEncryptionConfig } from "./config.js";
3
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/encryption/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC"}
@@ -1,41 +0,0 @@
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
- import type { Payload, PayloadCodec } from "@temporalio/common";
32
- import type { PayloadEncryptionConfig } from "./config.js";
33
- export declare class EncryptionPayloadCodec implements PayloadCodec {
34
- private readonly config;
35
- private readonly decryptKeysById;
36
- constructor(config: PayloadEncryptionConfig);
37
- encode(payloads: Payload[]): Promise<Payload[]>;
38
- decode(payloads: Payload[]): Promise<Payload[]>;
39
- private encodePayload;
40
- private decodePayload;
41
- }
@@ -1,130 +0,0 @@
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
- import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
32
- // Default-import + destructure, NOT `import { temporal } from …`:
33
- // @temporalio/proto is CommonJS and its `temporal` export defeats Node's
34
- // cjs-module-lexer named-export detection, so the named form loads under
35
- // tsx/vitest (their interop is looser) but crashes plain `node dist/main.js`
36
- // at startup with "Named export 'temporal' not found" (stigmer/stigmer#399
37
- // boot regression). Pinned by scripts/verify-dist-boot.mjs in CI.
38
- import proto from "@temporalio/proto";
39
- const { temporal } = proto;
40
- const ENCODING_METADATA_KEY = "encoding";
41
- const ENCRYPTED_ENCODING_VALUE = "binary/encrypted";
42
- const KEY_ID_METADATA_KEY = "encryption-key-id";
43
- /** AES-GCM parameters shared with the Java implementation. */
44
- const IV_BYTES = 12;
45
- const AUTH_TAG_BYTES = 16;
46
- export class EncryptionPayloadCodec {
47
- config;
48
- decryptKeysById;
49
- constructor(config) {
50
- this.config = config;
51
- this.decryptKeysById = new Map([[config.primary.keyId, config.primary.key]]);
52
- if (config.secondary) {
53
- this.decryptKeysById.set(config.secondary.keyId, config.secondary.key);
54
- }
55
- }
56
- async encode(payloads) {
57
- return payloads.map((p) => this.encodePayload(p));
58
- }
59
- async decode(payloads) {
60
- return payloads.map((p) => this.decodePayload(p));
61
- }
62
- encodePayload(payload) {
63
- // Data-less payloads (binary/null from void results) stay as-is:
64
- // there is nothing to protect, and the cross-language parents that
65
- // await our workflows as void must be able to read them without a key.
66
- if (!payload.data || payload.data.length === 0) {
67
- return payload;
68
- }
69
- const plaintext = temporal.api.common.v1.Payload.encode(payload).finish();
70
- return {
71
- metadata: {
72
- [ENCODING_METADATA_KEY]: Buffer.from(ENCRYPTED_ENCODING_VALUE),
73
- [KEY_ID_METADATA_KEY]: Buffer.from(this.config.primary.keyId),
74
- },
75
- data: encrypt(plaintext, this.config.primary),
76
- };
77
- }
78
- decodePayload(payload) {
79
- if (!isEncryptedPayload(payload)) {
80
- return payload;
81
- }
82
- const keyIdBytes = payload.metadata?.[KEY_ID_METADATA_KEY];
83
- if (!keyIdBytes) {
84
- throw new Error("Encrypted payload is missing its encryption-key-id metadata — refusing to decode");
85
- }
86
- const keyId = Buffer.from(keyIdBytes).toString("utf-8");
87
- const key = this.decryptKeysById.get(keyId);
88
- if (!key) {
89
- throw new Error(`Encrypted payload uses unknown key id '${keyId}' — configure it as the ` +
90
- `primary or secondary payload encryption key (rotation window?)`);
91
- }
92
- const plaintext = decrypt(payload.data, key, keyId);
93
- return temporal.api.common.v1.Payload.decode(plaintext);
94
- }
95
- }
96
- function isEncryptedPayload(payload) {
97
- const encoding = payload.metadata?.[ENCODING_METADATA_KEY];
98
- if (!encoding)
99
- return false;
100
- return Buffer.from(encoding).toString("utf-8") === ENCRYPTED_ENCODING_VALUE;
101
- }
102
- function encrypt(plaintext, key) {
103
- const iv = randomBytes(IV_BYTES);
104
- const cipher = createCipheriv("aes-256-gcm", key.key, iv);
105
- const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
106
- // Layout iv ‖ ciphertext ‖ tag matches Java's AES/GCM/NoPadding, whose
107
- // doFinal() output is ciphertext ‖ tag.
108
- return Buffer.concat([iv, ciphertext, cipher.getAuthTag()]);
109
- }
110
- function decrypt(data, key, keyId) {
111
- if (data.length < IV_BYTES + AUTH_TAG_BYTES) {
112
- throw new Error(`Encrypted payload under key id '${keyId}' is truncated (${data.length} bytes)`);
113
- }
114
- const buf = Buffer.from(data);
115
- const iv = buf.subarray(0, IV_BYTES);
116
- const ciphertext = buf.subarray(IV_BYTES, buf.length - AUTH_TAG_BYTES);
117
- const tag = buf.subarray(buf.length - AUTH_TAG_BYTES);
118
- const decipher = createDecipheriv("aes-256-gcm", key, iv);
119
- decipher.setAuthTag(tag);
120
- try {
121
- return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
122
- }
123
- catch {
124
- // GCM auth failure: tampered ciphertext or a key that does not match
125
- // its advertised id. Never surface partially decrypted bytes.
126
- throw new Error(`Failed to decrypt payload under key id '${keyId}' — ciphertext is ` +
127
- `corrupt or the configured key does not match`);
128
- }
129
- }
130
- //# sourceMappingURL=payload-codec.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"payload-codec.js","sourceRoot":"","sources":["../../src/encryption/payload-codec.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE5E,kEAAkE;AAClE,yEAAyE;AACzE,yEAAyE;AACzE,6EAA6E;AAC7E,2EAA2E;AAC3E,kEAAkE;AAClE,OAAO,KAAK,MAAM,mBAAmB,CAAC;AAGtC,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;AAE3B,MAAM,qBAAqB,GAAG,UAAU,CAAC;AACzC,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;AACpD,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAEhD,8DAA8D;AAC9D,MAAM,QAAQ,GAAG,EAAE,CAAC;AACpB,MAAM,cAAc,GAAG,EAAE,CAAC;AAE1B,MAAM,OAAO,sBAAsB;IAGJ;IAFZ,eAAe,CAAsB;IAEtD,YAA6B,MAA+B;QAA/B,WAAM,GA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AAE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IACxE,CAAC;IAAC,MAAM,CAAC;QACP,qEAAqE;QACrE,8DAA8D;QAC9D,MAAM,IAAI,KAAK,CACb,2CAA2C,KAAK,oBAAoB;YAClE,8CAA8C,CACjD,CAAC;IACJ,CAAC;AACH,CAAC"}
@@ -1,256 +0,0 @@
1
- import { describe, it, expect, beforeEach } from "vitest";
2
- import { ClaimcheckPayloadCodec } from "../claimcheck/payload-codec.js";
3
- import { compress } from "../claimcheck/compressor.js";
4
- import type { ClaimcheckConfig } from "../claimcheck/config.js";
5
- import { makeInMemoryArtifactStorage } from "../__test-utils__/fake-artifact-storage.js";
6
- import type { Payload } from "@temporalio/common";
7
-
8
- function makeConfig(overrides: Partial<ClaimcheckConfig> = {}): ClaimcheckConfig {
9
- return {
10
- enabled: true,
11
- thresholdBytes: 1024,
12
- compressionEnabled: true,
13
- keyPrefix: "claimcheck/",
14
- ...overrides,
15
- };
16
- }
17
-
18
- function makeStorage() {
19
- // The canonical in-memory double; `uploads` aliases its backing Map so the
20
- // existing `storage.uploads.*` assertions keep working, and `download` reads
21
- // straight from what `encode` uploaded (no fetch to stub).
22
- const { storage, blobs } = makeInMemoryArtifactStorage();
23
- return Object.assign(storage, { uploads: blobs });
24
- }
25
-
26
- function makePayload(data: string | Buffer): Payload {
27
- const buf = typeof data === "string" ? Buffer.from(data) : data;
28
- return {
29
- metadata: { encoding: Buffer.from("binary/plain") },
30
- data: buf,
31
- };
32
- }
33
-
34
- function makeLargePayload(sizeBytes: number): Payload {
35
- const buf = Buffer.alloc(sizeBytes, "x");
36
- return {
37
- metadata: { encoding: Buffer.from("binary/plain") },
38
- data: buf,
39
- };
40
- }
41
-
42
- describe("ClaimcheckPayloadCodec", () => {
43
- let storage: ReturnType<typeof makeStorage>;
44
- let codec: ClaimcheckPayloadCodec;
45
-
46
- beforeEach(() => {
47
- storage = makeStorage();
48
- codec = new ClaimcheckPayloadCodec(storage, makeConfig());
49
- });
50
-
51
- describe("encode", () => {
52
- it("passes through payloads below threshold unchanged", async () => {
53
- const payload = makePayload("small data");
54
- const [result] = await codec.encode([payload]);
55
- expect(result).toBe(payload);
56
- expect(storage.uploads.size).toBe(0);
57
- });
58
-
59
- it("passes through empty payloads", async () => {
60
- const payload: Payload = { metadata: {}, data: undefined };
61
- const [result] = await codec.encode([payload]);
62
- expect(result).toBe(payload);
63
- });
64
-
65
- it("offloads payloads at or above threshold", async () => {
66
- const payload = makeLargePayload(1024);
67
- const [result] = await codec.encode([payload]);
68
-
69
- expect(result).not.toBe(payload);
70
- expect(storage.uploads.size).toBe(1);
71
-
72
- const markerMeta = result.metadata?.["encoding"];
73
- expect(Buffer.from(markerMeta!).toString()).toBe("binary/claimcheck");
74
-
75
- const marker = JSON.parse(Buffer.from(result.data!).toString());
76
- expect(marker.key).toMatch(/^claimcheck\//);
77
- expect(marker.size).toBe(1024);
78
- expect(marker.compressed).toBe(true);
79
- });
80
-
81
- it("skips compression when it does not reduce size", async () => {
82
- const randomBuf = Buffer.from(
83
- Array.from({ length: 1024 }, () => Math.floor(Math.random() * 256)),
84
- );
85
- const payload: Payload = {
86
- metadata: { encoding: Buffer.from("binary/plain") },
87
- data: randomBuf,
88
- };
89
-
90
- const compressedSize = compress(randomBuf).length;
91
- if (compressedSize >= randomBuf.length) {
92
- const [result] = await codec.encode([payload]);
93
- const marker = JSON.parse(Buffer.from(result.data!).toString());
94
- expect(marker.compressed).toBe(false);
95
-
96
- const uploaded = storage.uploads.values().next().value!;
97
- expect(uploaded.length).toBe(randomBuf.length);
98
- }
99
- });
100
-
101
- it("does not compress when compression is disabled", async () => {
102
- codec = new ClaimcheckPayloadCodec(
103
- storage,
104
- makeConfig({ compressionEnabled: false }),
105
- );
106
- const payload = makeLargePayload(1024);
107
- const [result] = await codec.encode([payload]);
108
-
109
- const marker = JSON.parse(Buffer.from(result.data!).toString());
110
- expect(marker.compressed).toBe(false);
111
-
112
- const uploaded = storage.uploads.values().next().value!;
113
- expect(uploaded.length).toBe(1024);
114
- });
115
-
116
- it("handles multiple payloads in a batch", async () => {
117
- const small = makePayload("tiny");
118
- const large = makeLargePayload(2048);
119
-
120
- const results = await codec.encode([small, large]);
121
- expect(results[0]).toBe(small);
122
- expect(results[1]).not.toBe(large);
123
- expect(storage.uploads.size).toBe(1);
124
- });
125
-
126
- it("uses configured key prefix", async () => {
127
- codec = new ClaimcheckPayloadCodec(
128
- storage,
129
- makeConfig({ keyPrefix: "custom-prefix/" }),
130
- );
131
- const payload = makeLargePayload(1024);
132
- const [result] = await codec.encode([payload]);
133
-
134
- const marker = JSON.parse(Buffer.from(result.data!).toString());
135
- expect(marker.key).toMatch(/^custom-prefix\//);
136
- });
137
- });
138
-
139
- describe("decode", () => {
140
- it("passes through non-claimcheck payloads unchanged", async () => {
141
- const payload = makePayload("normal data");
142
- const [result] = await codec.decode([payload]);
143
- expect(result).toBe(payload);
144
- });
145
-
146
- it("retrieves and decompresses offloaded payloads (round-trip)", async () => {
147
- const original = makeLargePayload(2048);
148
- const [encoded] = await codec.encode([original]);
149
-
150
- // decode reads back through storage.download from what encode uploaded.
151
- const [decoded] = await codec.decode([encoded]);
152
- expect(Buffer.from(decoded.data!)).toEqual(original.data);
153
- });
154
-
155
- it("restores the original payload metadata (round-trip)", async () => {
156
- // The restored payload must carry its ORIGINAL encoding, not the
157
- // marker's binary/claimcheck — otherwise no payload converter can
158
- // interpret it and composition with the encryption codec breaks.
159
- const original: Payload = {
160
- metadata: {
161
- encoding: Buffer.from("json/plain"),
162
- "custom-key": Buffer.from("custom-value"),
163
- },
164
- data: Buffer.alloc(2048, "y"),
165
- };
166
-
167
- const [encoded] = await codec.encode([original]);
168
- const [decoded] = await codec.decode([encoded]);
169
-
170
- expect(Buffer.from(decoded.metadata!["encoding"]!).toString()).toBe("json/plain");
171
- expect(Buffer.from(decoded.metadata!["custom-key"]!).toString()).toBe("custom-value");
172
- expect(Buffer.from(decoded.data!)).toEqual(original.data);
173
- });
174
-
175
- it("decodes legacy markers written before metadata preservation", async () => {
176
- const original = makeLargePayload(2048);
177
- const [encoded] = await codec.encode([original]);
178
-
179
- // Simulate a pre-fix marker: strip the metadata field.
180
- const marker = JSON.parse(Buffer.from(encoded.data!).toString());
181
- delete marker.metadata;
182
- const legacy: Payload = {
183
- metadata: encoded.metadata,
184
- data: Buffer.from(JSON.stringify(marker)),
185
- };
186
-
187
- const [decoded] = await codec.decode([legacy]);
188
- expect(Buffer.from(decoded.data!)).toEqual(original.data);
189
- });
190
-
191
- it("retrieves uncompressed payloads correctly", async () => {
192
- codec = new ClaimcheckPayloadCodec(
193
- storage,
194
- makeConfig({ compressionEnabled: false }),
195
- );
196
-
197
- const original = makeLargePayload(1500);
198
- const [encoded] = await codec.encode([original]);
199
-
200
- const [decoded] = await codec.decode([encoded]);
201
- expect(Buffer.from(decoded.data!)).toEqual(original.data);
202
- });
203
-
204
- it("wraps a download failure with the claimcheck error contract", async () => {
205
- const encoded: Payload = {
206
- metadata: { encoding: Buffer.from("binary/claimcheck") },
207
- data: Buffer.from(JSON.stringify({
208
- key: "claimcheck/missing",
209
- size: 100,
210
- compressed: false,
211
- })),
212
- };
213
-
214
- // Drive the failure through the port; the proxy download surfaces the HTTP
215
- // status, which the codec must preserve in its wrapped, key-scoped message.
216
- storage.download.mockRejectedValueOnce(
217
- new Error("Artifact download failed (HTTP 404) for key 'claimcheck/missing'"),
218
- );
219
-
220
- await expect(codec.decode([encoded])).rejects.toThrow(
221
- /Claimcheck retrieve failed for key claimcheck\/missing.*HTTP 404/,
222
- );
223
- });
224
- });
225
-
226
- describe("threshold boundary", () => {
227
- it("does NOT offload at threshold - 1", async () => {
228
- const payload = makeLargePayload(1023);
229
- const [result] = await codec.encode([payload]);
230
- expect(result).toBe(payload);
231
- });
232
-
233
- it("offloads at exactly threshold", async () => {
234
- const payload = makeLargePayload(1024);
235
- const [result] = await codec.encode([payload]);
236
- expect(result).not.toBe(payload);
237
- });
238
-
239
- it("offloads above threshold", async () => {
240
- const payload = makeLargePayload(1025);
241
- const [result] = await codec.encode([payload]);
242
- expect(result).not.toBe(payload);
243
- });
244
- });
245
-
246
- describe("compressor", () => {
247
- it("compresses and decompresses correctly", async () => {
248
- const { compress: c, decompress: d } = await import("../claimcheck/compressor.js");
249
- const input = Buffer.from("hello world ".repeat(100));
250
- const compressed = c(input);
251
- expect(compressed.length).toBeLessThan(input.length);
252
- const decompressed = d(compressed);
253
- expect(decompressed).toEqual(input);
254
- });
255
- });
256
- });