nofax 0.2.47 → 0.2.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +65 -1
- package/docs/remote-mcp.md +55 -0
- package/package.json +1 -1
- package/src/adapters/claude.mjs +2 -2
- package/src/adapters/codex.mjs +2 -2
- package/src/adapters/gemini.mjs +3 -3
- package/src/cli.mjs +115 -17
- package/src/config.mjs +115 -11
- package/src/mcp-server.mjs +5 -1
- package/src/mcp-tools.mjs +42 -18
- package/src/ntfy.mjs +259 -44
- package/src/protocol.mjs +126 -21
- package/src/requests.mjs +107 -38
package/src/protocol.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
2
|
|
|
3
|
-
const SECRET_KEY = /(?:^|[_-])(token|password|passwd|secret|api[_-]?key|authorization|cookie|credential|private[_-]?key)(?:$|[_-])/i;
|
|
3
|
+
const SECRET_KEY = /(?:^|[_-])(token|password|passwd|secret|api[_-]?key|authorization|cookie|session[_-]?(?:id|key)|credential|private[_-]?key)(?:$|[_-])/i;
|
|
4
4
|
const MAX_STRING = 500;
|
|
5
|
+
const MAX_REDACTION_INPUT = 16 * 1024;
|
|
5
6
|
const MAX_DEPTH = 5;
|
|
6
7
|
const MAX_ARRAY = 20;
|
|
7
8
|
const MAX_OBJECT_KEYS = 30;
|
|
@@ -12,8 +13,12 @@ const TRUNCATION_MARKER = '…[truncated]';
|
|
|
12
13
|
function normalizeSecretKeyName(key) {
|
|
13
14
|
let normalized = '';
|
|
14
15
|
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
// Invisible format marks and blank fillers can split a credential field
|
|
17
|
+
// name without changing its appearance. Ignore them only for classification.
|
|
18
|
+
const comparisonKey = key.replace(/[\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]/gu, '');
|
|
19
|
+
|
|
20
|
+
for (let index = 0; index < comparisonKey.length; index += 1) {
|
|
21
|
+
const char = comparisonKey[index];
|
|
17
22
|
const code = char.charCodeAt(0);
|
|
18
23
|
const isUpper = code >= 65 && code <= 90;
|
|
19
24
|
const isLower = code >= 97 && code <= 122;
|
|
@@ -24,8 +29,8 @@ function normalizeSecretKeyName(key) {
|
|
|
24
29
|
continue;
|
|
25
30
|
}
|
|
26
31
|
|
|
27
|
-
const previousCode = index > 0 ?
|
|
28
|
-
const nextCode = index + 1 <
|
|
32
|
+
const previousCode = index > 0 ? comparisonKey.charCodeAt(index - 1) : -1;
|
|
33
|
+
const nextCode = index + 1 < comparisonKey.length ? comparisonKey.charCodeAt(index + 1) : -1;
|
|
29
34
|
const previousIsUpper = previousCode >= 65 && previousCode <= 90;
|
|
30
35
|
const previousIsLower = previousCode >= 97 && previousCode <= 122;
|
|
31
36
|
const previousIsDigit = previousCode >= 48 && previousCode <= 57;
|
|
@@ -58,12 +63,47 @@ function isSecretKey(key) {
|
|
|
58
63
|
|| lower === 'pass_phrase'
|
|
59
64
|
|| lower.endsWith('_passphrase')
|
|
60
65
|
|| lower.endsWith('_pass_phrase');
|
|
61
|
-
const isSignedUrlSignature = lower === 'x_amz_signature' || lower === 'x_goog_signature';
|
|
62
|
-
|
|
66
|
+
const isSignedUrlSignature = lower === 'sig' || lower === 'x_amz_signature' || lower === 'x_goog_signature';
|
|
67
|
+
// Hosted Git PAT fields are credentials even when the key omits "token".
|
|
68
|
+
const isHostedPat = /(?:^|_)(?:github|gitlab|gh)_pat$/.test(lower);
|
|
69
|
+
return lower === 'auth' || isSignedUrlSignature || isAuthHeader || isAuthHeaderValue || isPassphrase || isHostedPat || SECRET_KEY.test(normalized);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function normalizeUnicodeEscapedSecretKeys(text) {
|
|
73
|
+
// Serialized agent commands can conceal credential field names with JSON
|
|
74
|
+
// Unicode escapes (including extra escaping when JSON is serialized again).
|
|
75
|
+
// Normalize only secret-key names, so the existing quoted-value redaction
|
|
76
|
+
// handles them without decoding or exposing unrelated command content.
|
|
77
|
+
return text.replace(
|
|
78
|
+
/(?<!\\)(\\*["'])((?:[A-Za-z0-9_./ \\-]|\\+u[0-9a-fA-F]{4}){1,64})\1(?=\s*[:=])/g,
|
|
79
|
+
(match, quote, key) => {
|
|
80
|
+
if (!key.includes('\\u')) return match;
|
|
81
|
+
const decoded = key.replace(/\\+u([0-9a-fA-F]{4})/g, (_escape, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
82
|
+
return isSecretKey(decoded) ? `${quote}${decoded}${quote}` : match;
|
|
83
|
+
}
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function redactInvisibleSecretKeyText(text) {
|
|
88
|
+
const invisible = /[\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]/u;
|
|
89
|
+
if (!invisible.test(text)) return text;
|
|
90
|
+
|
|
91
|
+
// Classify the original key before escaping its invisible marks for display.
|
|
92
|
+
// Preserve that evidence while hiding the value in quoted and plain assignments.
|
|
93
|
+
return text.replace(
|
|
94
|
+
/(["']?)([A-Za-z][A-Za-z0-9_.\/ \-\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]{0,63})\1([ \t]*[:=][ \t]*)(?:(?:bearer|basic)[ \t]+(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s`,;&}\]]+)|"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s`,;&}\]]+)/giu,
|
|
95
|
+
(match, keyQuote, key, separator) => {
|
|
96
|
+
if (!invisible.test(key) || !isSecretKey(key)) return match;
|
|
97
|
+
const prefix = `${keyQuote}${key}${keyQuote}${separator}`;
|
|
98
|
+
const value = match.slice(prefix.length);
|
|
99
|
+
const valueQuote = value[0] === '"' || value[0] === "'" ? value[0] : '';
|
|
100
|
+
return `${prefix}${valueQuote}[REDACTED]${valueQuote}`;
|
|
101
|
+
}
|
|
102
|
+
);
|
|
63
103
|
}
|
|
64
104
|
|
|
65
105
|
function redactSecretText(value) {
|
|
66
|
-
let redacted = value;
|
|
106
|
+
let redacted = redactInvisibleSecretKeyText(normalizeUnicodeEscapedSecretKeys(value));
|
|
67
107
|
|
|
68
108
|
redacted = redacted.replace(
|
|
69
109
|
/-----BEGIN ([A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?)-----[\s\S]*?(?:-----END \1-----|$)/g,
|
|
@@ -71,8 +111,30 @@ function redactSecretText(value) {
|
|
|
71
111
|
);
|
|
72
112
|
|
|
73
113
|
redacted = redacted.replace(
|
|
74
|
-
/\b([A-Za-z][A-Za-z0-9+.-]{1,31}:\/\/)([^\s
|
|
75
|
-
|
|
114
|
+
/\b([A-Za-z][A-Za-z0-9+.-]{1,31}:\/\/)([^\s\/?#"'`<>]+)/g,
|
|
115
|
+
(match, scheme, authority) => {
|
|
116
|
+
const finalAt = authority.lastIndexOf('@');
|
|
117
|
+
if (finalAt === -1) return match;
|
|
118
|
+
|
|
119
|
+
const userinfo = authority.slice(0, finalAt);
|
|
120
|
+
const host = authority.slice(finalAt + 1);
|
|
121
|
+
const passwordAt = userinfo.indexOf(':');
|
|
122
|
+
// Keep established username:password output, but never expose token-only
|
|
123
|
+
// or ambiguous multi-@ userinfo in approval previews.
|
|
124
|
+
if (passwordAt !== -1 && !userinfo.includes('@')) {
|
|
125
|
+
return `${scheme}${userinfo.slice(0, passwordAt)}:[REDACTED]@${host}`;
|
|
126
|
+
}
|
|
127
|
+
return `${scheme}[REDACTED]@${host}`;
|
|
128
|
+
}
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
// Commands may embed a JSON string containing another serialized JSON object,
|
|
132
|
+
// such as \"api_key\":\"value\". Redact escaped credential fields too.
|
|
133
|
+
redacted = redacted.replace(
|
|
134
|
+
/(?<!\\)(\\+")([A-Za-z][A-Za-z0-9_./ \\-\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]{0,63})\1(\s*[:=]\s*)\1[\s\S]*?(?<!\\)\1/g,
|
|
135
|
+
(match, quote, key, separator) => isSecretKey(key)
|
|
136
|
+
? quote + key + quote + separator + quote + '[REDACTED]' + quote
|
|
137
|
+
: match
|
|
76
138
|
);
|
|
77
139
|
|
|
78
140
|
redacted = redacted.replace(
|
|
@@ -111,28 +173,41 @@ function redactSecretText(value) {
|
|
|
111
173
|
);
|
|
112
174
|
|
|
113
175
|
redacted = redacted.replace(
|
|
114
|
-
/([?&#])([A-Za-z][A-Za-z0-9._-]{0,63})=([^&\s"'`,;]+)/g,
|
|
115
|
-
(match, prefix, key) =>
|
|
116
|
-
|
|
117
|
-
|
|
176
|
+
/([?&#])((?:[A-Za-z]|%[0-9a-fA-F]{2})(?:[A-Za-z0-9._+-]|%[0-9a-fA-F]{2}){0,63})=([^&\s"'`,;]+)/g,
|
|
177
|
+
(match, prefix, key) => {
|
|
178
|
+
let decodedKey;
|
|
179
|
+
// Form-encoded query keys interpret '+' as a space (e.g. api+key).
|
|
180
|
+
try { decodedKey = decodeURIComponent(key.replace(/\+/g, ' ')); } catch { return match; }
|
|
181
|
+
return isSecretKey(decodedKey) || decodedKey.toLowerCase() === 'signature'
|
|
182
|
+
? `${prefix}${key}=[REDACTED]`
|
|
183
|
+
: match;
|
|
184
|
+
}
|
|
118
185
|
);
|
|
119
186
|
|
|
120
187
|
redacted = redacted.replace(
|
|
121
|
-
/(["'])([A-Za-z][A-Za-z0-9_
|
|
188
|
+
/(["'])([A-Za-z][A-Za-z0-9_./ \\-]{0,63})\1(\s*[:=]\s*)(["'])(?:\\.|(?!\4)[^\r\n])*\4/g,
|
|
122
189
|
(match, keyQuote, key, separator, valueQuote) => isSecretKey(key)
|
|
123
190
|
? `${keyQuote}${key}${keyQuote}${separator}${valueQuote}[REDACTED]${valueQuote}`
|
|
124
191
|
: match
|
|
125
192
|
);
|
|
126
193
|
|
|
127
194
|
redacted = redacted.replace(
|
|
128
|
-
/([A-Za-z][A-Za-z0-9_-]{0,63})(\s*[:=]\s*)(["'])(.*?)\3/g,
|
|
195
|
+
/([A-Za-z][A-Za-z0-9_./-]{0,63}(?:[ \t]+[A-Za-z][A-Za-z0-9_./-]{0,63})?)(\s*[:=]\s*)(["'])(.*?)\3/g,
|
|
129
196
|
(match, key, separator, valueQuote) => isSecretKey(key)
|
|
130
197
|
? `${key}${separator}${valueQuote}[REDACTED]${valueQuote}`
|
|
131
198
|
: match
|
|
132
199
|
);
|
|
133
200
|
|
|
201
|
+
// Preserve the displayed auth scheme, but never leave its credential behind.
|
|
134
202
|
redacted = redacted.replace(
|
|
135
|
-
/([A-Za-z][A-Za-z0-9_-]{0,63})(\
|
|
203
|
+
/([A-Za-z][A-Za-z0-9_./-]{0,63}(?:[ \t]+[A-Za-z][A-Za-z0-9_./-]{0,63})?)([ \t]*[:=][ \t]*)(bearer|basic)([ \t]+)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s"'`,;&]+)/gi,
|
|
204
|
+
(match, key, separator, scheme, gap) => isSecretKey(key)
|
|
205
|
+
? `${key}${separator}${scheme}${gap}[REDACTED]`
|
|
206
|
+
: match
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
redacted = redacted.replace(
|
|
210
|
+
/([A-Za-z][A-Za-z0-9_./-]{0,63}(?:[ \t]+[A-Za-z][A-Za-z0-9_./-]{0,63})?)(\s*[:=]\s*)([^\s"'`,;&]+)/g,
|
|
136
211
|
(match, key, separator, rawValue) => {
|
|
137
212
|
if (!isSecretKey(key)) return match;
|
|
138
213
|
if (/^\[REDACTED\][}\])]*$/.test(rawValue)) return match;
|
|
@@ -156,7 +231,7 @@ function redactSecretText(value) {
|
|
|
156
231
|
);
|
|
157
232
|
|
|
158
233
|
redacted = redacted.replace(
|
|
159
|
-
/--([A-Za-z][A-Za-z0-9_
|
|
234
|
+
/--([A-Za-z][A-Za-z0-9_./-]{0,63})(\s+)(["'](?:.*?)["']|[^\s"'`,;&]+)/g,
|
|
160
235
|
(match, key, separator) => isSecretKey(key)
|
|
161
236
|
? `--${key}${separator}[REDACTED]`
|
|
162
237
|
: match
|
|
@@ -182,6 +257,26 @@ function safeSliceEnd(text, end) {
|
|
|
182
257
|
return previous >= 0xD800 && previous <= 0xDBFF ? end - 1 : end;
|
|
183
258
|
}
|
|
184
259
|
|
|
260
|
+
function escapeDisplayControls(text) {
|
|
261
|
+
// Human-facing summaries must reveal hidden direction and zero-width marks,
|
|
262
|
+
// while retaining ordinary line breaks and emoji joiners.
|
|
263
|
+
const characters = [...text];
|
|
264
|
+
return characters.map((character, index) => {
|
|
265
|
+
if (character === '\u200c' || character === '\u200d') {
|
|
266
|
+
let before = index - 1;
|
|
267
|
+
while (before >= 0 && /[\ufe0e\ufe0f\p{Emoji_Modifier}]/u.test(characters[before])) before--;
|
|
268
|
+
if (character === '\u200d' &&
|
|
269
|
+
/\p{Extended_Pictographic}/u.test(characters[before] ?? '') &&
|
|
270
|
+
/\p{Extended_Pictographic}/u.test(characters[index + 1] ?? '')) {
|
|
271
|
+
return character;
|
|
272
|
+
}
|
|
273
|
+
return `\\u${character.codePointAt(0).toString(16).padStart(4, '0')}`;
|
|
274
|
+
}
|
|
275
|
+
return character.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u00ad\u034f\u061c\u115f-\u1160\u180e\u200b\u200e-\u200f\u2028-\u202e\u2060-\u2064\u2066-\u2069\u2800\u3164\uffa0\ufeff]/gu,
|
|
276
|
+
(control) => `\\u${control.codePointAt(0).toString(16).padStart(4, '0')}`);
|
|
277
|
+
}).join('');
|
|
278
|
+
}
|
|
279
|
+
|
|
185
280
|
function boundResponseText(value) {
|
|
186
281
|
if (value.length <= MAX_RESPONSE_TEXT) return value;
|
|
187
282
|
const end = safeSliceEnd(value, MAX_RESPONSE_TEXT - TRUNCATION_MARKER.length);
|
|
@@ -201,7 +296,10 @@ export function createPhoneTopic() {
|
|
|
201
296
|
}
|
|
202
297
|
|
|
203
298
|
function boundString(value) {
|
|
204
|
-
|
|
299
|
+
// Do not run complex credential-redaction patterns on arbitrarily large
|
|
300
|
+
// untrusted commands. Showing a prefix could disclose a partial secret.
|
|
301
|
+
if (value.length > MAX_REDACTION_INPUT) return '[OVERSIZED_INPUT_REDACTED]';
|
|
302
|
+
const redacted = escapeDisplayControls(redactSecretText(value));
|
|
205
303
|
const truncated = value.length > MAX_STRING || redacted.length > MAX_STRING;
|
|
206
304
|
const bounded = redacted.length <= MAX_STRING
|
|
207
305
|
? redacted
|
|
@@ -222,10 +320,12 @@ export function redactAndBound(value, options = {}) {
|
|
|
222
320
|
if (typeof value !== 'object') return boundString(String(value));
|
|
223
321
|
|
|
224
322
|
if (seen.has(value)) return '[CIRCULAR]';
|
|
323
|
+
// Track only the active recursion path; shared sibling references are not cycles.
|
|
225
324
|
seen.add(value);
|
|
226
325
|
|
|
227
326
|
if (Array.isArray(value)) {
|
|
228
327
|
if (value.length === 2 && typeof value[0] === 'string' && isSecretKey(value[0])) {
|
|
328
|
+
seen.delete(value);
|
|
229
329
|
return [boundString(value[0]), '[REDACTED]'];
|
|
230
330
|
}
|
|
231
331
|
const bounded = value.slice(0, MAX_ARRAY);
|
|
@@ -239,6 +339,7 @@ export function redactAndBound(value, options = {}) {
|
|
|
239
339
|
: redactAndBound(item, { seen, depth: depth + 1 })
|
|
240
340
|
));
|
|
241
341
|
if (value.length > MAX_ARRAY) out.push(TRUNCATION_MARKER);
|
|
342
|
+
seen.delete(value);
|
|
242
343
|
return out;
|
|
243
344
|
}
|
|
244
345
|
|
|
@@ -252,15 +353,18 @@ export function redactAndBound(value, options = {}) {
|
|
|
252
353
|
const out = {};
|
|
253
354
|
for (const [key, child] of entries.slice(0, MAX_OBJECT_KEYS)) {
|
|
254
355
|
const normalizedKey = key.toLowerCase();
|
|
255
|
-
|
|
356
|
+
const bounded = isSecretKey(key) || (redactEntryValue && (normalizedKey === 'value' || normalizedKey === 'values'))
|
|
256
357
|
? '[REDACTED]'
|
|
257
358
|
: redactAndBound(child, { seen, depth: depth + 1 });
|
|
359
|
+
// Assignment to '__proto__' changes the prototype instead of retaining approval context.
|
|
360
|
+
Object.defineProperty(out, key, { value: bounded, enumerable: true, writable: true, configurable: true });
|
|
258
361
|
}
|
|
259
362
|
if (entries.length > MAX_OBJECT_KEYS) {
|
|
260
363
|
let markerKey = TRUNCATION_MARKER;
|
|
261
364
|
while (Object.hasOwn(out, markerKey)) markerKey += '*';
|
|
262
365
|
out[markerKey] = true;
|
|
263
366
|
}
|
|
367
|
+
seen.delete(value);
|
|
264
368
|
return out;
|
|
265
369
|
}
|
|
266
370
|
|
|
@@ -307,7 +411,8 @@ export function parseResponseMessage(message, { requestId, allowed, kind }) {
|
|
|
307
411
|
if (kind === 'choice') return { decision: 'refine' };
|
|
308
412
|
if (typeof parsed.text !== 'string') return null;
|
|
309
413
|
const text = parsed.text.trim();
|
|
310
|
-
|
|
414
|
+
// JSON permits escaped lone surrogates; never silently rewrite a human refinement.
|
|
415
|
+
if (!text || !text.isWellFormed()) return null;
|
|
311
416
|
return { decision: 'refine', text: boundResponseText(text) };
|
|
312
417
|
}
|
|
313
418
|
|
package/src/requests.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { chmod, link, mkdir,
|
|
1
|
+
import { chmod, link, mkdir, open, opendir, unlink, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
|
-
import { normalizeServer, resolveNofaxHome } from './config.mjs';
|
|
3
|
+
import { normalizeServer, resolveNofaxHome, validateTopic } from './config.mjs';
|
|
4
4
|
|
|
5
5
|
const REQUEST_ID = /^nfx_[A-Za-z0-9_-]{20,80}$/;
|
|
6
6
|
const RESPONSE_TOPIC = /^nofax_r_[A-Za-z0-9_-]{20,120}$/;
|
|
@@ -8,6 +8,7 @@ const PHONE_TOPIC = /^[A-Za-z0-9_-]{24,128}$/;
|
|
|
8
8
|
const KINDS = new Set(['approval', 'choice', 'refinement']);
|
|
9
9
|
const STATUSES = new Set(['pending', 'resolved']);
|
|
10
10
|
const MAX_RESPONSE_TEXT = 2000;
|
|
11
|
+
const MAX_REQUEST_RECORD_BYTES = 64 * 1024;
|
|
11
12
|
const TRUNCATION_MARKER = '…[truncated]';
|
|
12
13
|
|
|
13
14
|
function validateRequestId(value) {
|
|
@@ -36,11 +37,29 @@ function validateRequest(input) {
|
|
|
36
37
|
throw new Error('NOFAX_REQUEST_ALLOWED_INVALID');
|
|
37
38
|
}
|
|
38
39
|
const allowed = input.allowed.map((value) => value.trim());
|
|
39
|
-
if (allowed.some((value) => !value || value.length > 80
|
|
40
|
+
if (allowed.some((value) => !value || value.length > 80 || !value.isWellFormed()) ||
|
|
41
|
+
new Set(allowed).size !== allowed.length) {
|
|
42
|
+
throw new Error('NOFAX_REQUEST_ALLOWED_INVALID');
|
|
43
|
+
}
|
|
44
|
+
// An imported record cannot turn an approval or refinement into an
|
|
45
|
+
// arbitrary choice by changing its stored allowed values.
|
|
46
|
+
if (input.kind === 'approval' &&
|
|
47
|
+
(!allowed.includes('allow') || !allowed.includes('deny') ||
|
|
48
|
+
allowed.some((value) => !['allow', 'deny', 'refine'].includes(value)))) {
|
|
49
|
+
throw new Error('NOFAX_REQUEST_ALLOWED_INVALID');
|
|
50
|
+
}
|
|
51
|
+
if (input.kind === 'refinement' && (allowed.length !== 1 || allowed[0] !== 'refine')) {
|
|
40
52
|
throw new Error('NOFAX_REQUEST_ALLOWED_INVALID');
|
|
41
53
|
}
|
|
42
54
|
if (!STATUSES.has(input.status)) throw new Error('NOFAX_REQUEST_STATUS_INVALID');
|
|
43
|
-
if (
|
|
55
|
+
if (input.status === 'pending' &&
|
|
56
|
+
(input.resolvedAt !== undefined || input.decision !== undefined || input.text !== undefined)) {
|
|
57
|
+
// Do not silently strip a legacy denial or private human text and then
|
|
58
|
+
// treat its record as a fresh, unresolved approval request.
|
|
59
|
+
throw new Error('NOFAX_REQUEST_PENDING_TERMINAL_FIELDS_INVALID');
|
|
60
|
+
}
|
|
61
|
+
const createdAtMs = typeof input.createdAt === 'string' ? Date.parse(input.createdAt) : NaN;
|
|
62
|
+
if (!Number.isFinite(createdAtMs)) throw new Error('NOFAX_REQUEST_CREATED_AT_INVALID');
|
|
44
63
|
const hasServer = input.server !== undefined;
|
|
45
64
|
const hasTopic = input.topic !== undefined;
|
|
46
65
|
if (hasServer !== hasTopic) throw new Error('NOFAX_REQUEST_TRANSPORT_INVALID');
|
|
@@ -61,17 +80,25 @@ function validateRequest(input) {
|
|
|
61
80
|
base.topic = input.topic;
|
|
62
81
|
}
|
|
63
82
|
if (input.status === 'resolved') {
|
|
64
|
-
|
|
83
|
+
const resolvedAtMs = typeof input.resolvedAt === 'string' ? Date.parse(input.resolvedAt) : NaN;
|
|
84
|
+
// A terminal decision cannot precede the request it purportedly resolved.
|
|
85
|
+
if (!Number.isFinite(resolvedAtMs) || resolvedAtMs < createdAtMs) throw new Error('NOFAX_REQUEST_RESOLVED_AT_INVALID');
|
|
65
86
|
if (typeof input.decision !== 'string') throw new Error('NOFAX_REQUEST_DECISION_INVALID');
|
|
66
87
|
const decision = input.decision.trim();
|
|
67
88
|
if (!allowed.includes(decision)) throw new Error('NOFAX_REQUEST_DECISION_INVALID');
|
|
89
|
+
// Only a refinement can carry human text; reject corrupt legacy sidecars
|
|
90
|
+
// and unexpected direct responses rather than persisting private content.
|
|
91
|
+
if (decision !== 'refine' && input.text !== undefined) throw new Error('NOFAX_REQUEST_TEXT_INVALID');
|
|
68
92
|
if (decision === 'refine' && input.kind !== 'choice' && (typeof input.text !== 'string' || !input.text.trim())) {
|
|
69
93
|
throw new Error('NOFAX_REQUEST_TEXT_INVALID');
|
|
70
94
|
}
|
|
71
95
|
base.resolvedAt = input.resolvedAt;
|
|
72
96
|
base.decision = decision;
|
|
73
97
|
if (input.text !== undefined) {
|
|
74
|
-
|
|
98
|
+
// JSON can preserve escaped lone surrogates even after strict UTF-8 decoding.
|
|
99
|
+
if (typeof input.text !== 'string' || !input.text.trim() || !input.text.isWellFormed()) {
|
|
100
|
+
throw new Error('NOFAX_REQUEST_TEXT_INVALID');
|
|
101
|
+
}
|
|
75
102
|
base.text = boundResponseText(input.text);
|
|
76
103
|
}
|
|
77
104
|
}
|
|
@@ -89,18 +116,36 @@ function paths({ home, env, requestId }) {
|
|
|
89
116
|
};
|
|
90
117
|
}
|
|
91
118
|
|
|
92
|
-
async function
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
119
|
+
async function readBoundedRecord(path, tooLargeCode, invalidUtf8Code) {
|
|
120
|
+
const file = await open(path, 'r');
|
|
121
|
+
try {
|
|
122
|
+
// A corrupt local request record must not allocate unbounded memory during
|
|
123
|
+
// status inspection, cleanup, or recovery of a terminal human decision.
|
|
124
|
+
const buffer = Buffer.allocUnsafe(MAX_REQUEST_RECORD_BYTES + 1);
|
|
125
|
+
let length = 0;
|
|
126
|
+
while (length < buffer.length) {
|
|
127
|
+
const { bytesRead } = await file.read(buffer, length, buffer.length - length, null);
|
|
128
|
+
if (bytesRead === 0) break;
|
|
129
|
+
length += bytesRead;
|
|
130
|
+
}
|
|
131
|
+
if (length > MAX_REQUEST_RECORD_BYTES) throw new Error(tooLargeCode);
|
|
132
|
+
try {
|
|
133
|
+
// A replacement character must not silently change persisted human
|
|
134
|
+
// decisions or refinement text when a request record is corrupted.
|
|
135
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, length));
|
|
136
|
+
} catch {
|
|
137
|
+
throw new Error(invalidUtf8Code);
|
|
138
|
+
}
|
|
139
|
+
} finally {
|
|
140
|
+
await file.close();
|
|
141
|
+
}
|
|
98
142
|
}
|
|
99
143
|
|
|
100
|
-
async function loadTerminalClaim(path) {
|
|
144
|
+
async function loadTerminalClaim(path, requestId) {
|
|
101
145
|
try {
|
|
102
|
-
const terminal = validateRequest(JSON.parse(await
|
|
146
|
+
const terminal = validateRequest(JSON.parse(await readBoundedRecord(path, 'NOFAX_REQUEST_TERMINAL_TOO_LARGE', 'NOFAX_REQUEST_TERMINAL_INVALID_UTF8')));
|
|
103
147
|
if (terminal.status !== 'resolved') throw new Error('NOFAX_REQUEST_TERMINAL_INVALID');
|
|
148
|
+
if (terminal.requestId !== requestId) throw new Error('NOFAX_REQUEST_ID_MISMATCH');
|
|
104
149
|
return terminal;
|
|
105
150
|
} catch (error) {
|
|
106
151
|
if (error?.code === 'ENOENT') return null;
|
|
@@ -109,18 +154,27 @@ async function loadTerminalClaim(path) {
|
|
|
109
154
|
}
|
|
110
155
|
}
|
|
111
156
|
|
|
112
|
-
async function
|
|
157
|
+
async function createExclusiveRecord(path, value) {
|
|
113
158
|
const temp = `${path}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
159
|
+
// Exclusive creation prevents a pre-existing hardlink or symlink from
|
|
160
|
+
// redirecting writes; cleanup is limited to the temporary file we created.
|
|
161
|
+
const handle = await open(temp, 'wx', 0o600);
|
|
117
162
|
try {
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
163
|
+
try {
|
|
164
|
+
await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
165
|
+
await handle.sync();
|
|
166
|
+
} finally {
|
|
167
|
+
await handle.close();
|
|
168
|
+
}
|
|
169
|
+
try { await chmod(temp, 0o600); } catch {}
|
|
170
|
+
try {
|
|
171
|
+
await link(temp, path);
|
|
172
|
+
try { await chmod(path, 0o600); } catch {}
|
|
173
|
+
return true;
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (error?.code === 'EEXIST') return false;
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
124
178
|
} finally {
|
|
125
179
|
try { await unlink(temp); } catch {}
|
|
126
180
|
}
|
|
@@ -129,17 +183,26 @@ async function claimTerminal(path, value) {
|
|
|
129
183
|
export async function savePendingRequest({ home, env, request }) {
|
|
130
184
|
const normalized = validateRequest(request);
|
|
131
185
|
if (normalized.status !== 'pending') throw new Error('NOFAX_REQUEST_NOT_PENDING');
|
|
132
|
-
|
|
186
|
+
// New records must use a strong notification topic. Keep the looser read
|
|
187
|
+
// contract for historical denials and other already-persisted decisions.
|
|
188
|
+
if (normalized.topic !== undefined) validateTopic(normalized.topic);
|
|
189
|
+
const { requestsRoot, file, terminal } = paths({ home, env, requestId: normalized.requestId });
|
|
133
190
|
await mkdir(requestsRoot, { recursive: true, mode: 0o700 });
|
|
134
|
-
await
|
|
191
|
+
if (await loadTerminalClaim(terminal, normalized.requestId) !== null) {
|
|
192
|
+
throw new Error('NOFAX_REQUEST_ALREADY_EXISTS');
|
|
193
|
+
}
|
|
194
|
+
if (!await createExclusiveRecord(file, normalized)) {
|
|
195
|
+
throw new Error('NOFAX_REQUEST_ALREADY_EXISTS');
|
|
196
|
+
}
|
|
135
197
|
return normalized;
|
|
136
198
|
}
|
|
137
199
|
|
|
138
200
|
export async function discardPendingRequest({ home, env, requestId }) {
|
|
139
201
|
const { file, terminal } = paths({ home, env, requestId });
|
|
140
|
-
if (await loadTerminalClaim(terminal) !== null) return false;
|
|
202
|
+
if (await loadTerminalClaim(terminal, requestId) !== null) return false;
|
|
141
203
|
try {
|
|
142
|
-
const current = validateRequest(JSON.parse(await
|
|
204
|
+
const current = validateRequest(JSON.parse(await readBoundedRecord(file, 'NOFAX_REQUEST_TOO_LARGE', 'NOFAX_REQUEST_INVALID_UTF8')));
|
|
205
|
+
if (current.requestId !== requestId) throw new Error('NOFAX_REQUEST_ID_MISMATCH');
|
|
143
206
|
if (current.status !== 'pending') return false;
|
|
144
207
|
await unlink(file);
|
|
145
208
|
return true;
|
|
@@ -152,10 +215,12 @@ export async function discardPendingRequest({ home, env, requestId }) {
|
|
|
152
215
|
|
|
153
216
|
export async function loadRequest({ home, env, requestId }) {
|
|
154
217
|
const { file, terminal } = paths({ home, env, requestId });
|
|
155
|
-
const claimed = await loadTerminalClaim(terminal);
|
|
218
|
+
const claimed = await loadTerminalClaim(terminal, requestId);
|
|
156
219
|
if (claimed !== null) return claimed;
|
|
157
220
|
try {
|
|
158
|
-
|
|
221
|
+
const request = validateRequest(JSON.parse(await readBoundedRecord(file, 'NOFAX_REQUEST_TOO_LARGE', 'NOFAX_REQUEST_INVALID_UTF8')));
|
|
222
|
+
if (request.requestId !== requestId) throw new Error('NOFAX_REQUEST_ID_MISMATCH');
|
|
223
|
+
return request;
|
|
159
224
|
} catch (error) {
|
|
160
225
|
if (error?.code === 'ENOENT') throw new Error('NOFAX_REQUEST_NOT_FOUND');
|
|
161
226
|
if (error instanceof SyntaxError) throw new Error('NOFAX_REQUEST_INVALID_JSON');
|
|
@@ -177,7 +242,7 @@ export async function resolveRequestWithClaim({ home, env, requestId, response,
|
|
|
177
242
|
...(response.text === undefined ? {} : { text: response.text })
|
|
178
243
|
});
|
|
179
244
|
const { terminal } = paths({ home, env, requestId });
|
|
180
|
-
if (!await
|
|
245
|
+
if (!await createExclusiveRecord(terminal, resolved)) {
|
|
181
246
|
return { request: await loadRequest({ home, env, requestId }), claimed: false };
|
|
182
247
|
}
|
|
183
248
|
return { request: resolved, claimed: true };
|
|
@@ -191,27 +256,31 @@ export async function listPendingRequests({ home, env, limit = 20 } = {}) {
|
|
|
191
256
|
if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error('NOFAX_REQUEST_LIMIT_INVALID');
|
|
192
257
|
const root = resolveNofaxHome({ home, env });
|
|
193
258
|
const requestsRoot = join(root, 'requests');
|
|
194
|
-
let
|
|
259
|
+
let directory;
|
|
195
260
|
try {
|
|
196
|
-
|
|
261
|
+
directory = await opendir(requestsRoot);
|
|
197
262
|
} catch (error) {
|
|
198
263
|
if (error?.code === 'ENOENT') return [];
|
|
199
264
|
throw error;
|
|
200
265
|
}
|
|
201
266
|
const results = [];
|
|
202
|
-
|
|
267
|
+
const newestFirst = (left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt) || right.requestId.localeCompare(left.requestId);
|
|
268
|
+
for await (const { name } of directory) {
|
|
203
269
|
if (!name.endsWith('.json')) continue;
|
|
204
270
|
const requestId = name.slice(0, -5);
|
|
205
271
|
if (!REQUEST_ID.test(requestId)) continue;
|
|
206
272
|
try {
|
|
207
273
|
const request = await loadRequest({ home: root, requestId });
|
|
208
|
-
if (request.status
|
|
274
|
+
if (request.status !== 'pending') continue;
|
|
275
|
+
// Scan every file to retain fail-closed validation, but keep only the newest limit records in memory.
|
|
276
|
+
if (results.length === limit && newestFirst(request, results[results.length - 1]) >= 0) continue;
|
|
277
|
+
results.push(request);
|
|
278
|
+
results.sort(newestFirst);
|
|
279
|
+
if (results.length > limit) results.pop();
|
|
209
280
|
} catch (error) {
|
|
210
281
|
if (error?.message === 'NOFAX_REQUEST_NOT_FOUND') continue;
|
|
211
282
|
throw error;
|
|
212
283
|
}
|
|
213
284
|
}
|
|
214
|
-
return results
|
|
215
|
-
.sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt) || right.requestId.localeCompare(left.requestId))
|
|
216
|
-
.slice(0, limit);
|
|
285
|
+
return results;
|
|
217
286
|
}
|