harness-everything 1.2.2 → 1.3.1

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 (147) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +29 -0
  4. package/ci/archive/325-prep/README.md +9 -2
  5. package/ci/archive/325-prep/doc-reconciliation-red.js +34 -8
  6. package/ci/fixtures/468-dispatch/agy-quota-PROVENANCE.md +19 -0
  7. package/ci/fixtures/468-dispatch/agy-quota-direct-individual.stderr +2 -0
  8. package/ci/fixtures/468-dispatch/agy-quota-direct-third-party.stderr +2 -0
  9. package/ci/fixtures/468-dispatch/agy-quota-exec-individual.log +3 -0
  10. package/ci/fixtures/553-t2a/body-edit/base/.agents/harness-everything/project-docs.json +11 -0
  11. package/ci/fixtures/553-t2a/body-edit/base/docs/a.md +6 -0
  12. package/ci/fixtures/553-t2a/body-edit/base/docs/b.md +1 -0
  13. package/ci/fixtures/553-t2a/body-edit/candidate/docs/a.md +6 -0
  14. package/ci/fixtures/553-t2c/derived-regenerate-must/base/docs/adr/EVID-001-verify-all-evidence.md +11 -0
  15. package/ci/fixtures/553-t2c/derived-regenerate-must/base/docs/governed-index.md +19 -0
  16. package/ci/fixtures/553-t2c/derived-regenerate-must/candidate/docs/adr/EVID-001-verify-all-evidence.md +11 -0
  17. package/ci/fixtures/553-t2c/derived-regenerate-must/candidate/docs/governed-index.md +19 -0
  18. package/ci/fixtures/553-t2c/derived-regenerate-must/config.json +17 -0
  19. package/ci/fixtures/doc-obligations/derive/regression-pins.json +153 -0
  20. package/ci/fixtures/state-persist-post-tool-use/harness.js +206 -0
  21. package/ci/fixtures/state-persist-post-tool-use/off-handoff-golden.json +16 -0
  22. package/ci/fixtures/state-persist-post-tool-use/payload-post-tool-use-success.json +13 -0
  23. package/ci/fixtures/stop/fail-session-writes.js +109 -0
  24. package/ci/fixtures/workflow-contract/cases.json +3355 -0
  25. package/ci/fixtures/workflow-contract/wiring-cases.json +560 -0
  26. package/ci/lib/doc-reconciliation-prep-fixtures.js +4 -9
  27. package/ci/mechanism-2an-workflow-replay.test.js +324 -0
  28. package/ci/mechanism-2ax-doc-lifecycle.test.js +132 -0
  29. package/ci/mechanism-325-3a-doc-evidence.test.js +73 -0
  30. package/ci/mechanism-325-3a-doc-obligations.test.js +61 -0
  31. package/ci/mechanism-325-3b-preparation.test.js +208 -49
  32. package/ci/mechanism-325-3b-s1-review.test.js +20 -828
  33. package/ci/mechanism-325-3b-s3-providers.test.js +59 -0
  34. package/ci/mechanism-325-f3-derived-views.test.js +140 -0
  35. package/ci/mechanism-341-opencode-lane.test.js +164 -284
  36. package/ci/mechanism-35-verification-contract.test.js +246 -0
  37. package/ci/mechanism-365-step-edit-accounting.test.js +5 -6
  38. package/ci/mechanism-383-doc-glob-line-terminators.test.js +0 -30
  39. package/ci/mechanism-397-opencode-observations.test.js +151 -18
  40. package/ci/mechanism-468-dispatch-cli.test.js +1496 -4
  41. package/ci/mechanism-548-bigint-identity.test.js +531 -0
  42. package/ci/mechanism-553-e1-unhook-credit.test.js +328 -0
  43. package/ci/mechanism-553-p2a-claude-hooks.test.js +98 -0
  44. package/ci/mechanism-553-p3-plan-start.test.js +212 -0
  45. package/ci/mechanism-553-state-persist-post-tool-use.test.js +307 -0
  46. package/ci/mechanism-553-stop.test.js +427 -0
  47. package/ci/mechanism-553-t2a-derive.test.js +110 -0
  48. package/ci/mechanism-553-t2c-derive.test.js +94 -0
  49. package/ci/mechanism-e1-derived-regenerate.test.js +45 -206
  50. package/ci/mechanism-error-ledger-oracle.test.js +786 -3
  51. package/ci/mechanism-error-ledger-scan.test.js +981 -0
  52. package/ci/mechanism-outline-sanitizer.test.js +0 -8
  53. package/ci/mechanism-pr-a-conflict-check.test.js +38 -305
  54. package/ci/mechanism-prb-outline-review.test.js +101 -3283
  55. package/ci/mechanism-report-writer.test.js +45 -0
  56. package/docs/adr/DOCS-006-reconciliation-pilot.md +4 -2
  57. package/docs/adr/DOCS-008-obligation-abstraction-bounded-consumer.md +3 -3
  58. package/docs/doc-workflow-reconciliation.md +17 -2
  59. package/docs/document-lifecycle.md +6 -2
  60. package/docs/error-handling/details/c8-dispatch-cli.md +109 -13
  61. package/docs/platform-capabilities.md +35 -5
  62. package/error-ledger-bootstrap/SKILL.md +1 -1
  63. package/error-ledger-bootstrap/references/workflow.md +42 -7
  64. package/error-ledger-bootstrap/scripts/promote.js +8 -6
  65. package/error-ledger-bootstrap/scripts/scan.js +525 -12
  66. package/hooks/hooks.json +0 -46
  67. package/hooks/scripts/lib/workflow-obligations.js +0 -55
  68. package/hooks/scripts/state-persist.js +7 -95
  69. package/hooks/scripts/workflow-disposition.js +0 -2
  70. package/hooks/scripts/workflow-stop-gate.js +17 -30
  71. package/opencode-plugin/index.mjs +6 -70
  72. package/opencode-plugin/plugin.json +1 -1
  73. package/package.json +1 -1
  74. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  75. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  76. package/plugins/harness-everything/hooks/scripts/lib/workflow-obligations.js +0 -55
  77. package/plugins/harness-everything/hooks/scripts/state-persist.js +7 -95
  78. package/plugins/harness-everything/hooks/scripts/workflow-disposition.js +0 -2
  79. package/plugins/harness-everything/hooks/scripts/workflow-stop-gate.js +17 -30
  80. package/plugins/harness-everything/plugin.json +1 -1
  81. package/plugins/harness-everything/skills/error-ledger-bootstrap/SKILL.md +1 -1
  82. package/plugins/harness-everything/skills/error-ledger-bootstrap/references/workflow.md +42 -7
  83. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/promote.js +8 -6
  84. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/scan.js +525 -12
  85. package/sbom.cdx.json +7 -7
  86. package/scripts/dispatch.js +499 -87
  87. package/scripts/error-ledger-oracle.js +521 -27
  88. package/scripts/errors-sync.js +4 -3
  89. package/scripts/report-writer.js +4 -3
  90. package/ci/fixtures/doc-obligations/reconciliation-s1/cases.json +0 -6854
  91. package/ci/fixtures/doc-obligations/reconciliation-s1/fail-session-writes.js +0 -116
  92. package/ci/fixtures/doc-obligations/reconciliation-s2a/harness.js +0 -507
  93. package/ci/fixtures/doc-obligations/reconciliation-s2a/run13-workflow-requirements.json +0 -42
  94. package/ci/fixtures/doc-obligations/reconciliation-s2a/vectors.json +0 -617
  95. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/harness.js +0 -415
  96. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-post-tool-use-success-minimal.json +0 -9
  97. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-start.json +0 -7
  98. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop-freetext-reject.json +0 -11
  99. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop-reject.json +0 -11
  100. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop.json +0 -11
  101. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-task-result.json +0 -19
  102. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/off-capture-only.json +0 -99
  103. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/off-legacy.json +0 -67
  104. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-concurrent-writers.json +0 -62
  105. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-lookalikes-runtime-mutations.json +0 -67
  106. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-malformed.json +0 -85
  107. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-normal-session.json +0 -74
  108. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-runtime-drift-later-npm-test.json +0 -58
  109. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-valid-direct-quoted-review.json +0 -85
  110. package/ci/fixtures/doc-obligations/reconciliation-s2b/f4/cases.json +0 -2267
  111. package/ci/fixtures/doc-obligations/reconciliation-s2b/wiring/cases.json +0 -1110
  112. package/ci/lib/doc-reconciliation-file-spy.js +0 -23
  113. package/ci/lib/doc-reconciliation-qualification-preload.js +0 -37
  114. package/ci/lib/doc-reconciliation-replay.js +0 -104
  115. package/ci/lib/doc-reconciliation-staged-tree.js +0 -102
  116. package/ci/mechanism-325-3b-h1-qualification.test.js +0 -206
  117. package/ci/mechanism-325-3b-s1.test.js +0 -188
  118. package/ci/mechanism-325-3b-s2a-core.test.js +0 -840
  119. package/ci/mechanism-325-3b-s2a-producer.test.js +0 -564
  120. package/ci/mechanism-325-3b-s2b-capture.test.js +0 -566
  121. package/ci/mechanism-325-3b-s2b-wiring.test.js +0 -679
  122. package/ci/mechanism-325-f4-invariants.test.js +0 -606
  123. package/ci/mechanism-325-f4-projections.test.js +0 -392
  124. package/ci/mechanism-325-f4-qualification.test.js +0 -228
  125. package/ci/mechanism-325-f4-trust-boundary.test.js +0 -880
  126. package/ci/mechanism-e1-dependency-artifact-scope.test.js +0 -657
  127. package/hooks/scripts/lib/doc-reconciliation-capture.sanitized.jsonl +0 -26
  128. package/hooks/scripts/lib/doc-reconciliation-core.js +0 -336
  129. package/hooks/scripts/lib/doc-reconciliation-events.js +0 -292
  130. package/hooks/scripts/lib/doc-reconciliation-outline-capture.sanitized.jsonl +0 -24
  131. package/hooks/scripts/lib/doc-reconciliation-pilot.js +0 -482
  132. package/hooks/scripts/lib/doc-reconciliation-producer.js +0 -468
  133. package/hooks/scripts/lib/doc-reconciliation-provider.js +0 -3304
  134. package/hooks/scripts/lib/doc-reconciliation-qualification.json +0 -54
  135. package/hooks/scripts/w6-state-operations.js +0 -239
  136. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-capture.sanitized.jsonl +0 -26
  137. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-core.js +0 -336
  138. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-events.js +0 -292
  139. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-outline-capture.sanitized.jsonl +0 -24
  140. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-pilot.js +0 -482
  141. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-producer.js +0 -468
  142. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-provider.js +0 -3304
  143. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-qualification.json +0 -54
  144. package/plugins/harness-everything/hooks/scripts/w6-state-operations.js +0 -239
  145. package/scripts/system-one-eval-laya.js +0 -112
  146. /package/ci/fixtures/{doc-obligations/reconciliation-s2b/capture → state-persist-post-tool-use}/payload-post-tool-use-failure.json +0 -0
  147. /package/ci/fixtures/{doc-obligations/reconciliation-s2b/wiring → workflow-contract}/legacy-off-golden.json +0 -0
