@bramvanoploo/sandbox-runtime 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +93 -2
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +285 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/index.d.ts +16 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +12 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/sandbox/credential-decode.d.ts +87 -0
  12. package/dist/sandbox/credential-decode.d.ts.map +1 -0
  13. package/dist/sandbox/credential-decode.js +143 -0
  14. package/dist/sandbox/credential-decode.js.map +1 -0
  15. package/dist/sandbox/credential-extract.d.ts +67 -0
  16. package/dist/sandbox/credential-extract.d.ts.map +1 -0
  17. package/dist/sandbox/credential-extract.js +122 -0
  18. package/dist/sandbox/credential-extract.js.map +1 -0
  19. package/dist/sandbox/credential-mask-env.d.ts +33 -0
  20. package/dist/sandbox/credential-mask-env.d.ts.map +1 -0
  21. package/dist/sandbox/credential-mask-env.js +155 -0
  22. package/dist/sandbox/credential-mask-env.js.map +1 -0
  23. package/dist/sandbox/credential-mask-files.d.ts +120 -0
  24. package/dist/sandbox/credential-mask-files.d.ts.map +1 -0
  25. package/dist/sandbox/credential-mask-files.js +285 -0
  26. package/dist/sandbox/credential-mask-files.js.map +1 -0
  27. package/dist/sandbox/credential-sentinel.d.ts +88 -0
  28. package/dist/sandbox/credential-sentinel.d.ts.map +1 -0
  29. package/dist/sandbox/credential-sentinel.js +177 -0
  30. package/dist/sandbox/credential-sentinel.js.map +1 -0
  31. package/dist/sandbox/domain-pattern.d.ts +36 -0
  32. package/dist/sandbox/domain-pattern.d.ts.map +1 -0
  33. package/dist/sandbox/domain-pattern.js +60 -0
  34. package/dist/sandbox/domain-pattern.js.map +1 -0
  35. package/dist/sandbox/generate-seccomp-filter.d.ts +20 -0
  36. package/dist/sandbox/generate-seccomp-filter.d.ts.map +1 -0
  37. package/dist/sandbox/generate-seccomp-filter.js +168 -0
  38. package/dist/sandbox/generate-seccomp-filter.js.map +1 -0
  39. package/dist/sandbox/http-proxy.d.ts +85 -0
  40. package/dist/sandbox/http-proxy.d.ts.map +1 -0
  41. package/dist/sandbox/http-proxy.js +379 -0
  42. package/dist/sandbox/http-proxy.js.map +1 -0
  43. package/dist/sandbox/linux-sandbox-utils.d.ts +162 -0
  44. package/dist/sandbox/linux-sandbox-utils.d.ts.map +1 -0
  45. package/dist/sandbox/linux-sandbox-utils.js +1179 -0
  46. package/dist/sandbox/linux-sandbox-utils.js.map +1 -0
  47. package/dist/sandbox/linux-violation-monitor.d.ts +48 -0
  48. package/dist/sandbox/linux-violation-monitor.d.ts.map +1 -0
  49. package/dist/sandbox/linux-violation-monitor.js +168 -0
  50. package/dist/sandbox/linux-violation-monitor.js.map +1 -0
  51. package/dist/sandbox/listen-in-range.d.ts +12 -0
  52. package/dist/sandbox/listen-in-range.d.ts.map +1 -0
  53. package/dist/sandbox/listen-in-range.js +43 -0
  54. package/dist/sandbox/listen-in-range.js.map +1 -0
  55. package/dist/sandbox/macos-sandbox-utils.d.ts +57 -0
  56. package/dist/sandbox/macos-sandbox-utils.d.ts.map +1 -0
  57. package/dist/sandbox/macos-sandbox-utils.js +810 -0
  58. package/dist/sandbox/macos-sandbox-utils.js.map +1 -0
  59. package/dist/sandbox/mitm-ca.d.ts +112 -0
  60. package/dist/sandbox/mitm-ca.d.ts.map +1 -0
  61. package/dist/sandbox/mitm-ca.js +380 -0
  62. package/dist/sandbox/mitm-ca.js.map +1 -0
  63. package/dist/sandbox/mitm-leaf.d.ts +28 -0
  64. package/dist/sandbox/mitm-leaf.d.ts.map +1 -0
  65. package/dist/sandbox/mitm-leaf.js +132 -0
  66. package/dist/sandbox/mitm-leaf.js.map +1 -0
  67. package/dist/sandbox/mux-proxy.d.ts +59 -0
  68. package/dist/sandbox/mux-proxy.d.ts.map +1 -0
  69. package/dist/sandbox/mux-proxy.js +161 -0
  70. package/dist/sandbox/mux-proxy.js.map +1 -0
  71. package/dist/sandbox/parent-proxy.d.ts +118 -0
  72. package/dist/sandbox/parent-proxy.d.ts.map +1 -0
  73. package/dist/sandbox/parent-proxy.js +469 -0
  74. package/dist/sandbox/parent-proxy.js.map +1 -0
  75. package/dist/sandbox/request-filter.d.ts +56 -0
  76. package/dist/sandbox/request-filter.d.ts.map +1 -0
  77. package/dist/sandbox/request-filter.js +109 -0
  78. package/dist/sandbox/request-filter.js.map +1 -0
  79. package/dist/sandbox/sandbox-config.d.ts +1347 -0
  80. package/dist/sandbox/sandbox-config.d.ts.map +1 -0
  81. package/dist/sandbox/sandbox-config.js +917 -0
  82. package/dist/sandbox/sandbox-config.js.map +1 -0
  83. package/dist/sandbox/sandbox-manager.d.ts +48 -0
  84. package/dist/sandbox/sandbox-manager.d.ts.map +1 -0
  85. package/dist/sandbox/sandbox-manager.js +1498 -0
  86. package/dist/sandbox/sandbox-manager.js.map +1 -0
  87. package/dist/sandbox/sandbox-schemas.d.ts +90 -0
  88. package/dist/sandbox/sandbox-schemas.d.ts.map +1 -0
  89. package/dist/sandbox/sandbox-schemas.js +3 -0
  90. package/dist/sandbox/sandbox-schemas.js.map +1 -0
  91. package/dist/sandbox/sandbox-temp-dir.d.ts +9 -0
  92. package/dist/sandbox/sandbox-temp-dir.d.ts.map +1 -0
  93. package/dist/sandbox/sandbox-temp-dir.js +73 -0
  94. package/dist/sandbox/sandbox-temp-dir.js.map +1 -0
  95. package/dist/sandbox/sandbox-utils.d.ts +121 -0
  96. package/dist/sandbox/sandbox-utils.d.ts.map +1 -0
  97. package/dist/sandbox/sandbox-utils.js +642 -0
  98. package/dist/sandbox/sandbox-utils.js.map +1 -0
  99. package/dist/sandbox/sandbox-violation-store.d.ts +19 -0
  100. package/dist/sandbox/sandbox-violation-store.d.ts.map +1 -0
  101. package/dist/sandbox/sandbox-violation-store.js +57 -0
  102. package/dist/sandbox/sandbox-violation-store.js.map +1 -0
  103. package/dist/sandbox/socks-proxy.d.ts +38 -0
  104. package/dist/sandbox/socks-proxy.d.ts.map +1 -0
  105. package/dist/sandbox/socks-proxy.js +123 -0
  106. package/dist/sandbox/socks-proxy.js.map +1 -0
  107. package/dist/sandbox/tls-terminate-proxy.d.ts +63 -0
  108. package/dist/sandbox/tls-terminate-proxy.d.ts.map +1 -0
  109. package/dist/sandbox/tls-terminate-proxy.js +332 -0
  110. package/dist/sandbox/tls-terminate-proxy.js.map +1 -0
  111. package/dist/sandbox/windows-sandbox-utils.d.ts +625 -0
  112. package/dist/sandbox/windows-sandbox-utils.d.ts.map +1 -0
  113. package/dist/sandbox/windows-sandbox-utils.js +982 -0
  114. package/dist/sandbox/windows-sandbox-utils.js.map +1 -0
  115. package/dist/utils/config-loader.d.ts +24 -0
  116. package/dist/utils/config-loader.d.ts.map +1 -0
  117. package/dist/utils/config-loader.js +65 -0
  118. package/dist/utils/config-loader.js.map +1 -0
  119. package/dist/utils/debug.d.ts +7 -0
  120. package/dist/utils/debug.d.ts.map +1 -0
  121. package/dist/utils/debug.js +25 -0
  122. package/dist/utils/debug.js.map +1 -0
  123. package/dist/utils/platform.d.ts +15 -0
  124. package/dist/utils/platform.d.ts.map +1 -0
  125. package/dist/utils/platform.js +52 -0
  126. package/dist/utils/platform.js.map +1 -0
  127. package/dist/utils/shell-quote.d.ts +27 -0
  128. package/dist/utils/shell-quote.d.ts.map +1 -0
  129. package/dist/utils/shell-quote.js +47 -0
  130. package/dist/utils/shell-quote.js.map +1 -0
  131. package/dist/utils/which.d.ts +9 -0
  132. package/dist/utils/which.d.ts.map +1 -0
  133. package/dist/utils/which.js +28 -0
  134. package/dist/utils/which.js.map +1 -0
  135. package/package.json +85 -4
  136. package/vendor/seccomp/x64/apply-seccomp +0 -0
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Decoding support for encoded credential formats (`decode` on a
3
+ * `credentials.files` entry). Currently JWT only.
4
+ *
5
+ * Pure helpers: the default extraction pattern for finding JWT candidates
6
+ * in a file, the verification predicate that confirms a candidate actually
7
+ * is a JWT before it gets masked, and the minting of a JWT-shaped fake to
8
+ * stand in for the real token inside the sandbox.
9
+ */
10
+ /**
11
+ * Default `extract` pattern for `decode: "jwt"` entries.
12
+ *
13
+ * A JWT's first segment is the base64url encoding of a JSON header that
14
+ * starts `{"` (it always declares `alg`/`typ`), and base64url of `{"` is
15
+ * `eyJ` — so every JWT starts with `eyJ`. Capture group 1 is the whole
16
+ * three-segment token. The pattern over-matches (any eyJ-prefixed
17
+ * base64url triple); {@link verifyJwt} filters the false positives.
18
+ */
19
+ export declare const JWT_DEFAULT_EXTRACT_PATTERN = "(eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)";
20
+ /**
21
+ * True when `candidate` is structurally a JWT: three dot-separated
22
+ * segments, the first two base64url-decoding to JSON, and the header
23
+ * (segment 1) declaring an `alg` property.
24
+ *
25
+ * Used to filter extraction candidates before masking — a regex match
26
+ * that fails this check (e.g. a random base64 blob the default pattern
27
+ * over-matched) is left untouched rather than masked.
28
+ */
29
+ export declare function verifyJwt(candidate: string): boolean;
30
+ /**
31
+ * Mint a structurally valid fake JWT carrying the sentinel identity
32
+ * `fake_value_<uuid>` in its `sub` claim. Deterministic given `uuid`.
33
+ *
34
+ * The fake is parseable by client-side JWT handling (three segments, JSON
35
+ * header/payload, far-future `exp`), so a tool inside the sandbox that
36
+ * inspects the token before sending it doesn't break. The header says
37
+ * `alg: HS256` — NOT `alg: none` — deliberately: misconfigured validators
38
+ * accept `alg: none` tokens as valid, whereas an HS256 header forces every
39
+ * validator to attempt signature verification and reject the garbage
40
+ * signature. So if the fake ever reaches a verifier unswapped (e.g. sent
41
+ * to a non-injectHosts destination, the designed fail-closed pass-through),
42
+ * it is cryptographically rejected.
43
+ */
44
+ export declare function mintFakeJwt(uuid: string): string;
45
+ /** Result of {@link maskJwtClaims}. */
46
+ export interface MaskedClaimsResult {
47
+ /**
48
+ * The rebuilt token: the original header segment verbatim, the modified
49
+ * payload re-encoded, and the fixed filler signature.
50
+ */
51
+ fakeToken: string;
52
+ /** Claim name → the sentinel now carried in the fake payload. */
53
+ claimSentinels: Map<string, string>;
54
+ }
55
+ /**
56
+ * Claim-level masking for a verified JWT: replace each named top-level
57
+ * payload claim that is present with a string value by a caller-provided
58
+ * sentinel, and rebuild the token around the modified payload.
59
+ *
60
+ * The rebuilt token is `header.payload'.signature-filler`:
61
+ *
62
+ * - **Header**: the original base64url segment is reused verbatim, so the
63
+ * token still advertises the real `alg`/`typ`/`kid` and client-side
64
+ * header inspection sees exactly what it would outside the sandbox.
65
+ * - **Payload**: the decoded object with the named claims swapped for
66
+ * sentinels, re-encoded with `JSON.stringify`. Key order and whitespace
67
+ * inside the payload segment may differ from the original encoding —
68
+ * irrelevant to any JSON consumer, and the segment bytes change anyway
69
+ * because a claim value changed.
70
+ * - **Signature**: the fixed filler from {@link mintFakeJwt}, NOT the real
71
+ * signature. For RS/ES algorithms signature verification needs only the
72
+ * public key, so shipping the real signature over a modified payload
73
+ * would hand the sandbox an offline brute-force oracle for a low-entropy
74
+ * masked claim (guess the claim, re-encode, verify). The filler also
75
+ * keeps the fake a non-credential end to end, consistent with the
76
+ * garbage-signature rationale in {@link mintFakeJwt}.
77
+ *
78
+ * Claims that are absent from the payload, or present with a non-string
79
+ * value, are skipped (the caller logs them). Returns `null` — without
80
+ * invoking `sentinelFor` — when no named claim matched, or when the
81
+ * payload does not decode to a JSON object; the caller routes that
82
+ * through its no-match policy.
83
+ *
84
+ * Pure on `token`/`claims`; the callback may close over a registry.
85
+ */
86
+ export declare function maskJwtClaims(token: string, claims: readonly string[], sentinelFor: (claim: string, realValue: string) => string): MaskedClaimsResult | null;
87
+ //# sourceMappingURL=credential-decode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-decode.d.ts","sourceRoot":"","sources":["../../src/sandbox/credential-decode.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH;;;;;;;;GAQG;AACH,eAAO,MAAM,2BAA2B,0DACiB,CAAA;AAWzD;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAepD;AAeD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMhD;AAED,uCAAuC;AACvC,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,SAAS,EAAE,MAAM,CAAA;IACjB,iEAAiE;IACjE,cAAc,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACpC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,SAAS,MAAM,EAAE,EACzB,WAAW,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,MAAM,GACxD,kBAAkB,GAAG,IAAI,CA4B3B"}
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Decoding support for encoded credential formats (`decode` on a
3
+ * `credentials.files` entry). Currently JWT only.
4
+ *
5
+ * Pure helpers: the default extraction pattern for finding JWT candidates
6
+ * in a file, the verification predicate that confirms a candidate actually
7
+ * is a JWT before it gets masked, and the minting of a JWT-shaped fake to
8
+ * stand in for the real token inside the sandbox.
9
+ */
10
+ import { SENTINEL_PREFIX } from './credential-sentinel.js';
11
+ /**
12
+ * Default `extract` pattern for `decode: "jwt"` entries.
13
+ *
14
+ * A JWT's first segment is the base64url encoding of a JSON header that
15
+ * starts `{"` (it always declares `alg`/`typ`), and base64url of `{"` is
16
+ * `eyJ` — so every JWT starts with `eyJ`. Capture group 1 is the whole
17
+ * three-segment token. The pattern over-matches (any eyJ-prefixed
18
+ * base64url triple); {@link verifyJwt} filters the false positives.
19
+ */
20
+ export const JWT_DEFAULT_EXTRACT_PATTERN = '(eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)';
21
+ /** Parse a base64url segment as JSON, or undefined if either step fails. */
22
+ function decodeSegment(segment) {
23
+ try {
24
+ return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ /**
31
+ * True when `candidate` is structurally a JWT: three dot-separated
32
+ * segments, the first two base64url-decoding to JSON, and the header
33
+ * (segment 1) declaring an `alg` property.
34
+ *
35
+ * Used to filter extraction candidates before masking — a regex match
36
+ * that fails this check (e.g. a random base64 blob the default pattern
37
+ * over-matched) is left untouched rather than masked.
38
+ */
39
+ export function verifyJwt(candidate) {
40
+ const parts = candidate.split('.');
41
+ if (parts.length !== 3)
42
+ return false;
43
+ if (!/^[A-Za-z0-9_-]+$/.test(parts[0]) ||
44
+ !/^[A-Za-z0-9_-]+$/.test(parts[1]) ||
45
+ !/^[A-Za-z0-9_-]*$/.test(parts[2])) {
46
+ return false;
47
+ }
48
+ const header = decodeSegment(parts[0]);
49
+ if (typeof header !== 'object' || header === null || !('alg' in header)) {
50
+ return false;
51
+ }
52
+ return decodeSegment(parts[1]) !== undefined;
53
+ }
54
+ /**
55
+ * Fixed far-future `exp` claim for fake JWTs (2286-11-20). A constant, not
56
+ * an offset from now, so the fake is fully deterministic given the uuid.
57
+ */
58
+ const FAKE_JWT_EXP = 9999999999;
59
+ /** Fixed signature filler: base64url("srt-fake"). Never a valid signature. */
60
+ const FAKE_JWT_SIGNATURE = 'c3J0LWZha2U';
61
+ function base64url(s) {
62
+ return Buffer.from(s, 'utf8').toString('base64url');
63
+ }
64
+ /**
65
+ * Mint a structurally valid fake JWT carrying the sentinel identity
66
+ * `fake_value_<uuid>` in its `sub` claim. Deterministic given `uuid`.
67
+ *
68
+ * The fake is parseable by client-side JWT handling (three segments, JSON
69
+ * header/payload, far-future `exp`), so a tool inside the sandbox that
70
+ * inspects the token before sending it doesn't break. The header says
71
+ * `alg: HS256` — NOT `alg: none` — deliberately: misconfigured validators
72
+ * accept `alg: none` tokens as valid, whereas an HS256 header forces every
73
+ * validator to attempt signature verification and reject the garbage
74
+ * signature. So if the fake ever reaches a verifier unswapped (e.g. sent
75
+ * to a non-injectHosts destination, the designed fail-closed pass-through),
76
+ * it is cryptographically rejected.
77
+ */
78
+ export function mintFakeJwt(uuid) {
79
+ const header = base64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
80
+ const payload = base64url(JSON.stringify({ sub: SENTINEL_PREFIX + uuid, exp: FAKE_JWT_EXP }));
81
+ return `${header}.${payload}.${FAKE_JWT_SIGNATURE}`;
82
+ }
83
+ /**
84
+ * Claim-level masking for a verified JWT: replace each named top-level
85
+ * payload claim that is present with a string value by a caller-provided
86
+ * sentinel, and rebuild the token around the modified payload.
87
+ *
88
+ * The rebuilt token is `header.payload'.signature-filler`:
89
+ *
90
+ * - **Header**: the original base64url segment is reused verbatim, so the
91
+ * token still advertises the real `alg`/`typ`/`kid` and client-side
92
+ * header inspection sees exactly what it would outside the sandbox.
93
+ * - **Payload**: the decoded object with the named claims swapped for
94
+ * sentinels, re-encoded with `JSON.stringify`. Key order and whitespace
95
+ * inside the payload segment may differ from the original encoding —
96
+ * irrelevant to any JSON consumer, and the segment bytes change anyway
97
+ * because a claim value changed.
98
+ * - **Signature**: the fixed filler from {@link mintFakeJwt}, NOT the real
99
+ * signature. For RS/ES algorithms signature verification needs only the
100
+ * public key, so shipping the real signature over a modified payload
101
+ * would hand the sandbox an offline brute-force oracle for a low-entropy
102
+ * masked claim (guess the claim, re-encode, verify). The filler also
103
+ * keeps the fake a non-credential end to end, consistent with the
104
+ * garbage-signature rationale in {@link mintFakeJwt}.
105
+ *
106
+ * Claims that are absent from the payload, or present with a non-string
107
+ * value, are skipped (the caller logs them). Returns `null` — without
108
+ * invoking `sentinelFor` — when no named claim matched, or when the
109
+ * payload does not decode to a JSON object; the caller routes that
110
+ * through its no-match policy.
111
+ *
112
+ * Pure on `token`/`claims`; the callback may close over a registry.
113
+ */
114
+ export function maskJwtClaims(token, claims, sentinelFor) {
115
+ const [headerSeg, payloadSeg] = token.split('.');
116
+ const payload = decodeSegment(payloadSeg ?? '');
117
+ // verifyJwt only guarantees the payload is JSON — it could still be a
118
+ // scalar or array, which has no claims to mask.
119
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload))
120
+ return null;
121
+ const record = payload;
122
+ // Collect matches before minting any sentinel, so a null return never
123
+ // leaves an orphaned registration behind in the caller's registry.
124
+ const matched = [];
125
+ for (const claim of claims) {
126
+ const value = record[claim];
127
+ if (typeof value === 'string')
128
+ matched.push([claim, value]);
129
+ }
130
+ if (matched.length === 0)
131
+ return null;
132
+ const claimSentinels = new Map();
133
+ for (const [claim, value] of matched) {
134
+ const sentinel = sentinelFor(claim, value);
135
+ record[claim] = sentinel;
136
+ claimSentinels.set(claim, sentinel);
137
+ }
138
+ return {
139
+ fakeToken: `${headerSeg}.${base64url(JSON.stringify(record))}.${FAKE_JWT_SIGNATURE}`,
140
+ claimSentinels,
141
+ };
142
+ }
143
+ //# sourceMappingURL=credential-decode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-decode.js","sourceRoot":"","sources":["../../src/sandbox/credential-decode.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAE1D;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,2BAA2B,GACtC,uDAAuD,CAAA;AAEzD,4EAA4E;AAC5E,SAAS,aAAa,CAAC,OAAe;IACpC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAA;IACvE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAA;IAClB,CAAC;AACH,CAAC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A;QACxB,cAAc,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;IACrC,CAAC;IACD,OAAO;QACL,SAAS,EAAE,GAAG,SAAS,IAAI,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,kBAAkB,EAAE;QACpF,cAAc;KACf,CAAA;AACH,CAAC"}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Structured credential extraction, shared by file masking
3
+ * (credential-mask-files.ts) and env-var masking (credential-mask-env.ts).
4
+ *
5
+ * `extract` is a regex whose capture group 1 picks the credential value(s)
6
+ * out of a larger text (a config file, a connection-string env var). Only
7
+ * the captured span(s) are replaced with sentinels; the rest of the text is
8
+ * preserved byte-for-byte so parsers still succeed inside the sandbox.
9
+ */
10
+ /**
11
+ * Result of {@link extractAndSubstitute}: the content with each matched
12
+ * capture-group-1 span replaced by `sentinelFor(capture, i)`, plus the
13
+ * distinct captured values in first-seen (index) order.
14
+ */
15
+ export interface ExtractResult {
16
+ fakeContent: string;
17
+ captures: string[];
18
+ }
19
+ /** Options for {@link extractAndSubstitute}. */
20
+ export interface ExtractOptions {
21
+ /**
22
+ * If true, verbatim occurrences of each captured value *outside* the
23
+ * regex-matched spans are also replaced with that capture's sentinel —
24
+ * for a secret repeated where the regex does not reach (e.g. pasted
25
+ * into a comment). The scan matches raw substrings: a short or common
26
+ * captured value may corrupt unrelated content that happens to contain
27
+ * it, so this option is intended for long, high-entropy secrets.
28
+ */
29
+ maskDuplicates?: boolean;
30
+ }
31
+ /**
32
+ * Apply `pattern` globally to `content` and return `content` with each
33
+ * matched capture-group-1 span replaced by `sentinelFor(capture, i)`,
34
+ * where `i` is the zero-based index of the distinct captured value in
35
+ * first-seen order.
36
+ *
37
+ * Offset-based: the regex `d` flag exposes capture-group offsets, so the
38
+ * output is built by slicing between spans and splicing the sentinel in
39
+ * at the exact `[start, end)` of group 1. By default only the
40
+ * regex-matched span is replaced — a captured value that coincidentally
41
+ * appears elsewhere in the content (outside any match) is left intact. No
42
+ * placeholder pass, no substring-ordering concern.
43
+ *
44
+ * With `maskDuplicates` (see {@link ExtractOptions}), an indexOf scan
45
+ * additionally collects every verbatim occurrence of each captured value
46
+ * elsewhere in the content. All spans are computed against the ORIGINAL
47
+ * content — never the partially substituted output — so an inserted
48
+ * sentinel can never be re-matched and corrupted, even when a captured
49
+ * value is a substring of the sentinel literal. Regex-match spans win
50
+ * over verbatim ones, and verbatim scans run longest-capture-first so a
51
+ * shorter capture that is a substring of a longer one cannot claim part
52
+ * of the longer secret's occurrence. A capture the callback declined to
53
+ * mask (returned unchanged — the decode-verification gate) is excluded
54
+ * from the verbatim scan.
55
+ *
56
+ * Returns `null` when the pattern matches nothing — the caller routes
57
+ * that per the entry's `onExtractNoMatch` option (warn / deny / error).
58
+ *
59
+ * Throws when a match has no group-1 capture. The schema already rejects
60
+ * patterns with zero groups, so this only fires when group 1 is optional
61
+ * and absent for some match (e.g. `"token: (\\S+)?"`); accepting that
62
+ * would silently mask nothing for that occurrence.
63
+ *
64
+ * Pure on `content`/`pattern`; the callback may close over a registry.
65
+ */
66
+ export declare function extractAndSubstitute(content: string, pattern: string, sentinelFor: (capture: string, index: number) => string, options?: ExtractOptions): ExtractResult | null;
67
+ //# sourceMappingURL=credential-extract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-extract.d.ts","sourceRoot":"","sources":["../../src/sandbox/credential-extract.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,WAAW,EAAE,MAAM,CAAA;IACnB,QAAQ,EAAE,MAAM,EAAE,CAAA;CACnB;AAWD,gDAAgD;AAChD,MAAM,WAAW,cAAc;IAC7B;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;CACzB;AASD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,WAAW,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,EACvD,OAAO,GAAE,cAAmB,GAC3B,aAAa,GAAG,IAAI,CAiFtB"}
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Structured credential extraction, shared by file masking
3
+ * (credential-mask-files.ts) and env-var masking (credential-mask-env.ts).
4
+ *
5
+ * `extract` is a regex whose capture group 1 picks the credential value(s)
6
+ * out of a larger text (a config file, a connection-string env var). Only
7
+ * the captured span(s) are replaced with sentinels; the rest of the text is
8
+ * preserved byte-for-byte so parsers still succeed inside the sandbox.
9
+ */
10
+ /**
11
+ * Apply `pattern` globally to `content` and return `content` with each
12
+ * matched capture-group-1 span replaced by `sentinelFor(capture, i)`,
13
+ * where `i` is the zero-based index of the distinct captured value in
14
+ * first-seen order.
15
+ *
16
+ * Offset-based: the regex `d` flag exposes capture-group offsets, so the
17
+ * output is built by slicing between spans and splicing the sentinel in
18
+ * at the exact `[start, end)` of group 1. By default only the
19
+ * regex-matched span is replaced — a captured value that coincidentally
20
+ * appears elsewhere in the content (outside any match) is left intact. No
21
+ * placeholder pass, no substring-ordering concern.
22
+ *
23
+ * With `maskDuplicates` (see {@link ExtractOptions}), an indexOf scan
24
+ * additionally collects every verbatim occurrence of each captured value
25
+ * elsewhere in the content. All spans are computed against the ORIGINAL
26
+ * content — never the partially substituted output — so an inserted
27
+ * sentinel can never be re-matched and corrupted, even when a captured
28
+ * value is a substring of the sentinel literal. Regex-match spans win
29
+ * over verbatim ones, and verbatim scans run longest-capture-first so a
30
+ * shorter capture that is a substring of a longer one cannot claim part
31
+ * of the longer secret's occurrence. A capture the callback declined to
32
+ * mask (returned unchanged — the decode-verification gate) is excluded
33
+ * from the verbatim scan.
34
+ *
35
+ * Returns `null` when the pattern matches nothing — the caller routes
36
+ * that per the entry's `onExtractNoMatch` option (warn / deny / error).
37
+ *
38
+ * Throws when a match has no group-1 capture. The schema already rejects
39
+ * patterns with zero groups, so this only fires when group 1 is optional
40
+ * and absent for some match (e.g. `"token: (\\S+)?"`); accepting that
41
+ * would silently mask nothing for that occurrence.
42
+ *
43
+ * Pure on `content`/`pattern`; the callback may close over a registry.
44
+ */
45
+ export function extractAndSubstitute(content, pattern, sentinelFor, options = {}) {
46
+ // The schema validates `pattern` compiles; `g` makes matchAll iterate
47
+ // every occurrence and `d` populates `m.indices` with group offsets.
48
+ const re = new RegExp(pattern, 'gd');
49
+ const indexByCapture = new Map();
50
+ // First sentinel returned per capture — reused for verbatim spans so
51
+ // the duplicate pass never re-invokes the callback.
52
+ const sentinelByCapture = new Map();
53
+ const spans = [];
54
+ for (const m of content.matchAll(re)) {
55
+ const cap = m[1];
56
+ if (cap === undefined) {
57
+ throw new Error(`extract pattern /${pattern}/ matched at offset ${m.index} but ` +
58
+ `capture group 1 is undefined — group 1 must capture the ` +
59
+ `credential value on every match.`);
60
+ }
61
+ // Empty captures are skipped: a zero-width span has nothing to mask.
62
+ if (cap.length === 0)
63
+ continue;
64
+ const [start, end] = m.indices[1];
65
+ // Skip overlapping captures (e.g. from lookahead patterns) so splicing
66
+ // cannot go backwards and leak unmasked bytes.
67
+ if (spans.some(s => start < s.end && s.start < end))
68
+ continue;
69
+ let i = indexByCapture.get(cap);
70
+ if (i === undefined)
71
+ indexByCapture.set(cap, (i = indexByCapture.size));
72
+ const sentinel = sentinelFor(cap, i);
73
+ if (!sentinelByCapture.has(cap))
74
+ sentinelByCapture.set(cap, sentinel);
75
+ spans.push({ start, end, sentinel });
76
+ }
77
+ if (indexByCapture.size === 0)
78
+ return null;
79
+ spans.sort((a, b) => a.start - b.start);
80
+ if (options.maskDuplicates) {
81
+ // Longest capture first: a shorter capture that is a substring of a
82
+ // longer one would otherwise claim part of the longer secret's
83
+ // occurrence and leave the remainder exposed.
84
+ const byLength = [...indexByCapture.keys()].sort((a, b) => b.length - a.length);
85
+ for (const cap of byLength) {
86
+ const sentinel = sentinelByCapture.get(cap);
87
+ if (sentinel === cap)
88
+ continue;
89
+ // Binary search / monotonic scan against sorted spans for O(N log S)
90
+ // overlap checks instead of O(N * S).
91
+ let cursor = 0;
92
+ for (let start = content.indexOf(cap); start !== -1; start = content.indexOf(cap, start)) {
93
+ const end = start + cap.length;
94
+ while (cursor < spans.length && spans[cursor].end <= start) {
95
+ cursor++;
96
+ }
97
+ const hit = spans[cursor];
98
+ if (hit && hit.start < end) {
99
+ start = hit.end;
100
+ continue;
101
+ }
102
+ spans.push({ start, end, sentinel });
103
+ start = end;
104
+ }
105
+ spans.sort((a, b) => a.start - b.start);
106
+ }
107
+ }
108
+ // Spans are non-overlapping and sorted by offset (matchAll yields
109
+ // matches in order; the verbatim pass re-sorts), so a single
110
+ // slice-and-concat pass over the original content is sound.
111
+ let out = '';
112
+ let pos = 0;
113
+ for (const s of spans) {
114
+ out += content.slice(pos, s.start) + s.sentinel;
115
+ pos = s.end;
116
+ }
117
+ return {
118
+ fakeContent: out + content.slice(pos),
119
+ captures: [...indexByCapture.keys()],
120
+ };
121
+ }
122
+ //# sourceMappingURL=credential-extract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-extract.js","sourceRoot":"","sources":["../../src/sandbox/credential-extract.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAyCH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,UAAU,oBAAoB,CAClC,OAAe,EACf,OAAe,EACf,WAAuD,EACvD,UAA0B,EAAE;IAE5B,sEAAsE;IACtE,qEAAqE;IACrE,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;IACpC,MAAM,cAAc,GAAG,IAAI,GAAG,EAAkB,CAAA;IAChD,qEAAqE;IACrE,oDAAoD;IACpD,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAkB,CAAA;IACnD,MAAM,KAAK,GAAsB,EAAE,CAAA;IACnC,KAAK,MAAM,CAAC,IAA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AAK,GAAG,GAAG,CAAA;YACb,CAAC;YACD,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAA;QACzC,CAAC;IACH,CAAC;IAED,kEAAkE;IAClE,6DAA6D;IAC7D,4DAA4D;IAC5D,IAAI,GAAG,GAAG,EAAE,CAAA;IACZ,IAAI,GAAG,GAAG,CAAC,CAAA;IACX,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC;QACtB,GAAG,IAAI,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAA;QAC/C,GAAG,GAAG,CAAC,CAAC,GAAG,CAAA;IACb,CAAC;IACD,OAAO;QACL,WAAW,EAAE,GAAG,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC;QACrC,QAAQ,EAAE,CAAC,GAAG,cAAc,CAAC,IAAI,EAAE,CAAC;KACrC,CAAA;AACH,CAAC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Credential env-var masking.
3
+ *
4
+ * For a `credentials.envVars` entry with `mode: "mask"`, srt reads the real
5
+ * value from the host environment, registers one or more sentinels in the
6
+ * {@link SentinelRegistry}, and sets the variable to the fake value inside
7
+ * the sandbox (bwrap `--setenv` on Linux, the env preamble on macOS). The
8
+ * proxy substitutes sentinel→real on egress to the entry's injectHosts.
9
+ *
10
+ * Without `extract`, masking is **whole-value**: one sentinel replaces the
11
+ * entire value. With `extract`, masking is **structured**: a regex picks
12
+ * out the credential span(s) and only those are replaced, so a tool that
13
+ * parses the value (e.g. a `DATABASE_URL` connection string) still sees
14
+ * valid syntax. See {@link extractAndSubstitute} and
15
+ * {@link CredentialEnvVarConfigSchema}.
16
+ */
17
+ import type { CredentialEnvVarConfig } from './sandbox-config.js';
18
+ import type { SentinelRegistry } from './credential-sentinel.js';
19
+ /** Result of {@link buildMaskedEnvVars}. */
20
+ export interface MaskedEnvBuildResult {
21
+ /** NAME → fake value to set inside the sandbox. */
22
+ setEnvVars: Record<string, string>;
23
+ /**
24
+ * Names of `mode: "mask"` entries that degraded to unset at runtime —
25
+ * populated when `extract` matches nothing and the entry's
26
+ * `onExtractNoMatch` is `"deny"`. Callers union these into the
27
+ * unset-env set so the credential value is withheld rather than
28
+ * exposed (the env analog of a file degrading to `mode: "deny"`).
29
+ */
30
+ degradeToUnsetNames: string[];
31
+ }
32
+ export declare function buildMaskedEnvVars(envVars: readonly CredentialEnvVarConfig[], allowedDomains: readonly string[], registry: SentinelRegistry, env?: Record<string, string | undefined>): MaskedEnvBuildResult;
33
+ //# sourceMappingURL=credential-mask-env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-mask-env.d.ts","sourceRoot":"","sources":["../../src/sandbox/credential-mask-env.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAMH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAA;AACjE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAA;AAUhE,4CAA4C;AAC5C,MAAM,WAAW,oBAAoB;IACnC,mDAAmD;IACnD,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAClC;;;;;;OAMG;IACH,mBAAmB,EAAE,MAAM,EAAE,CAAA;CAC9B;AAyGD,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,SAAS,sBAAsB,EAAE,EAC1C,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,QAAQ,EAAE,gBAAgB,EAC1B,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GACpD,oBAAoB,CA6DtB"}
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Credential env-var masking.
3
+ *
4
+ * For a `credentials.envVars` entry with `mode: "mask"`, srt reads the real
5
+ * value from the host environment, registers one or more sentinels in the
6
+ * {@link SentinelRegistry}, and sets the variable to the fake value inside
7
+ * the sandbox (bwrap `--setenv` on Linux, the env preamble on macOS). The
8
+ * proxy substitutes sentinel→real on egress to the entry's injectHosts.
9
+ *
10
+ * Without `extract`, masking is **whole-value**: one sentinel replaces the
11
+ * entire value. With `extract`, masking is **structured**: a regex picks
12
+ * out the credential span(s) and only those are replaced, so a tool that
13
+ * parses the value (e.g. a `DATABASE_URL` connection string) still sees
14
+ * valid syntax. See {@link extractAndSubstitute} and
15
+ * {@link CredentialEnvVarConfigSchema}.
16
+ */
17
+ import { randomUUID } from 'node:crypto';
18
+ import { logForDebugging } from '../utils/debug.js';
19
+ import { maskJwtClaims, mintFakeJwt, verifyJwt } from './credential-decode.js';
20
+ import { extractAndSubstitute } from './credential-extract.js';
21
+ /**
22
+ * Sentinel-registry key prefix for structured (extract) env-var captures.
23
+ * Whole-value env masking keys on the bare variable name; extract captures
24
+ * key on `env:<NAME>#<i>` so the two forms — and masked files, which use
25
+ * `file:<path>` — can never collide (env var names cannot contain `:`).
26
+ */
27
+ const ENV_EXTRACT_KEY_PREFIX = 'env:';
28
+ /**
29
+ * For each `mode: "mask"` env-var entry: read the real value from `env`,
30
+ * build the fake value (whole-value or structured per `extract`), register
31
+ * sentinels in `registry`, and return the set-env map plus any entries
32
+ * that degraded to unset.
33
+ *
34
+ * Whole-value mode (no `extract`): one sentinel keyed on the bare variable
35
+ * name whose real value is the entire env value; the fake value *is* the
36
+ * sentinel.
37
+ *
38
+ * Structured mode (`extract` set): one sentinel per distinct captured
39
+ * value, keyed `env:<NAME>#<i>`; the fake value is the real value with
40
+ * each captured span replaced by its sentinel. If the regex matches
41
+ * nothing, the entry's `onExtractNoMatch` decides:
42
+ * - `"warn"` (default): skip the entry with a loud stderr warning —
43
+ * fail-open, the variable passes through with its real value;
44
+ * - `"deny"`: push the name to `degradeToUnsetNames` — fail-closed, the
45
+ * variable is unset inside the sandbox;
46
+ * - `"error"`: throw, so nothing runs until the regex is fixed.
47
+ *
48
+ * Decoded mode (`decode: "jwt"`): the whole value is verified as a JWT
49
+ * and replaced by a JWT-shaped fake registered as a caller-minted
50
+ * sentinel; with `maskClaims`, each named top-level payload claim present
51
+ * with a string value gets its own sentinel (keyed `env:<NAME>#<claim>`)
52
+ * and the token is rebuilt around the modified payload — BOTH the whole
53
+ * rebuilt token and each claim sentinel are registered under the same
54
+ * injectHosts. A value that does not verify — or, with `maskClaims`,
55
+ * verifies but has no named claim present as a string — fails open with a
56
+ * loud stderr warning.
57
+ *
58
+ * A masked variable with no value in `env` is skipped — there is nothing
59
+ * to protect, and emitting an unset (or set) var would change tool
60
+ * behaviour (presence checks would flip).
61
+ *
62
+ * `mode: "deny"` entries are ignored here; the caller handles them
63
+ * directly (they need no registry or host environment access).
64
+ */
65
+ function handleEnvNoMatch(v, cause, degradeToUnsetNames) {
66
+ const onNoMatch = v.onExtractNoMatch ?? 'warn';
67
+ if (onNoMatch === 'error') {
68
+ throw new Error(`credentials.envVars entry "${v.name}": ${cause} ` +
69
+ `(onExtractNoMatch: "error"). Fix the config, change to ` +
70
+ `"warn"/"deny", or remove the entry.`);
71
+ }
72
+ if (onNoMatch === 'deny') {
73
+ logForDebugging(`[credential-mask] ${v.name} has ${cause} — unsetting the variable.`, { level: 'warn' });
74
+ degradeToUnsetNames.push(v.name);
75
+ return;
76
+ }
77
+ const msg = `[sandbox-runtime] WARNING: credentials.envVars entry ` +
78
+ `"${v.name}" has ${cause}. The variable is left ` +
79
+ `UNPROTECTED (visible as-is inside the sandbox). Fix the config, ` +
80
+ `set onExtractNoMatch to "deny" or "error", or remove the entry.`;
81
+ console.warn(msg);
82
+ logForDebugging(msg, { level: 'warn' });
83
+ }
84
+ function maskJwtValue(name, token, maskClaims, injectHosts, registry) {
85
+ if (!verifyJwt(token))
86
+ return null;
87
+ if (maskClaims?.length) {
88
+ const masked = maskJwtClaims(token, maskClaims, (claim, val) => registry.register(`${name}#${claim}`, val, injectHosts));
89
+ if (masked === null)
90
+ return null;
91
+ const skipped = maskClaims.filter(c => !masked.claimSentinels.has(c));
92
+ if (skipped.length > 0) {
93
+ logForDebugging(`[credential-mask] env var "${name}": maskClaims ` +
94
+ `${JSON.stringify(skipped)} absent or non-string in the ` +
95
+ `JWT — skipped.`);
96
+ }
97
+ return registry.registerWithSentinel(name, masked.fakeToken, token, injectHosts);
98
+ }
99
+ return registry.registerWithSentinel(name, mintFakeJwt(randomUUID()), token, injectHosts);
100
+ }
101
+ export function buildMaskedEnvVars(envVars, allowedDomains, registry, env = process.env) {
102
+ const setEnvVars = {};
103
+ const degradeToUnsetNames = [];
104
+ for (const v of envVars) {
105
+ if (v.mode !== 'mask')
106
+ continue;
107
+ const real = env[v.name];
108
+ if (real === undefined)
109
+ continue;
110
+ const injectHosts = v.injectHosts ?? allowedDomains;
111
+ if (v.extract === undefined && v.decode === undefined) {
112
+ // Whole-value: one sentinel for the entire value.
113
+ setEnvVars[v.name] = registry.register(v.name, real, injectHosts);
114
+ continue;
115
+ }
116
+ if (v.decode === 'jwt' && v.extract === undefined) {
117
+ const fake = maskJwtValue(`${ENV_EXTRACT_KEY_PREFIX}${v.name}`, real, v.maskClaims, injectHosts, registry);
118
+ if (fake === null) {
119
+ const cause = v.maskClaims?.length
120
+ ? `decode "jwt" with maskClaims ${JSON.stringify(v.maskClaims)} that matched no verified JWT with maskable string claims`
121
+ : `decode "jwt" but its value did not verify as a JWT`;
122
+ handleEnvNoMatch(v, cause, degradeToUnsetNames);
123
+ continue;
124
+ }
125
+ setEnvVars[v.name] = fake;
126
+ continue;
127
+ }
128
+ const pattern = v.extract;
129
+ let maskedCount = 0;
130
+ const extracted = extractAndSubstitute(real, pattern, (cap, i) => {
131
+ const key = `${ENV_EXTRACT_KEY_PREFIX}${v.name}#${i}`;
132
+ if (v.decode === 'jwt') {
133
+ const fake = maskJwtValue(key, cap, v.maskClaims, injectHosts, registry);
134
+ if (fake === null)
135
+ return cap;
136
+ maskedCount++;
137
+ return fake;
138
+ }
139
+ maskedCount++;
140
+ return registry.register(key, cap, injectHosts);
141
+ });
142
+ if (extracted === null || maskedCount === 0) {
143
+ const cause = v.decode === 'jwt'
144
+ ? v.maskClaims?.length
145
+ ? `decode "jwt" with extract "${pattern}" that matched no verified JWT with maskable claims (maskClaims: ${JSON.stringify(v.maskClaims)})`
146
+ : `decode "jwt" with extract "${pattern}" that matched no verified JWT`
147
+ : `extract pattern "${pattern}" that matched nothing in the variable's value`;
148
+ handleEnvNoMatch(v, cause, degradeToUnsetNames);
149
+ continue;
150
+ }
151
+ setEnvVars[v.name] = extracted.fakeContent;
152
+ }
153
+ return { setEnvVars, degradeToUnsetNames };
154
+ }
155
+ //# sourceMappingURL=credential-mask-env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-mask-env.js","sourceRoot":"","sources":["../../src/sandbox/credential-mask-env.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAA;AAC9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAA;AAI9D;;;;;GAKG;AACH,MAAM,sBAAsB,GAAG,MAAM,CAAA;AAgBrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,SAAS,gBAAgB,CACvB,CAAyB,EACzB,KAAa,EACb,mBAA6B;IAE7B,MAAM,SAAS,GAAG,CAAC,CAAC,gBAAgB,IAAI,MAAM,CAAA;IAC9C,IAAI,SAAS,KAAK,OAAO,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CACb,8BAA8B,CAAC,CAAC,IAAI,MAAM,KAAK,GAAG;YAChD,yDAAyD;YACzD,qCAAqC,CACxC,CAAA;IACH,CAAC;IACD,IAAI,SAAS,KAAK,MAAM,E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