@dr-co/dsh-secret-form 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +264 -2
- package/index.mjs +442 -0
- package/lib/forms.mjs +318 -0
- package/lib/i18n.mjs +458 -0
- package/lib/page.mjs +318 -0
- package/lib/targets.mjs +222 -0
- package/lib/yaml.mjs +252 -0
- package/package.json +41 -4
package/lib/forms.mjs
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
// The pending-form registry.
|
|
2
|
+
//
|
|
3
|
+
// Everything lives in this process's memory: a restart makes every form
|
|
4
|
+
// `expired`, which is the accepted trade for never writing a one-time token to
|
|
5
|
+
// disk. The registry knows nothing about HTTP or files — it validates the
|
|
6
|
+
// request, decides the state machine, and hands the submitted value to the
|
|
7
|
+
// caller so the caller can store it.
|
|
8
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
9
|
+
|
|
10
|
+
export const STATUS = Object.freeze({
|
|
11
|
+
pending: 'pending',
|
|
12
|
+
saved: 'saved',
|
|
13
|
+
empty: 'empty',
|
|
14
|
+
cancelled: 'cancelled',
|
|
15
|
+
expired: 'expired',
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export const MIN_TTL_SECONDS = 30;
|
|
19
|
+
export const MAX_TTL_SECONDS = 3600;
|
|
20
|
+
export const DEFAULT_TTL_SECONDS = 300;
|
|
21
|
+
export const DEFAULT_WAIT_SECONDS = 0;
|
|
22
|
+
export const MAX_WAIT_SECONDS = 30;
|
|
23
|
+
export const MAX_DATA_BYTES = 1024;
|
|
24
|
+
export const MAX_DESCRIPTION_CHARS = 300;
|
|
25
|
+
|
|
26
|
+
// A finished form keeps answering its link ("already used", "cancelled") for an
|
|
27
|
+
// hour past expiry; after that a lazy sweep drops it and the link reads as
|
|
28
|
+
// unknown.
|
|
29
|
+
const RETAIN_MS = 3_600_000;
|
|
30
|
+
|
|
31
|
+
function invalid(message) {
|
|
32
|
+
const error = new TypeError(message);
|
|
33
|
+
error.code = 'secret-form-invalid';
|
|
34
|
+
return error;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Clamp a TTL into the supported window.
|
|
39
|
+
* @param seconds - requested TTL; undefined takes the default.
|
|
40
|
+
* @param fallback - configured default TTL.
|
|
41
|
+
* @returns whole seconds within 30..3600.
|
|
42
|
+
*/
|
|
43
|
+
export function clampTtl(seconds, fallback = DEFAULT_TTL_SECONDS) {
|
|
44
|
+
const wanted = seconds === undefined || seconds === null ? fallback : seconds;
|
|
45
|
+
if (typeof wanted !== 'number' || !Number.isFinite(wanted)) throw invalid('ttlSeconds must be a number');
|
|
46
|
+
return Math.min(MAX_TTL_SECONDS, Math.max(MIN_TTL_SECONDS, Math.round(wanted)));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Validate the `waitSeconds` argument of `secret_result`. */
|
|
50
|
+
export function normalizeWait(seconds) {
|
|
51
|
+
if (seconds === undefined || seconds === null) return DEFAULT_WAIT_SECONDS;
|
|
52
|
+
if (!Number.isInteger(seconds) || seconds < 0 || seconds > MAX_WAIT_SECONDS) {
|
|
53
|
+
throw invalid(`waitSeconds must be an integer from 0 to ${MAX_WAIT_SECONDS}`);
|
|
54
|
+
}
|
|
55
|
+
return seconds;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function normalizeData(data) {
|
|
59
|
+
if (data === undefined || data === null) return {};
|
|
60
|
+
if (typeof data !== 'object' || Array.isArray(data)) throw invalid('data must be a JSON object');
|
|
61
|
+
const clone = structuredClone(data);
|
|
62
|
+
let serialised;
|
|
63
|
+
try {
|
|
64
|
+
serialised = JSON.stringify(clone);
|
|
65
|
+
} catch {
|
|
66
|
+
throw invalid('data must be JSON-serialisable');
|
|
67
|
+
}
|
|
68
|
+
if (serialised === undefined) throw invalid('data must be JSON-serialisable');
|
|
69
|
+
if (Buffer.byteLength(serialised, 'utf8') > MAX_DATA_BYTES) {
|
|
70
|
+
throw invalid(`data must serialise to at most ${MAX_DATA_BYTES} bytes`);
|
|
71
|
+
}
|
|
72
|
+
return clone;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function normalizeExpect(expect) {
|
|
76
|
+
if (expect === undefined || expect === null || expect === '') return undefined;
|
|
77
|
+
if (typeof expect !== 'string') throw invalid('expect must be a string holding a regular expression');
|
|
78
|
+
try {
|
|
79
|
+
return { source: expect, regex: new RegExp(expect) };
|
|
80
|
+
} catch (error) {
|
|
81
|
+
throw invalid(`expect is not a valid regular expression: ${error.message}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function normalizeLabel(label) {
|
|
86
|
+
if (typeof label !== 'string') throw invalid('label must be a string');
|
|
87
|
+
const text = label.trim();
|
|
88
|
+
if (text === '') throw invalid('label must not be empty');
|
|
89
|
+
const words = text.split(/\s+/);
|
|
90
|
+
if (words.length < 2 || words.length > 5) throw invalid('label must be 2 to 5 words');
|
|
91
|
+
if (text.length > 120) throw invalid('label must be at most 120 characters');
|
|
92
|
+
return text;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function normalizeDescription(description) {
|
|
96
|
+
if (description === undefined || description === null) return undefined;
|
|
97
|
+
if (typeof description !== 'string') throw invalid('description must be a string');
|
|
98
|
+
const text = description.trim();
|
|
99
|
+
if (text === '') return undefined;
|
|
100
|
+
if (text.length > MAX_DESCRIPTION_CHARS) {
|
|
101
|
+
throw invalid(`description must be at most ${MAX_DESCRIPTION_CHARS} characters`);
|
|
102
|
+
}
|
|
103
|
+
return text;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function normalizeKind(kind) {
|
|
107
|
+
if (kind !== 'single' && kind !== 'multi') throw invalid('kind must be "single" or "multi"');
|
|
108
|
+
return kind;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Trim a submitted value and report what trimming changed.
|
|
113
|
+
* @param raw - the form field exactly as posted.
|
|
114
|
+
* @param kind - 'single' also drops embedded newlines, which a one-line field
|
|
115
|
+
* cannot express and a pasted key file carries at its end.
|
|
116
|
+
*/
|
|
117
|
+
export function normalizeSubmission(raw, kind) {
|
|
118
|
+
const text = typeof raw === 'string' ? raw : '';
|
|
119
|
+
const stripped = text.trim();
|
|
120
|
+
const value = kind === 'single' ? stripped.replace(/[\r\n]+/g, '') : stripped;
|
|
121
|
+
return { value, trimmed: stripped !== text };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Project a form into the aggregate facts the model may see.
|
|
126
|
+
* The value itself never leaves this module.
|
|
127
|
+
*/
|
|
128
|
+
export function publicResult(form) {
|
|
129
|
+
return {
|
|
130
|
+
status: form.status,
|
|
131
|
+
data: form.data,
|
|
132
|
+
ref: form.ref,
|
|
133
|
+
label: form.label,
|
|
134
|
+
...(form.result === undefined ? {} : {
|
|
135
|
+
length: form.result.length,
|
|
136
|
+
lines: form.result.lines,
|
|
137
|
+
trimmed: form.result.trimmed,
|
|
138
|
+
...(form.result.matchesExpect === undefined ? {} : { matchesExpect: form.result.matchesExpect }),
|
|
139
|
+
}),
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Project a form into one `secret_list` row. */
|
|
144
|
+
export function publicSummary(form) {
|
|
145
|
+
return {
|
|
146
|
+
uuid: form.uuid,
|
|
147
|
+
ref: form.ref,
|
|
148
|
+
label: form.label,
|
|
149
|
+
status: form.status,
|
|
150
|
+
createdAt: new Date(form.createdAt).toISOString(),
|
|
151
|
+
expiresAt: new Date(form.expiresAt).toISOString(),
|
|
152
|
+
data: form.data,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Create the in-memory registry.
|
|
158
|
+
* @param options - `now` and `defaultTtlSeconds` are injectable so tests can
|
|
159
|
+
* move the clock instead of sleeping.
|
|
160
|
+
*/
|
|
161
|
+
export function createFormStore({ now = () => Date.now(), defaultTtlSeconds = DEFAULT_TTL_SECONDS } = {}) {
|
|
162
|
+
const byToken = new Map();
|
|
163
|
+
const byUuid = new Map();
|
|
164
|
+
|
|
165
|
+
const finish = (form, status, result) => {
|
|
166
|
+
form.status = status;
|
|
167
|
+
form.finishedAt = now();
|
|
168
|
+
form.busy = false;
|
|
169
|
+
if (result !== undefined) form.result = result;
|
|
170
|
+
for (const wake of [...form.waiters]) wake();
|
|
171
|
+
form.waiters.clear();
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const expireIfDue = (form) => {
|
|
175
|
+
if (form.status !== STATUS.pending) return form;
|
|
176
|
+
if (now() < form.expiresAt) return form;
|
|
177
|
+
finish(form, STATUS.expired);
|
|
178
|
+
return form;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const store = {
|
|
182
|
+
/** Create a pending form; `target` and `ref` are already validated. */
|
|
183
|
+
create(spec) {
|
|
184
|
+
const createdAt = now();
|
|
185
|
+
const ttlSeconds = clampTtl(spec.ttlSeconds, defaultTtlSeconds);
|
|
186
|
+
const form = {
|
|
187
|
+
uuid: randomUUID(),
|
|
188
|
+
token: randomBytes(32).toString('base64url'),
|
|
189
|
+
ref: spec.ref,
|
|
190
|
+
label: normalizeLabel(spec.label),
|
|
191
|
+
kind: normalizeKind(spec.kind),
|
|
192
|
+
description: normalizeDescription(spec.description),
|
|
193
|
+
target: spec.target,
|
|
194
|
+
allowEmpty: spec.allowEmpty === true,
|
|
195
|
+
expect: normalizeExpect(spec.expect),
|
|
196
|
+
data: normalizeData(spec.data),
|
|
197
|
+
ttlSeconds,
|
|
198
|
+
createdAt,
|
|
199
|
+
expiresAt: createdAt + ttlSeconds * 1000,
|
|
200
|
+
status: STATUS.pending,
|
|
201
|
+
finishedAt: undefined,
|
|
202
|
+
result: undefined,
|
|
203
|
+
busy: false,
|
|
204
|
+
waiters: new Set(),
|
|
205
|
+
};
|
|
206
|
+
byToken.set(form.token, form);
|
|
207
|
+
byUuid.set(form.uuid, form);
|
|
208
|
+
return form;
|
|
209
|
+
},
|
|
210
|
+
|
|
211
|
+
/** Resolve a link token, expiring it first when its window has passed. */
|
|
212
|
+
lookup(token) {
|
|
213
|
+
const form = typeof token === 'string' ? byToken.get(token) : undefined;
|
|
214
|
+
if (form === undefined) return undefined;
|
|
215
|
+
return expireIfDue(form);
|
|
216
|
+
},
|
|
217
|
+
|
|
218
|
+
/** Resolve a form by the uuid the model holds. */
|
|
219
|
+
require(uuid) {
|
|
220
|
+
const form = typeof uuid === 'string' ? byUuid.get(uuid) : undefined;
|
|
221
|
+
if (form === undefined) throw invalid(`unknown secret form ${JSON.stringify(uuid ?? null)}`);
|
|
222
|
+
return expireIfDue(form);
|
|
223
|
+
},
|
|
224
|
+
|
|
225
|
+
/** Every form of this process, oldest first. */
|
|
226
|
+
list() {
|
|
227
|
+
store.sweep();
|
|
228
|
+
return [...byUuid.values()].sort((left, right) => left.createdAt - right.createdAt);
|
|
229
|
+
},
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Start a submission. The caller stores the value and then reports the
|
|
233
|
+
* outcome, so a failed write never reads as saved.
|
|
234
|
+
* @returns `{ outcome }` plus the normalised value when `outcome` is `ready`.
|
|
235
|
+
*/
|
|
236
|
+
beginSubmit(form, raw) {
|
|
237
|
+
expireIfDue(form);
|
|
238
|
+
if (form.status !== STATUS.pending) return { outcome: 'terminal' };
|
|
239
|
+
if (form.busy) return { outcome: 'busy' };
|
|
240
|
+
const { value, trimmed } = normalizeSubmission(raw, form.kind);
|
|
241
|
+
const facts = {
|
|
242
|
+
value,
|
|
243
|
+
trimmed,
|
|
244
|
+
length: [...value].length,
|
|
245
|
+
lines: value === '' ? 0 : value.split('\n').length,
|
|
246
|
+
matchesExpect: form.expect === undefined ? undefined : form.expect.regex.test(value),
|
|
247
|
+
};
|
|
248
|
+
if (value === '' && !form.allowEmpty) return { outcome: 'invalid', ...facts };
|
|
249
|
+
form.busy = true;
|
|
250
|
+
return { outcome: 'ready', empty: value === '', ...facts };
|
|
251
|
+
},
|
|
252
|
+
|
|
253
|
+
/** Mark a submission finished after the value reached its target. */
|
|
254
|
+
completeSubmit(form, submission) {
|
|
255
|
+
finish(
|
|
256
|
+
form,
|
|
257
|
+
submission.empty ? STATUS.empty : STATUS.saved,
|
|
258
|
+
{
|
|
259
|
+
length: submission.length,
|
|
260
|
+
lines: submission.lines,
|
|
261
|
+
trimmed: submission.trimmed,
|
|
262
|
+
matchesExpect: submission.matchesExpect,
|
|
263
|
+
},
|
|
264
|
+
);
|
|
265
|
+
return form;
|
|
266
|
+
},
|
|
267
|
+
|
|
268
|
+
/** Return a form to `pending` after the target refused the write. */
|
|
269
|
+
abortSubmit(form) {
|
|
270
|
+
form.busy = false;
|
|
271
|
+
return form;
|
|
272
|
+
},
|
|
273
|
+
|
|
274
|
+
/** Cancel a pending form; a finished form reports its current status. */
|
|
275
|
+
cancel(form) {
|
|
276
|
+
expireIfDue(form);
|
|
277
|
+
if (form.status === STATUS.pending) finish(form, STATUS.cancelled);
|
|
278
|
+
return form;
|
|
279
|
+
},
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Wait for a form to leave `pending`, at most `ms`.
|
|
283
|
+
* @returns the same form, settled or still pending at the deadline.
|
|
284
|
+
*/
|
|
285
|
+
async settle(form, ms) {
|
|
286
|
+
expireIfDue(form);
|
|
287
|
+
if (form.status !== STATUS.pending || !(ms > 0)) return form;
|
|
288
|
+
await new Promise((resolve) => {
|
|
289
|
+
const done = () => {
|
|
290
|
+
clearTimeout(timer);
|
|
291
|
+
form.waiters.delete(done);
|
|
292
|
+
resolve();
|
|
293
|
+
};
|
|
294
|
+
const timer = setTimeout(done, ms);
|
|
295
|
+
form.waiters.add(done);
|
|
296
|
+
});
|
|
297
|
+
return form;
|
|
298
|
+
},
|
|
299
|
+
|
|
300
|
+
/** Expire overdue forms and drop finished ones past their retention. */
|
|
301
|
+
sweep() {
|
|
302
|
+
const at = now();
|
|
303
|
+
for (const [token, form] of byToken) {
|
|
304
|
+
expireIfDue(form);
|
|
305
|
+
if (form.status === STATUS.pending) continue;
|
|
306
|
+
if (form.finishedAt !== undefined && form.finishedAt + RETAIN_MS > at) continue;
|
|
307
|
+
byToken.delete(token);
|
|
308
|
+
byUuid.delete(form.uuid);
|
|
309
|
+
}
|
|
310
|
+
return store;
|
|
311
|
+
},
|
|
312
|
+
|
|
313
|
+
get size() {
|
|
314
|
+
return byUuid.size;
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
return store;
|
|
318
|
+
}
|