@@ -0,0 +1,206 @@
1
+ 'use strict';
2
+
3
+ // Test-only harness for the general state-persist PostToolUse compatibility
4
+ // controls. Copies the capture fixture's two-leg loader/driver contract so the
5
+ // moved controls keep the same input, same assertion and both real hook legs
6
+ // (canonical hooks/scripts + packaged plugins/harness-everything copy).
7
+ // No runtime module is required at load time; R2 may retire the E1 modules
8
+ // without affecting these controls.
9
+
10
+ const fs = require('fs');
11
+ const os = require('os');
12
+ const path = require('path');
13
+ const { spawnSync } = require('child_process');
14
+
15
+ const HERE = __dirname;
16
+ const ROOT = path.resolve(HERE, '..', '..', '..');
17
+
18
+ const LEGS = [
19
+ {
20
+ name: 'source',
21
+ hooksScripts: path.join(ROOT, 'hooks', 'scripts'),
22
+ hooksManifest: path.join(ROOT, 'hooks', 'hooks.json'),
23
+ lib: path.join(ROOT, 'hooks', 'scripts', 'lib'),
24
+ },
25
+ {
26
+ name: 'packaged',
27
+ hooksScripts: path.join(ROOT, 'plugins', 'harness-everything', 'hooks', 'scripts'),
28
+ hooksManifest: path.join(ROOT, 'plugins', 'harness-everything', 'hooks', 'hooks.json'),
29
+ lib: path.join(ROOT, 'plugins', 'harness-everything', 'hooks', 'scripts', 'lib'),
30
+ },
31
+ ];
32
+
33
+ class InfraError extends Error {}
34
+
35
+ const CAPTURE_EVENT_NAMES = ['PostToolUse', 'PostToolUseFailure', 'SubagentStart', 'SubagentStop'];
36
+ const CAPTURE_BASE_REQUIRED = ['event', 'command', 'cwd', 'tool_use_id', 'session_id', 'responseDigest', 'responseRef'];
37
+
38
+ function payload(name) {
39
+ return JSON.parse(fs.readFileSync(path.join(HERE, name), 'utf8'));
40
+ }
41
+
42
+ function golden() {
43
+ return JSON.parse(fs.readFileSync(path.join(HERE, 'off-handoff-golden.json'), 'utf8'));
44
+ }
45
+
46
+ const moduleCache = new Map();
47
+ function loadModule(leg, file) {
48
+ const key = `${leg.name}:${file}`;
49
+ if (moduleCache.has(key)) return moduleCache.get(key);
50
+ const abs = path.join(leg.lib, file);
51
+ const rel = path.relative(ROOT, abs);
52
+ let result;
53
+ if (!fs.existsSync(abs)) {
54
+ result = { error: `module-missing: ${rel} does not exist` };
55
+ } else {
56
+ try {
57
+ result = { mod: require(abs) };
58
+ } catch (error) {
59
+ result = { error: `load-error: ${rel}: ${String(error && error.message).split('\n')[0]}` };
60
+ }
61
+ }
62
+ moduleCache.set(key, result);
63
+ return result;
64
+ }
65
+
66
+ function requirementsMet(leg, requirements) {
67
+ const mods = {};
68
+ for (const req of requirements || []) {
69
+ const loaded = loadModule(leg, req.file);
70
+ if (loaded.error) return { error: loaded.error };
71
+ for (const name of req.exports || []) {
72
+ if (typeof loaded.mod[name] !== 'function') {
73
+ return { error: `export-missing: ${req.file} does not export ${name}` };
74
+ }
75
+ }
76
+ mods[req.file] = loaded.mod;
77
+ }
78
+ return { mods };
79
+ }
80
+
81
+ function createRunner(label) {
82
+ const rows = [];
83
+ const counts = { PASS: 0, FAIL: 0, INFRA: 0 };
84
+ function emit(status, id, leg, detail) {
85
+ counts[status] += 1;
86
+ rows.push({ status, id, leg, detail: detail || '' });
87
+ console.log(` ${status} ${id}${leg ? ` [${leg}]` : ''}${detail ? ` — ${detail}` : ''}`);
88
+ }
89
+ function run(id, requirements, fn) {
90
+ for (const leg of LEGS) {
91
+ const met = requirementsMet(leg, requirements);
92
+ if (met.error) { emit('FAIL', id, leg.name, met.error); continue; }
93
+ try {
94
+ fn(met.mods, leg);
95
+ emit('PASS', id, leg.name);
96
+ } catch (error) {
97
+ if (error instanceof InfraError) emit('INFRA', id, leg.name, String(error && error.message).split('\n')[0]);
98
+ else emit('FAIL', id, leg.name, String(error && error.message).split('\n')[0]);
99
+ }
100
+ }
101
+ }
102
+ function summary() {
103
+ console.log(`\n${label} summary: ${counts.PASS} PASS, ${counts.FAIL} FAIL, ${counts.INFRA} INFRA across ${rows.length} assertion-legs`);
104
+ return counts;
105
+ }
106
+ return { run, summary, counts, rows, emit };
107
+ }
108
+
109
+ function sessionDirectoryNameSafe(sessionId) {
110
+ return String(sessionId || 'default').replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\.+/, '');
111
+ }
112
+
113
+ function snapshotSessionTree(stateHome, sessionId) {
114
+ const dirName = sessionDirectoryNameSafe(sessionId);
115
+ const hits = [];
116
+ (function walk(dir) {
117
+ if (!fs.existsSync(dir)) return;
118
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
119
+ const abs = path.join(dir, entry.name);
120
+ if (entry.isDirectory()) walk(abs);
121
+ else if (abs.split(path.sep).includes(dirName)) hits.push(abs);
122
+ }
123
+ })(stateHome);
124
+ const files = {};
125
+ for (const abs of hits) files[path.relative(stateHome, abs).replace(/\\/g, '/')] = fs.readFileSync(abs, 'utf8');
126
+ return files;
127
+ }
128
+
129
+ function driveStatePersist(leg, baseName, overrides = {}, options = {}) {
130
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'state-persist-post-'));
131
+ const wsRoot = path.join(home, 'ws');
132
+ fs.mkdirSync(wsRoot, { recursive: true });
133
+ const stateHome = path.join(home, 'state-home');
134
+ fs.mkdirSync(stateHome, { recursive: true });
135
+ const driven = JSON.parse(JSON.stringify(payload(baseName)));
136
+ for (const [k, v] of Object.entries(overrides)) {
137
+ if (v === undefined) delete driven[k];
138
+ else driven[k] = v;
139
+ }
140
+ driven.cwd = wsRoot;
141
+ const env = {
142
+ ...process.env,
143
+ CLAUDE: '1',
144
+ HARNESS_STATE_HOME: stateHome,
145
+ HARNESS_WORKSPACE_ROOT: wsRoot,
146
+ ...(options.env || {}),
147
+ };
148
+ let result;
149
+ try {
150
+ result = spawnSync('node', [path.join(leg.hooksScripts, 'state-persist.js')], {
151
+ input: JSON.stringify(driven),
152
+ encoding: 'utf8',
153
+ env,
154
+ timeout: 30000,
155
+ });
156
+ } catch (error) {
157
+ throw new InfraError(`state-persist subprocess could not be started: ${error.message}`);
158
+ }
159
+ if (result.error) throw new InfraError(`state-persist subprocess error: ${String(result.error.message || result.error)}`);
160
+ const out = {
161
+ code: result.status,
162
+ stdout: result.stdout || '',
163
+ stderr: result.stderr || '',
164
+ files: snapshotSessionTree(stateHome, driven.session_id),
165
+ filesRoot: stateHome,
166
+ wsRoot,
167
+ payload: driven,
168
+ };
169
+ try { fs.rmSync(home, { recursive: true, force: true }); } catch { /* best effort */ }
170
+ return out;
171
+ }
172
+
173
+ function deepScan(value, visit) {
174
+ if (value && typeof value === 'object') {
175
+ visit(value);
176
+ if (Array.isArray(value)) for (const item of value) deepScan(item, visit);
177
+ else for (const key of Object.keys(value)) deepScan(value[key], visit);
178
+ }
179
+ }
180
+
181
+ function findCaptureRecords(files) {
182
+ const found = [];
183
+ for (const content of Object.values(files)) {
184
+ let parsed;
185
+ try { parsed = JSON.parse(content); } catch { continue; }
186
+ deepScan(parsed, node => {
187
+ if (node && CAPTURE_EVENT_NAMES.includes(node.event)
188
+ && CAPTURE_BASE_REQUIRED.every(k => Object.prototype.hasOwnProperty.call(node, k))) {
189
+ found.push(node);
190
+ }
191
+ });
192
+ }
193
+ return found;
194
+ }
195
+
196
+ module.exports = {
197
+ ROOT,
198
+ LEGS,
199
+ InfraError,
200
+ payload,
201
+ golden,
202
+ createRunner,
203
+ requirementsMet,
204
+ driveStatePersist,
205
+ findCaptureRecords,
206
+ };
@@ -0,0 +1,16 @@
1
+ {
2
+ "expectedFiles": [
3
+ "handoff-state.json"
4
+ ],
5
+ "keys": [
6
+ "lastEditAt",
7
+ "lastVerifyAt",
8
+ "lastVerifyExitCode",
9
+ "status",
10
+ "timestamp"
11
+ ],
12
+ "values": {
13
+ "status": "idle",
14
+ "lastVerifyExitCode": null
15
+ }
16
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "session_id": "r2c1-sess-a",
3
+ "prompt_id": "550e8400-e29b-41d4-a716-446655440000",
4
+ "transcript_path": "/tmp/r2c1/transcript-a.jsonl",
5
+ "cwd": "/tmp/r2c1-ws",
6
+ "permission_mode": "default",
7
+ "hook_event_name": "PostToolUse",
8
+ "tool_name": "Bash",
9
+ "tool_input": { "command": "npm test", "description": "Run test suite" },
10
+ "tool_response": { "stdout": "ok", "stderr": "", "interrupted": false, "isImage": false },
11
+ "tool_use_id": "toolu_r2c1_a",
12
+ "duration_ms": 12
13
+ }
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ // Test preload for real Stop hooks: reject writes whose target is inside one
4
+ // selected session directory while leaving reads and unrelated writes alone.
5
+ // The migration suite passes the target with HARNESS_STOP_TEST_SESSION_DIR.
6
+
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+
10
+ (function install() {
11
+ const sessionDirectory = process.env.HARNESS_STOP_TEST_SESSION_DIR;
12
+ if (!sessionDirectory) return;
13
+ let resolvedDirectory;
14
+ try { resolvedDirectory = path.resolve(sessionDirectory); } catch (_) { return; }
15
+ if (!resolvedDirectory || resolvedDirectory === path.parse(resolvedDirectory).root) return;
16
+
17
+ function unwritable(target) {
18
+ if (target === undefined || target === null) return false;
19
+ try {
20
+ const resolved = path.resolve(String(target));
21
+ const relative = path.relative(resolvedDirectory, resolved);
22
+ return relative === '' || (!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative));
23
+ } catch (_) { return false; }
24
+ }
25
+
26
+ function denied(method, target) {
27
+ const error = new Error(`EACCES: permission denied, ${method} ${target} (simulated session store write failure)`);
28
+ error.code = 'EACCES';
29
+ error.errno = -13;
30
+ error.syscall = method;
31
+ error.path = String(target);
32
+ return error;
33
+ }
34
+
35
+ const originalWriteFileSync = fs.writeFileSync;
36
+ fs.writeFileSync = function (file, ...rest) {
37
+ if (unwritable(file)) throw denied('write', file);
38
+ return originalWriteFileSync.call(fs, file, ...rest);
39
+ };
40
+
41
+ const originalRenameSync = fs.renameSync;
42
+ fs.renameSync = function (from, to, ...rest) {
43
+ if (unwritable(from) || unwritable(to)) throw denied('rename', from);
44
+ return originalRenameSync.call(fs, from, to, ...rest);
45
+ };
46
+
47
+ const originalOpenSync = fs.openSync;
48
+ fs.openSync = function (file, flags, ...rest) {
49
+ const value = String(flags || 'r');
50
+ if (unwritable(file) && (value.startsWith('w') || value.startsWith('a') || value.includes('+') || value.includes('x'))) {
51
+ throw denied('open', file);
52
+ }
53
+ return originalOpenSync.call(fs, file, flags, ...rest);
54
+ };
55
+
56
+ const originalUnlinkSync = fs.unlinkSync;
57
+ fs.unlinkSync = function (file, ...rest) {
58
+ if (unwritable(file)) throw denied('unlink', file);
59
+ return originalUnlinkSync.call(fs, file, ...rest);
60
+ };
61
+
62
+ const callback = args => typeof args[args.length - 1] === 'function' ? args[args.length - 1] : () => {};
63
+ const originalWriteFile = fs.writeFile;
64
+ fs.writeFile = function (file, data, ...rest) {
65
+ const done = callback(rest);
66
+ if (unwritable(file)) return process.nextTick(() => done(denied('write', file)));
67
+ return originalWriteFile.call(fs, file, data, ...rest);
68
+ };
69
+
70
+ const originalRename = fs.rename;
71
+ fs.rename = function (from, to, ...rest) {
72
+ const done = callback(rest);
73
+ if (unwritable(from) || unwritable(to)) return process.nextTick(() => done(denied('rename', from)));
74
+ return originalRename.call(fs, from, to, ...rest);
75
+ };
76
+
77
+ const originalUnlink = fs.unlink;
78
+ fs.unlink = function (file, ...rest) {
79
+ const done = callback(rest);
80
+ if (unwritable(file)) return process.nextTick(() => done(denied('unlink', file)));
81
+ return originalUnlink.call(fs, file, ...rest);
82
+ };
83
+
84
+ const promises = fs.promises;
85
+ if (!promises) return;
86
+ const originalPromisesWriteFile = promises.writeFile;
87
+ promises.writeFile = function (file, data, ...rest) {
88
+ if (unwritable(file)) return Promise.reject(denied('write', file));
89
+ return originalPromisesWriteFile.call(promises, file, data, ...rest);
90
+ };
91
+ const originalPromisesRename = promises.rename;
92
+ promises.rename = function (from, to, ...rest) {
93
+ if (unwritable(from) || unwritable(to)) return Promise.reject(denied('rename', from));
94
+ return originalPromisesRename.call(promises, from, to, ...rest);
95
+ };
96
+ const originalPromisesUnlink = promises.unlink;
97
+ promises.unlink = function (file, ...rest) {
98
+ if (unwritable(file)) return Promise.reject(denied('unlink', file));
99
+ return originalPromisesUnlink.call(promises, file, ...rest);
100
+ };
101
+ const originalPromisesOpen = promises.open;
102
+ promises.open = function (file, flags, ...rest) {
103
+ const value = String(flags || 'r');
104
+ if (unwritable(file) && (value.startsWith('w') || value.startsWith('a') || value.includes('+') || value.includes('x'))) {
105
+ return Promise.reject(denied('open', file));
106
+ }
107
+ return originalPromisesOpen.call(promises, file, flags, ...rest);
108
+ };
109
+ })();