@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,120 @@
1
+ /**
2
+ * Credential file masking (Linux).
3
+ *
4
+ * For a `credentials.files` entry with `mode: "mask"`, srt reads the real
5
+ * file content on the host, registers one or more sentinels in the
6
+ * {@link SentinelRegistry}, and writes a fake file (sentinel-substituted)
7
+ * to a manager-owned temp directory. The Linux sandbox then `--ro-bind`s
8
+ * the fake over the real path, so the sandboxed process reads the
9
+ * sentinel(s). The proxy substitution from env-var masking already scans
10
+ * every header for any registered sentinel, so a tool that does
11
+ * `Authorization: Bearer $(cat <maskedFile>)` reaches the upstream with
12
+ * the real bytes — no proxy changes required.
13
+ *
14
+ * Without `extract`, masking is **whole-file**: one sentinel replaces the
15
+ * entire content. With `extract`, masking is **structured**: a regex picks
16
+ * out the credential value(s) and only those spans are replaced, so a tool
17
+ * that parses the file (JSON/YAML/.netrc) still sees valid syntax. See
18
+ * {@link extractAndSubstitute} and {@link CredentialFileConfigSchema}.
19
+ *
20
+ * On macOS, SBPL cannot redirect reads, so masked files degrade to
21
+ * `mode: "deny"` (see macos-sandbox-utils.ts).
22
+ */
23
+ import type { CredentialFileConfig } from './sandbox-config.js';
24
+ import type { SentinelRegistry } from './credential-sentinel.js';
25
+ /** One masked file's bind mapping for the platform builder. */
26
+ export interface MaskedFileBind {
27
+ /** Resolved (tilde-expanded, realpath'd) host path of the real file. */
28
+ realPath: string;
29
+ /** Path to the fake file containing the sentinel. */
30
+ fakePath: string;
31
+ }
32
+ /**
33
+ * Manager-owned temp dir holding the fake files.
34
+ *
35
+ * INVARIANT: this directory must never be writable from inside the sandbox.
36
+ * The Linux layer enforces this by emitting `--ro-bind <dirPath> <dirPath>`
37
+ * after every other filesystem mount (see generateFilesystemArgs), so the
38
+ * store stays read-only even if a caller's allowWrite covers os.tmpdir() or
39
+ * the host's $TMPDIR points under a default-writable path. If the sandbox
40
+ * could write here it could replace a fake's content (the bind exposes the
41
+ * source file) or plant a symlink for a later host-side write() to follow.
42
+ */
43
+ export declare class MaskedFileStore {
44
+ private dir;
45
+ private readonly byKey;
46
+ /**
47
+ * Write `sentinel` to a fake file for `key` and return its path.
48
+ * Idempotent on `key`: a repeat call rewrites the same fake (so a
49
+ * changed sentinel after re-register propagates) instead of leaking a
50
+ * new file per wrapWithSandbox() call.
51
+ */
52
+ write(key: string, sentinel: string): string;
53
+ /** Remove the temp dir and every fake file in it. Idempotent. */
54
+ dispose(): void;
55
+ /** Temp dir path, or undefined if no fake has been written yet. */
56
+ get dirPath(): string | undefined;
57
+ }
58
+ /** Result of {@link buildMaskedFileBinds}. */
59
+ export interface MaskedFileBuildResult {
60
+ binds: MaskedFileBind[];
61
+ /**
62
+ * Resolved paths of `mode: "mask"` entries that degraded to deny at
63
+ * runtime — populated when `extract` matches nothing (or, with
64
+ * `decode`, no candidate verifies) and the entry's `onExtractNoMatch`
65
+ * is `"deny"`. Callers union these into the read-deny set so the
66
+ * credential file is unreadable rather than exposed.
67
+ */
68
+ degradeToDenyPaths: string[];
69
+ }
70
+ /**
71
+ * For each `mode: "mask"` file entry: resolve the path, read the real
72
+ * content, build the fake content (whole-file or structured per `extract`),
73
+ * register sentinels in `registry`, write the fake via `store`, and return
74
+ * the bind list plus any entries that degraded to deny.
75
+ *
76
+ * Whole-file mode (no `extract`): one sentinel keyed `file:<path>` whose
77
+ * real value is the entire file content; the fake file *is* the sentinel.
78
+ *
79
+ * Structured mode (`extract` and/or `decode` set): one sentinel per
80
+ * distinct captured value, keyed `file:<path>#<i>`; the fake file is the
81
+ * real content with each captured span replaced by its sentinel. With
82
+ * `decode: "jwt"`, candidates come from the explicit `extract` pattern or
83
+ * the built-in JWT pattern, each candidate must pass {@link verifyJwt}
84
+ * before it is masked (failed candidates are left untouched), and the
85
+ * sentinel is a JWT-shaped fake ({@link mintFakeJwt}) registered via
86
+ * `registerWithSentinel`. With `maskClaims`, masking goes one level
87
+ * deeper: each named top-level payload claim present with a string value
88
+ * gets its own sentinel and the token is rebuilt around the modified
89
+ * payload ({@link maskJwtClaims}); BOTH mappings are registered — the
90
+ * whole fake token → the whole real token (a tool sending the token as a
91
+ * bearer credential) and each claim sentinel → the real claim value (a
92
+ * tool extracting the claim and sending it alone) — under the same
93
+ * injectHosts. Named claims absent or non-string in a token are skipped
94
+ * with a debug log (portable-config posture, like a missing file). If the
95
+ * regex matches nothing — or, with decode, no candidate verifies, or with
96
+ * `maskClaims`, no named claim matches in any verified token — the
97
+ * entry's `onExtractNoMatch` decides:
98
+ * - `"warn"` (default): skip the entry with a loud stderr warning —
99
+ * fail-open, the file stays readable via the root mount;
100
+ * - `"deny"`: push the path to `degradeToDenyPaths` — fail-closed, the
101
+ * file becomes unreadable inside the sandbox;
102
+ * - `"error"`: throw, so nothing runs until the config is fixed.
103
+ * With `maskDuplicates`, verbatim occurrences of each captured value
104
+ * outside the matched spans are also replaced (see {@link ExtractOptions}).
105
+ * Composed with `decode`, the duplicate pass covers only captures that
106
+ * passed verification — a duplicate is the same value, so it inherits the
107
+ * verified capture's sentinel without re-verification; unverified
108
+ * candidates (left untouched by the decode gate) never mask duplicates.
109
+ *
110
+ * Entries whose path does not exist, is unreadable, or resolves to a
111
+ * directory are skipped with a debug log — same posture as a masked env
112
+ * var that's unset on the host: nothing to protect, and surfacing a hard
113
+ * error would make a portable config brittle across machines.
114
+ *
115
+ * The directory check is the authoritative one (the schema only catches a
116
+ * trailing slash); whole-file masking has no meaning for a directory.
117
+ */
118
+ export declare function buildMaskedFileBinds(files: readonly CredentialFileConfig[], allowedDomains: readonly string[], registry: SentinelRegistry, store: MaskedFileStore): MaskedFileBuildResult;
119
+ export declare const MASKED_FILE_STORE_PREFIX = "srt-credmask-";
120
+ //# sourceMappingURL=credential-mask-files.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-mask-files.d.ts","sourceRoot":"","sources":["../../src/sandbox/credential-mask-files.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAeH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AAC/D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAA;AAShE,+DAA+D;AAC/D,MAAM,WAAW,cAAc;IAC7B,wEAAwE;IACxE,QAAQ,EAAE,MAAM,CAAA;IAChB,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED;;;;;;;;;;GAUG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,GAAG,CAAoB;IAC/B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA4B;IAElD;;;;;OAKG;IACH,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM;IAkB5C,iEAAiE;IACjE,OAAO,IAAI,IAAI;IAcf,mEAAmE;IACnE,IAAI,OAAO,IAAI,MAAM,GAAG,SAAS,CAEhC;CACF;AAED,8CAA8C;AAC9C,MAAM,WAAW,qBAAqB;IACpC,KAAK,EAAE,cAAc,EAAE,CAAA;IACvB;;;;;;OAMG;IACH,kBAAkB,EAAE,MAAM,EAAE,CAAA;CAC7B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,SAAS,oBAAoB,EAAE,EACtC,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,QAAQ,EAAE,gBAAgB,EAC1B,KAAK,EAAE,eAAe,GACrB,qBAAqB,CAiLvB;AAED,eAAO,MAAM,wBAAwB,kBAAkB,CAAA"}
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Credential file masking (Linux).
3
+ *
4
+ * For a `credentials.files` entry with `mode: "mask"`, srt reads the real
5
+ * file content on the host, registers one or more sentinels in the
6
+ * {@link SentinelRegistry}, and writes a fake file (sentinel-substituted)
7
+ * to a manager-owned temp directory. The Linux sandbox then `--ro-bind`s
8
+ * the fake over the real path, so the sandboxed process reads the
9
+ * sentinel(s). The proxy substitution from env-var masking already scans
10
+ * every header for any registered sentinel, so a tool that does
11
+ * `Authorization: Bearer $(cat <maskedFile>)` reaches the upstream with
12
+ * the real bytes — no proxy changes required.
13
+ *
14
+ * Without `extract`, masking is **whole-file**: one sentinel replaces the
15
+ * entire content. With `extract`, masking is **structured**: a regex picks
16
+ * out the credential value(s) and only those spans are replaced, so a tool
17
+ * that parses the file (JSON/YAML/.netrc) still sees valid syntax. See
18
+ * {@link extractAndSubstitute} and {@link CredentialFileConfigSchema}.
19
+ *
20
+ * On macOS, SBPL cannot redirect reads, so masked files degrade to
21
+ * `mode: "deny"` (see macos-sandbox-utils.ts).
22
+ */
23
+ import { randomUUID } from 'node:crypto';
24
+ import * as fs from 'node:fs';
25
+ import { tmpdir } from 'node:os';
26
+ import { join } from 'node:path';
27
+ import { logForDebugging } from '../utils/debug.js';
28
+ import { extractAndSubstitute } from './credential-extract.js';
29
+ import { normalizePathForSandbox } from './sandbox-utils.js';
30
+ import { JWT_DEFAULT_EXTRACT_PATTERN, maskJwtClaims, mintFakeJwt, verifyJwt, } from './credential-decode.js';
31
+ /**
32
+ * Sentinel-registry key prefix for masked files. Keeps file keys disjoint
33
+ * from env-var names so a credential file at path `GH_TOKEN` cannot collide
34
+ * with the env var `GH_TOKEN`.
35
+ */
36
+ const FILE_KEY_PREFIX = 'file:';
37
+ /**
38
+ * Manager-owned temp dir holding the fake files.
39
+ *
40
+ * INVARIANT: this directory must never be writable from inside the sandbox.
41
+ * The Linux layer enforces this by emitting `--ro-bind <dirPath> <dirPath>`
42
+ * after every other filesystem mount (see generateFilesystemArgs), so the
43
+ * store stays read-only even if a caller's allowWrite covers os.tmpdir() or
44
+ * the host's $TMPDIR points under a default-writable path. If the sandbox
45
+ * could write here it could replace a fake's content (the bind exposes the
46
+ * source file) or plant a symlink for a later host-side write() to follow.
47
+ */
48
+ export class MaskedFileStore {
49
+ constructor() {
50
+ this.byKey = new Map();
51
+ }
52
+ /**
53
+ * Write `sentinel` to a fake file for `key` and return its path.
54
+ * Idempotent on `key`: a repeat call rewrites the same fake (so a
55
+ * changed sentinel after re-register propagates) instead of leaking a
56
+ * new file per wrapWithSandbox() call.
57
+ */
58
+ write(key, sentinel) {
59
+ if (this.dir === undefined) {
60
+ this.dir = fs.mkdtempSync(join(tmpdir(), MASKED_FILE_STORE_PREFIX));
61
+ }
62
+ let fakePath = this.byKey.get(key);
63
+ if (fakePath === undefined) {
64
+ fakePath = join(this.dir, `${this.byKey.size}.fake`);
65
+ this.byKey.set(key, fakePath);
66
+ }
67
+ // Atomic temp-write + rename so concurrent wrapWithSandbox() calls never
68
+ // observe ENOENT while another bwrap process opens fakePath, and symlinks
69
+ // are replaced without being followed.
70
+ const tmpPath = `${fakePath}.${randomUUID()}.tmp`;
71
+ fs.writeFileSync(tmpPath, sentinel, { mode: 0o600 });
72
+ fs.renameSync(tmpPath, fakePath);
73
+ return fakePath;
74
+ }
75
+ /** Remove the temp dir and every fake file in it. Idempotent. */
76
+ dispose() {
77
+ if (this.dir !== undefined) {
78
+ try {
79
+ fs.rmSync(this.dir, { recursive: true, force: true });
80
+ }
81
+ catch (err) {
82
+ logForDebugging(`MaskedFileStore cleanup failed: ${err}`, {
83
+ level: 'error',
84
+ });
85
+ }
86
+ }
87
+ this.dir = undefined;
88
+ this.byKey.clear();
89
+ }
90
+ /** Temp dir path, or undefined if no fake has been written yet. */
91
+ get dirPath() {
92
+ return this.dir;
93
+ }
94
+ }
95
+ /**
96
+ * For each `mode: "mask"` file entry: resolve the path, read the real
97
+ * content, build the fake content (whole-file or structured per `extract`),
98
+ * register sentinels in `registry`, write the fake via `store`, and return
99
+ * the bind list plus any entries that degraded to deny.
100
+ *
101
+ * Whole-file mode (no `extract`): one sentinel keyed `file:<path>` whose
102
+ * real value is the entire file content; the fake file *is* the sentinel.
103
+ *
104
+ * Structured mode (`extract` and/or `decode` set): one sentinel per
105
+ * distinct captured value, keyed `file:<path>#<i>`; the fake file is the
106
+ * real content with each captured span replaced by its sentinel. With
107
+ * `decode: "jwt"`, candidates come from the explicit `extract` pattern or
108
+ * the built-in JWT pattern, each candidate must pass {@link verifyJwt}
109
+ * before it is masked (failed candidates are left untouched), and the
110
+ * sentinel is a JWT-shaped fake ({@link mintFakeJwt}) registered via
111
+ * `registerWithSentinel`. With `maskClaims`, masking goes one level
112
+ * deeper: each named top-level payload claim present with a string value
113
+ * gets its own sentinel and the token is rebuilt around the modified
114
+ * payload ({@link maskJwtClaims}); BOTH mappings are registered — the
115
+ * whole fake token → the whole real token (a tool sending the token as a
116
+ * bearer credential) and each claim sentinel → the real claim value (a
117
+ * tool extracting the claim and sending it alone) — under the same
118
+ * injectHosts. Named claims absent or non-string in a token are skipped
119
+ * with a debug log (portable-config posture, like a missing file). If the
120
+ * regex matches nothing — or, with decode, no candidate verifies, or with
121
+ * `maskClaims`, no named claim matches in any verified token — the
122
+ * entry's `onExtractNoMatch` decides:
123
+ * - `"warn"` (default): skip the entry with a loud stderr warning —
124
+ * fail-open, the file stays readable via the root mount;
125
+ * - `"deny"`: push the path to `degradeToDenyPaths` — fail-closed, the
126
+ * file becomes unreadable inside the sandbox;
127
+ * - `"error"`: throw, so nothing runs until the config is fixed.
128
+ * With `maskDuplicates`, verbatim occurrences of each captured value
129
+ * outside the matched spans are also replaced (see {@link ExtractOptions}).
130
+ * Composed with `decode`, the duplicate pass covers only captures that
131
+ * passed verification — a duplicate is the same value, so it inherits the
132
+ * verified capture's sentinel without re-verification; unverified
133
+ * candidates (left untouched by the decode gate) never mask duplicates.
134
+ *
135
+ * Entries whose path does not exist, is unreadable, or resolves to a
136
+ * directory are skipped with a debug log — same posture as a masked env
137
+ * var that's unset on the host: nothing to protect, and surfacing a hard
138
+ * error would make a portable config brittle across machines.
139
+ *
140
+ * The directory check is the authoritative one (the schema only catches a
141
+ * trailing slash); whole-file masking has no meaning for a directory.
142
+ */
143
+ export function buildMaskedFileBinds(files, allowedDomains, registry, store) {
144
+ const binds = [];
145
+ const degradeToDenyPaths = [];
146
+ for (const f of files) {
147
+ if (f.mode !== 'mask')
148
+ continue;
149
+ const realPath = normalizePathForSandbox(f.path);
150
+ let content;
151
+ try {
152
+ const stat = fs.statSync(realPath);
153
+ if (!stat.isFile()) {
154
+ logForDebugging(`[credential-mask] Skipping masked file entry that is not a regular file: ${f.path} — use mode "deny" for directories or special files.`, { level: 'warn' });
155
+ continue;
156
+ }
157
+ // Read as bytes first: a utf8 read silently maps invalid sequences
158
+ // to U+FFFD, so the sentinel would round-trip to corrupted bytes at
159
+ // the proxy. Compare round-tripped bytes so equal-length corruptions
160
+ // (e.g. 3 invalid bytes -> 3-byte U+FFFD) are caught too.
161
+ const raw = fs.readFileSync(realPath);
162
+ content = raw.toString('utf8');
163
+ if (!raw.equals(Buffer.from(content, 'utf8'))) {
164
+ logForDebugging(`[credential-mask] Skipping masked file with non-UTF-8 content ` +
165
+ `(binary credential files are not supported in mask mode): ` +
166
+ `${f.path}`, { level: 'warn' });
167
+ continue;
168
+ }
169
+ }
170
+ catch (err) {
171
+ logForDebugging(`[credential-mask] Skipping masked file (unreadable on host): ` +
172
+ `${f.path} — ${err.message}`);
173
+ continue;
174
+ }
175
+ const injectHosts = f.injectHosts ?? allowedDomains;
176
+ const key = FILE_KEY_PREFIX + realPath;
177
+ let fakeContent;
178
+ if (f.extract === undefined && f.decode === undefined) {
179
+ // Whole-file: keep trailing line endings outside the sentinel so tools
180
+ // doing `$(cat file)` or HTTP header injection do not embed \r/\n into
181
+ // outgoing HTTP header values.
182
+ const trailingMatch = content.match(/(\r?\n)+$/);
183
+ const trailing = trailingMatch ? trailingMatch[0] : '';
184
+ const body = trailing ? content.slice(0, -trailing.length) : content;
185
+ if (body.length > 0) {
186
+ fakeContent = registry.register(key, body, injectHosts) + trailing;
187
+ }
188
+ else {
189
+ fakeContent = registry.register(key, content, injectHosts);
190
+ }
191
+ }
192
+ else {
193
+ // An explicit extract pattern wins; decode without one falls back to
194
+ // the built-in JWT pattern so authors don't hand-write it.
195
+ const pattern = f.extract ?? JWT_DEFAULT_EXTRACT_PATTERN;
196
+ let maskedCount = 0;
197
+ const extracted = extractAndSubstitute(content, pattern, (cap, i) => {
198
+ // Decode-verification: a regex match that is not actually a JWT
199
+ // (the default pattern over-matches by design) is left untouched —
200
+ // returning the capture replaces the span with itself.
201
+ if (f.decode === 'jwt' && !verifyJwt(cap))
202
+ return cap;
203
+ const name = `${key}#${i}`;
204
+ if (f.decode === 'jwt' && f.maskClaims?.length) {
205
+ // Claim-level masking: sentinels go INSIDE the payload; the
206
+ // rebuilt fake token is itself registered as a sentinel for
207
+ // the whole real token, so both the bearer path (token sent
208
+ // verbatim) and the extracted-claim path substitute on egress.
209
+ const masked = maskJwtClaims(cap, f.maskClaims, (claim, real) => registry.register(`${key}#jwt${i}.${claim}`, real, injectHosts));
210
+ if (masked === null) {
211
+ // A verified JWT none of whose named claims are present as
212
+ // strings: nothing to mask in THIS token — leave it as-is;
213
+ // if no token matches any claim, onExtractNoMatch applies.
214
+ logForDebugging(`[credential-mask] ${f.path}: verified JWT candidate has ` +
215
+ `none of maskClaims ${JSON.stringify(f.maskClaims)} as ` +
216
+ `string claims — left unmasked.`);
217
+ return cap;
218
+ }
219
+ const skipped = f.maskClaims.filter(c => !masked.claimSentinels.has(c));
220
+ if (skipped.length > 0) {
221
+ logForDebugging(`[credential-mask] ${f.path}: maskClaims ` +
222
+ `${JSON.stringify(skipped)} absent or non-string in a ` +
223
+ `verified JWT — skipped.`);
224
+ }
225
+ maskedCount++;
226
+ return registry.registerWithSentinel(name, masked.fakeToken, cap, injectHosts);
227
+ }
228
+ maskedCount++;
229
+ // For decode the fake must keep the token's shape: a JWT-shaped
230
+ // sentinel keeps client-side parsers (segment count, payload
231
+ // decode, exp checks) working inside the sandbox.
232
+ return f.decode === 'jwt'
233
+ ? registry.registerWithSentinel(name, mintFakeJwt(randomUUID()), cap, injectHosts)
234
+ : registry.register(name, cap, injectHosts);
235
+ }, { maskDuplicates: f.maskDuplicates ?? false });
236
+ if (extracted === null || maskedCount === 0) {
237
+ // Nothing was masked — either the pattern matched nothing or, with
238
+ // decode, no candidate survived verification. Both are the same
239
+ // "masking cannot apply" condition, so both route through the
240
+ // entry's onExtractNoMatch policy.
241
+ const cause = f.decode === 'jwt'
242
+ ? f.maskClaims?.length
243
+ ? `decode "jwt" with pattern "${pattern}" that matched no ` +
244
+ `verified JWT with maskable claims (maskClaims: ` +
245
+ `${JSON.stringify(f.maskClaims)})`
246
+ : `decode "jwt" with pattern "${pattern}" that matched no ` +
247
+ `verified JWT`
248
+ : `extract pattern "${pattern}" that matched nothing`;
249
+ const onNoMatch = f.onExtractNoMatch ?? 'warn';
250
+ if (onNoMatch === 'error') {
251
+ throw new Error(`credentials.files entry "${f.path}": ${cause} ` +
252
+ `(onExtractNoMatch: "error"). Fix the config, change to ` +
253
+ `"warn"/"deny", or remove the entry.`);
254
+ }
255
+ if (onNoMatch === 'deny') {
256
+ // Fail-closed: the operator declared this file as containing a
257
+ // credential. Masking can't apply — degrade to deny so the
258
+ // sandboxed process cannot read the credential at all.
259
+ logForDebugging(`[credential-mask] ${f.path} has ${cause} — degrading to ` +
260
+ `mode "deny".`, { level: 'warn' });
261
+ degradeToDenyPaths.push(realPath);
262
+ continue;
263
+ }
264
+ // 'warn' (default): fail-open. A non-matching config is an error
265
+ // to surface, not a reason to block file access. Skip the entry
266
+ // (no bind, no deny) — the file stays readable via the root mount
267
+ // — and warn loudly on stderr so the operator fixes the config.
268
+ const msg = `[sandbox-runtime] WARNING: credentials.files entry ` +
269
+ `"${f.path}" has ${cause} in the file. The file is left ` +
270
+ `UNPROTECTED (readable as-is inside the sandbox). Fix the ` +
271
+ `config, set onExtractNoMatch to "deny" or "error", or remove ` +
272
+ `the entry.`;
273
+ console.warn(msg);
274
+ logForDebugging(msg, { level: 'warn' });
275
+ continue;
276
+ }
277
+ fakeContent = extracted.fakeContent;
278
+ }
279
+ const fakePath = store.write(key, fakeContent);
280
+ binds.push({ realPath, fakePath });
281
+ }
282
+ return { binds, degradeToDenyPaths };
283
+ }
284
+ export const MASKED_FILE_STORE_PREFIX = 'srt-credmask-';
285
+ //# sourceMappingURL=credential-mask-files.js.map
@@ -0,0 +1 @@
1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,MAAM,GAAG,GACP,qDAAqD;oBACrD,IAAI,CAAC,CAAC,IAAI,SAAS,KAAK,iCAAiC;oBACzD,2DAA2D;oBAC3D,+DAA+D;oBAC/D,YAAY,CAAA;gBACd,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBACjB,eAAe,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAA;gBACvC,SAAQ;YACV,CAAC;YACD,WAAW,GAAG,SAAS,CAAC,WAAW,CAAA;QACrC,CAAC;QAED,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE,WAAW,CAAC,CAAA;QAC9C,KAAK,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAA;IACpC,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,CAAA;AACtC,CAAC;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG,eAAe,CAAA"}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Per-session sentinel registry for credential masking.
3
+ *
4
+ * A masked credential's real value is replaced inside the sandbox with a
5
+ * sentinel of the form `fake_value_<uuid4>`. The sandboxed process sees only
6
+ * the sentinel; the host-side proxy substitutes sentinel→real on egress to
7
+ * allowlisted destinations. The map lives only in process memory — it is
8
+ * never written to disk and never logged.
9
+ */
10
+ import type { IncomingHttpHeaders } from 'node:http';
11
+ export declare const SENTINEL_PREFIX = "fake_value_";
12
+ /** Predicate matching a destination host against one injectHosts pattern. */
13
+ export type HostMatcher = (host: string, pattern: string) => boolean;
14
+ /**
15
+ * Sentinel↔real-value map for one sandbox session, keyed by credential name.
16
+ *
17
+ * Each credential carries its own `injectHosts` list, and substitution is
18
+ * gated per sentinel: a sentinel is swapped to its real value only when the
19
+ * destination matches THAT credential's hosts. This prevents laundering
20
+ * credential A through credential B's allowlisted host by sending A's
21
+ * sentinel there — the proxy leaves A's sentinel intact on B's host.
22
+ *
23
+ * Keying on name (not value) means two env vars holding the same secret get
24
+ * distinct sentinels, so each can have an independent host list.
25
+ */
26
+ export declare class SentinelRegistry {
27
+ private readonly byName;
28
+ private readonly bySentinel;
29
+ private allSentinelsPrefixed;
30
+ /**
31
+ * Return the sentinel for the credential named `name`, minting a fresh one
32
+ * on first use. The sentinel is `fake_value_<uuid4>`: long enough that an
33
+ * accidental collision with legitimate header content is negligible, and
34
+ * free of shell/URL metacharacters so it survives `--setenv` and
35
+ * `env NAME=value` unquoted.
36
+ *
37
+ * Idempotent on `name`: a repeat call returns the same sentinel and updates
38
+ * `realValue`/`injectHosts` in place so `updateConfig()` can change either
39
+ * without invalidating sentinels the sandboxed process has already read.
40
+ */
41
+ register(name: string, realValue: string, injectHosts: readonly string[]): string;
42
+ /**
43
+ * Like {@link register}, but with a caller-minted sentinel instead of the
44
+ * default `fake_value_<uuid4>` — used when the fake must keep the real
45
+ * value's shape (e.g. a structurally valid JWT for `decode: "jwt"`), so
46
+ * client-side parsers inside the sandbox don't choke on it.
47
+ *
48
+ * Same idempotency contract as {@link register}: if `name` is already
49
+ * registered, the EXISTING sentinel is returned (and `sentinel` discarded)
50
+ * so a re-register never invalidates a fake the sandboxed process has
51
+ * already read. The caller must mint sentinels with enough entropy that
52
+ * collisions with real content are negligible (embed a uuid4).
53
+ */
54
+ registerWithSentinel(name: string, sentinel: string, realValue: string, injectHosts: readonly string[]): string;
55
+ /** Real value for `sentinel`, or undefined if not registered. */
56
+ lookupReal(sentinel: string): string | undefined;
57
+ /**
58
+ * Names of the registered credentials whose `injectHosts` cover
59
+ * `destHost`. Diagnostic helper: the proxy uses it to warn when a host is
60
+ * exempted from TLS termination (so substitution can never run there) but
61
+ * a masked credential is configured for injection at it.
62
+ */
63
+ namesInjectableAt(destHost: string, matches: HostMatcher): string[];
64
+ /** Iterate registered `[sentinel, realValue]` pairs. */
65
+ entries(): IterableIterator<[string, string]>;
66
+ /** Number of registered sentinels. */
67
+ get size(): number;
68
+ /** Drop entries whose credential name does not satisfy `keep`. */
69
+ prune(keep: (name: string) => boolean): void;
70
+ /** Drop every mapping. Called on session teardown. */
71
+ clear(): void;
72
+ /**
73
+ * Replace registered sentinels found in `headers` with their real values,
74
+ * in place. Each sentinel substitutes only when `destHost` matches one of
75
+ * THAT credential's `injectHosts` patterns (via `matches`); a sentinel
76
+ * whose host list does not cover `destHost` is left as the useless fake.
77
+ *
78
+ * Scans all header values rather than a fixed set — a sentinel showing up
79
+ * anywhere is the substitution trigger, regardless of header name
80
+ * (Authorization, X-Api-Key, Private-Token, ...).
81
+ *
82
+ * The caller remains responsible for transport gating (TLS-terminated path
83
+ * unless `allowPlaintextInject`).
84
+ */
85
+ substituteInHeaders(headers: IncomingHttpHeaders, destHost: string, matches: HostMatcher): void;
86
+ private substituteInString;
87
+ }
88
+ //# sourceMappingURL=credential-sentinel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-sentinel.d.ts","sourceRoot":"","sources":["../../src/sandbox/credential-sentinel.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAA;AAEpD,eAAO,MAAM,eAAe,gBAAgB,CAAA;AAE5C,6EAA6E;AAC7E,MAAM,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAA;AASpE;;;;;;;;;;;GAWG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmC;IAC1D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmC;IAI9D,OAAO,CAAC,oBAAoB,CAAO;IAEnC;;;;;;;;;;OAUG;IACH,QAAQ,CACN,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,SAAS,MAAM,EAAE,GAC7B,MAAM;IAST;;;;;;;;;;;OAWG;IACH,oBAAoB,CAClB,IAAI,EAAE,MAAM,EACZ,QAAQ,E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