nofax 0.2.48 → 0.2.51

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/src/requests.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { chmod, link, mkdir, readFile, readdir, rename, unlink, writeFile } from 'node:fs/promises';
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) {
@@ -27,6 +28,21 @@ function boundResponseText(value) {
27
28
  return `${text.slice(0, end)}${TRUNCATION_MARKER}`;
28
29
  }
29
30
 
31
+ function parseRequestTimestamp(value) {
32
+ if (typeof value !== 'string') return NaN;
33
+ const parsed = Date.parse(value);
34
+ if (!Number.isFinite(parsed)) return NaN;
35
+ // Date.parse normalizes impossible ISO calendar days, e.g. February 30.
36
+ const calendar = /^(\d{4})-(\d{2})-(\d{2})(?:T|$)/.exec(value);
37
+ if (!calendar) return parsed; // Preserve preexisting non-ISO record compatibility.
38
+ const year = Number(calendar[1]);
39
+ const month = Number(calendar[2]);
40
+ const day = Number(calendar[3]);
41
+ const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
42
+ const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
43
+ return day >= 1 && day <= daysInMonth ? parsed : NaN;
44
+ }
45
+
30
46
  function validateRequest(input) {
31
47
  if (!input || input.version !== 1) throw new Error('NOFAX_REQUEST_VERSION');
32
48
  const requestId = validateRequestId(input.requestId);
@@ -36,11 +52,29 @@ function validateRequest(input) {
36
52
  throw new Error('NOFAX_REQUEST_ALLOWED_INVALID');
37
53
  }
38
54
  const allowed = input.allowed.map((value) => value.trim());
39
- if (allowed.some((value) => !value || value.length > 80) || new Set(allowed).size !== allowed.length) {
55
+ if (allowed.some((value) => !value || value.length > 80 || !value.isWellFormed()) ||
56
+ new Set(allowed).size !== allowed.length) {
57
+ throw new Error('NOFAX_REQUEST_ALLOWED_INVALID');
58
+ }
59
+ // An imported record cannot turn an approval or refinement into an
60
+ // arbitrary choice by changing its stored allowed values.
61
+ if (input.kind === 'approval' &&
62
+ (!allowed.includes('allow') || !allowed.includes('deny') ||
63
+ allowed.some((value) => !['allow', 'deny', 'refine'].includes(value)))) {
64
+ throw new Error('NOFAX_REQUEST_ALLOWED_INVALID');
65
+ }
66
+ if (input.kind === 'refinement' && (allowed.length !== 1 || allowed[0] !== 'refine')) {
40
67
  throw new Error('NOFAX_REQUEST_ALLOWED_INVALID');
41
68
  }
42
69
  if (!STATUSES.has(input.status)) throw new Error('NOFAX_REQUEST_STATUS_INVALID');
43
- if (typeof input.createdAt !== 'string' || Number.isNaN(Date.parse(input.createdAt))) throw new Error('NOFAX_REQUEST_CREATED_AT_INVALID');
70
+ if (input.status === 'pending' &&
71
+ (input.resolvedAt !== undefined || input.decision !== undefined || input.text !== undefined)) {
72
+ // Do not silently strip a legacy denial or private human text and then
73
+ // treat its record as a fresh, unresolved approval request.
74
+ throw new Error('NOFAX_REQUEST_PENDING_TERMINAL_FIELDS_INVALID');
75
+ }
76
+ const createdAtMs = parseRequestTimestamp(input.createdAt);
77
+ if (!Number.isFinite(createdAtMs)) throw new Error('NOFAX_REQUEST_CREATED_AT_INVALID');
44
78
  const hasServer = input.server !== undefined;
45
79
  const hasTopic = input.topic !== undefined;
46
80
  if (hasServer !== hasTopic) throw new Error('NOFAX_REQUEST_TRANSPORT_INVALID');
@@ -61,17 +95,25 @@ function validateRequest(input) {
61
95
  base.topic = input.topic;
62
96
  }
63
97
  if (input.status === 'resolved') {
64
- if (typeof input.resolvedAt !== 'string' || Number.isNaN(Date.parse(input.resolvedAt))) throw new Error('NOFAX_REQUEST_RESOLVED_AT_INVALID');
98
+ const resolvedAtMs = parseRequestTimestamp(input.resolvedAt);
99
+ // A terminal decision cannot precede the request it purportedly resolved.
100
+ if (!Number.isFinite(resolvedAtMs) || resolvedAtMs < createdAtMs) throw new Error('NOFAX_REQUEST_RESOLVED_AT_INVALID');
65
101
  if (typeof input.decision !== 'string') throw new Error('NOFAX_REQUEST_DECISION_INVALID');
66
102
  const decision = input.decision.trim();
67
103
  if (!allowed.includes(decision)) throw new Error('NOFAX_REQUEST_DECISION_INVALID');
104
+ // Only a refinement can carry human text; reject corrupt legacy sidecars
105
+ // and unexpected direct responses rather than persisting private content.
106
+ if (decision !== 'refine' && input.text !== undefined) throw new Error('NOFAX_REQUEST_TEXT_INVALID');
68
107
  if (decision === 'refine' && input.kind !== 'choice' && (typeof input.text !== 'string' || !input.text.trim())) {
69
108
  throw new Error('NOFAX_REQUEST_TEXT_INVALID');
70
109
  }
71
110
  base.resolvedAt = input.resolvedAt;
72
111
  base.decision = decision;
73
112
  if (input.text !== undefined) {
74
- if (typeof input.text !== 'string' || !input.text.trim()) throw new Error('NOFAX_REQUEST_TEXT_INVALID');
113
+ // JSON can preserve escaped lone surrogates even after strict UTF-8 decoding.
114
+ if (typeof input.text !== 'string' || !input.text.trim() || !input.text.isWellFormed()) {
115
+ throw new Error('NOFAX_REQUEST_TEXT_INVALID');
116
+ }
75
117
  base.text = boundResponseText(input.text);
76
118
  }
77
119
  }
@@ -89,18 +131,36 @@ function paths({ home, env, requestId }) {
89
131
  };
90
132
  }
91
133
 
92
- async function atomicWrite(path, value) {
93
- const temp = `${path}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;
94
- await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
95
- try { await chmod(temp, 0o600); } catch {}
96
- await rename(temp, path);
97
- try { await chmod(path, 0o600); } catch {}
134
+ async function readBoundedRecord(path, tooLargeCode, invalidUtf8Code) {
135
+ const file = await open(path, 'r');
136
+ try {
137
+ // A corrupt local request record must not allocate unbounded memory during
138
+ // status inspection, cleanup, or recovery of a terminal human decision.
139
+ const buffer = Buffer.allocUnsafe(MAX_REQUEST_RECORD_BYTES + 1);
140
+ let length = 0;
141
+ while (length < buffer.length) {
142
+ const { bytesRead } = await file.read(buffer, length, buffer.length - length, null);
143
+ if (bytesRead === 0) break;
144
+ length += bytesRead;
145
+ }
146
+ if (length > MAX_REQUEST_RECORD_BYTES) throw new Error(tooLargeCode);
147
+ try {
148
+ // A replacement character must not silently change persisted human
149
+ // decisions or refinement text when a request record is corrupted.
150
+ return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, length));
151
+ } catch {
152
+ throw new Error(invalidUtf8Code);
153
+ }
154
+ } finally {
155
+ await file.close();
156
+ }
98
157
  }
99
158
 
100
- async function loadTerminalClaim(path) {
159
+ async function loadTerminalClaim(path, requestId) {
101
160
  try {
102
- const terminal = validateRequest(JSON.parse(await readFile(path, 'utf8')));
161
+ const terminal = validateRequest(JSON.parse(await readBoundedRecord(path, 'NOFAX_REQUEST_TERMINAL_TOO_LARGE', 'NOFAX_REQUEST_TERMINAL_INVALID_UTF8')));
103
162
  if (terminal.status !== 'resolved') throw new Error('NOFAX_REQUEST_TERMINAL_INVALID');
163
+ if (terminal.requestId !== requestId) throw new Error('NOFAX_REQUEST_ID_MISMATCH');
104
164
  return terminal;
105
165
  } catch (error) {
106
166
  if (error?.code === 'ENOENT') return null;
@@ -109,18 +169,27 @@ async function loadTerminalClaim(path) {
109
169
  }
110
170
  }
111
171
 
112
- async function claimTerminal(path, value) {
172
+ async function createExclusiveRecord(path, value) {
113
173
  const temp = `${path}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;
114
- await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
115
- try { await chmod(temp, 0o600); } catch {}
116
-
174
+ // Exclusive creation prevents a pre-existing hardlink or symlink from
175
+ // redirecting writes; cleanup is limited to the temporary file we created.
176
+ const handle = await open(temp, 'wx', 0o600);
117
177
  try {
118
- await link(temp, path);
119
- try { await chmod(path, 0o600); } catch {}
120
- return true;
121
- } catch (error) {
122
- if (error?.code === 'EEXIST') return false;
123
- throw error;
178
+ try {
179
+ await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`, 'utf8');
180
+ await handle.sync();
181
+ } finally {
182
+ await handle.close();
183
+ }
184
+ try { await chmod(temp, 0o600); } catch {}
185
+ try {
186
+ await link(temp, path);
187
+ try { await chmod(path, 0o600); } catch {}
188
+ return true;
189
+ } catch (error) {
190
+ if (error?.code === 'EEXIST') return false;
191
+ throw error;
192
+ }
124
193
  } finally {
125
194
  try { await unlink(temp); } catch {}
126
195
  }
@@ -129,17 +198,26 @@ async function claimTerminal(path, value) {
129
198
  export async function savePendingRequest({ home, env, request }) {
130
199
  const normalized = validateRequest(request);
131
200
  if (normalized.status !== 'pending') throw new Error('NOFAX_REQUEST_NOT_PENDING');
132
- const { requestsRoot, file } = paths({ home, env, requestId: normalized.requestId });
201
+ // New records must use a strong notification topic. Keep the looser read
202
+ // contract for historical denials and other already-persisted decisions.
203
+ if (normalized.topic !== undefined) validateTopic(normalized.topic);
204
+ const { requestsRoot, file, terminal } = paths({ home, env, requestId: normalized.requestId });
133
205
  await mkdir(requestsRoot, { recursive: true, mode: 0o700 });
134
- await atomicWrite(file, normalized);
206
+ if (await loadTerminalClaim(terminal, normalized.requestId) !== null) {
207
+ throw new Error('NOFAX_REQUEST_ALREADY_EXISTS');
208
+ }
209
+ if (!await createExclusiveRecord(file, normalized)) {
210
+ throw new Error('NOFAX_REQUEST_ALREADY_EXISTS');
211
+ }
135
212
  return normalized;
136
213
  }
137
214
 
138
215
  export async function discardPendingRequest({ home, env, requestId }) {
139
216
  const { file, terminal } = paths({ home, env, requestId });
140
- if (await loadTerminalClaim(terminal) !== null) return false;
217
+ if (await loadTerminalClaim(terminal, requestId) !== null) return false;
141
218
  try {
142
- const current = validateRequest(JSON.parse(await readFile(file, 'utf8')));
219
+ const current = validateRequest(JSON.parse(await readBoundedRecord(file, 'NOFAX_REQUEST_TOO_LARGE', 'NOFAX_REQUEST_INVALID_UTF8')));
220
+ if (current.requestId !== requestId) throw new Error('NOFAX_REQUEST_ID_MISMATCH');
143
221
  if (current.status !== 'pending') return false;
144
222
  await unlink(file);
145
223
  return true;
@@ -152,10 +230,12 @@ export async function discardPendingRequest({ home, env, requestId }) {
152
230
 
153
231
  export async function loadRequest({ home, env, requestId }) {
154
232
  const { file, terminal } = paths({ home, env, requestId });
155
- const claimed = await loadTerminalClaim(terminal);
233
+ const claimed = await loadTerminalClaim(terminal, requestId);
156
234
  if (claimed !== null) return claimed;
157
235
  try {
158
- return validateRequest(JSON.parse(await readFile(file, 'utf8')));
236
+ const request = validateRequest(JSON.parse(await readBoundedRecord(file, 'NOFAX_REQUEST_TOO_LARGE', 'NOFAX_REQUEST_INVALID_UTF8')));
237
+ if (request.requestId !== requestId) throw new Error('NOFAX_REQUEST_ID_MISMATCH');
238
+ return request;
159
239
  } catch (error) {
160
240
  if (error?.code === 'ENOENT') throw new Error('NOFAX_REQUEST_NOT_FOUND');
161
241
  if (error instanceof SyntaxError) throw new Error('NOFAX_REQUEST_INVALID_JSON');
@@ -177,7 +257,7 @@ export async function resolveRequestWithClaim({ home, env, requestId, response,
177
257
  ...(response.text === undefined ? {} : { text: response.text })
178
258
  });
179
259
  const { terminal } = paths({ home, env, requestId });
180
- if (!await claimTerminal(terminal, resolved)) {
260
+ if (!await createExclusiveRecord(terminal, resolved)) {
181
261
  return { request: await loadRequest({ home, env, requestId }), claimed: false };
182
262
  }
183
263
  return { request: resolved, claimed: true };
@@ -191,27 +271,31 @@ export async function listPendingRequests({ home, env, limit = 20 } = {}) {
191
271
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error('NOFAX_REQUEST_LIMIT_INVALID');
192
272
  const root = resolveNofaxHome({ home, env });
193
273
  const requestsRoot = join(root, 'requests');
194
- let names;
274
+ let directory;
195
275
  try {
196
- names = await readdir(requestsRoot);
276
+ directory = await opendir(requestsRoot);
197
277
  } catch (error) {
198
278
  if (error?.code === 'ENOENT') return [];
199
279
  throw error;
200
280
  }
201
281
  const results = [];
202
- for (const name of names) {
282
+ const newestFirst = (left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt) || right.requestId.localeCompare(left.requestId);
283
+ for await (const { name } of directory) {
203
284
  if (!name.endsWith('.json')) continue;
204
285
  const requestId = name.slice(0, -5);
205
286
  if (!REQUEST_ID.test(requestId)) continue;
206
287
  try {
207
288
  const request = await loadRequest({ home: root, requestId });
208
- if (request.status === 'pending') results.push(request);
289
+ if (request.status !== 'pending') continue;
290
+ // Scan every file to retain fail-closed validation, but keep only the newest limit records in memory.
291
+ if (results.length === limit && newestFirst(request, results[results.length - 1]) >= 0) continue;
292
+ results.push(request);
293
+ results.sort(newestFirst);
294
+ if (results.length > limit) results.pop();
209
295
  } catch (error) {
210
296
  if (error?.message === 'NOFAX_REQUEST_NOT_FOUND') continue;
211
297
  throw error;
212
298
  }
213
299
  }
214
- return results
215
- .sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt) || right.requestId.localeCompare(left.requestId))
216
- .slice(0, limit);
300
+ return results;
217
301
  }