@dr-co/dsh-secret-form 0.3.0 → 0.4.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.
package/lib/page.mjs CHANGED
@@ -129,6 +129,35 @@ button { font: inherit; cursor: pointer; }
129
129
  }
130
130
  .save { background: var(--accent); color: var(--accent-fg); }
131
131
  .cancel { background: transparent; color: var(--fg); border-color: var(--line) !important; }
132
+ input[type=file] {
133
+ padding: 10px;
134
+ border-style: dashed;
135
+ background: var(--bg);
136
+ }
137
+ pre.secret {
138
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
139
+ font-size: 15px;
140
+ line-height: 1.45;
141
+ white-space: pre-wrap;
142
+ word-break: break-all;
143
+ background: var(--card);
144
+ border: 1px solid var(--line);
145
+ border-radius: 10px;
146
+ padding: 12px;
147
+ margin: 0 0 12px;
148
+ max-height: 60vh;
149
+ overflow: auto;
150
+ }
151
+ .copy {
152
+ min-height: 46px;
153
+ padding: 10px 18px;
154
+ font-size: 15px;
155
+ font-weight: 600;
156
+ color: var(--accent);
157
+ background: transparent;
158
+ border: 1px solid var(--accent);
159
+ border-radius: 10px;
160
+ }
132
161
  .notice { border-left: 3px solid var(--accent); padding: 2px 0 2px 12px; }
133
162
  .err { color: var(--danger); }
134
163
  .warn { background: var(--warn-bg); color: var(--warn-fg); border-radius: 10px; padding: 12px; font-size: 15px; }
@@ -198,9 +227,12 @@ function remainingText(messages, remainingSeconds) {
198
227
  */
199
228
  export function renderFormView(form, { actionPath, remainingSeconds, error, warning, locale } = {}) {
200
229
  const { locale: lang, messages } = localized(locale);
230
+ const isFile = form.kind === 'file';
201
231
  const name = form.ref;
202
232
  const required = form.allowEmpty ? '' : ' required';
203
- const field = form.kind === 'single'
233
+ const field = isFile
234
+ ? `<input type="file" id="value" name="file"${required}>`
235
+ : form.kind === 'single'
204
236
  ? `<div class="field"><textarea id="value" name="value" rows="1" class="single masked" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" wrap="off" autofocus${required}></textarea><div class="mask" id="mask" aria-hidden="true" hidden></div></div>`
205
237
  : `<textarea id="value" name="value" rows="8" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" autofocus${required}></textarea>`;
206
238
  const reveal = form.kind === 'single'
@@ -230,9 +262,9 @@ export function renderFormView(form, { actionPath, remainingSeconds, error, warn
230
262
  });
231
263
  })();`);
232
264
  }
233
- if (form.expect !== undefined) {
265
+ if (form.expectSource !== undefined && !isFile) {
234
266
  scripts.push(`(function () {
235
- var pattern = new RegExp(${scriptLiteral(form.expect.source)});
267
+ var pattern = new RegExp(${scriptLiteral(form.expectSource)});
236
268
  var field = document.getElementById('value');
237
269
  var box = document.getElementById('expect-warning');
238
270
  if (!field || !box) return;
@@ -249,16 +281,16 @@ export function renderFormView(form, { actionPath, remainingSeconds, error, warn
249
281
  form.description === undefined ? '' : `<p class="hint">${escapeHtml(form.description)}</p>`,
250
282
  error === undefined ? '' : `<p class="err">${escapeHtml(error)}</p>`,
251
283
  warning === undefined ? '' : `<p class="warn">${escapeHtml(warning)}</p>`,
252
- `<form method="post" action="${escapeHtml(actionPath)}" autocomplete="off">`,
284
+ `<form method="post" action="${escapeHtml(actionPath)}"${isFile ? ' enctype="multipart/form-data"' : ''} autocomplete="off">`,
253
285
  // The ref is an identifier such as OPENAI_API_KEY: it is shown as is, next
254
286
  // to the translated word for the thing being filled in.
255
- `<label for="value">${escapeHtml(messages.field)} <span class="hint">${escapeHtml(name)}</span></label>`,
287
+ `<label for="value">${escapeHtml(isFile ? messages.fileField : messages.field)} <span class="hint">${escapeHtml(name)}</span></label>`,
256
288
  // The locale travels with the post so the outcome page answers in the
257
289
  // language the form was read in, whatever the next request's header says.
258
290
  `<input type="hidden" name="lang" value="${escapeHtml(lang)}">`,
259
291
  field,
260
292
  reveal,
261
- form.expect === undefined
293
+ form.expectSource === undefined || isFile
262
294
  ? ''
263
295
  : `<p class="warn" id="expect-warning" hidden>${escapeHtml(messages.mismatch)}</p>`,
264
296
  `<div class="actions">`,
@@ -294,6 +326,81 @@ export function renderNotice(kind, note, { locale } = {}) {
294
326
  return shell({ title: notice.title, body: body.join('\n'), locale: lang });
295
327
  }
296
328
 
329
+ /**
330
+ * Render the page of an outbound secret: a link that may be opened any number of
331
+ * times, and a button that works exactly once.
332
+ * @param share - pending share.
333
+ * @param options - `actionPath` is where the reveal posts, `remainingSeconds`
334
+ * feeds the expiry line, `error` and `warning` are page-level messages,
335
+ * `locale` picks the wording.
336
+ */
337
+ export function renderShareView(share, { actionPath, remainingSeconds, error, warning, locale } = {}) {
338
+ const { locale: lang, messages } = localized(locale);
339
+ const remaining = remainingText(messages, remainingSeconds);
340
+ const body = [
341
+ `<h1>${escapeHtml(share.label)}</h1>`,
342
+ share.description === undefined ? '' : `<p class="hint">${escapeHtml(share.description)}</p>`,
343
+ error === undefined ? '' : `<p class="err">${escapeHtml(error)}</p>`,
344
+ warning === undefined ? '' : `<p class="warn">${escapeHtml(warning)}</p>`,
345
+ `<form method="post" action="${escapeHtml(actionPath)}" autocomplete="off">`,
346
+ `<input type="hidden" name="lang" value="${escapeHtml(lang)}">`,
347
+ `<div class="actions">`,
348
+ `<button class="save" type="submit" name="action" value="reveal">${escapeHtml(messages.revealSecret)}</button>`,
349
+ `</div>`,
350
+ `</form>`,
351
+ remaining === '' ? '' : `<p class="meta">${escapeHtml(format(messages.shareNote, { time: remaining }))}</p>`,
352
+ ].filter((part) => part !== '');
353
+ return shell({
354
+ title: share.label,
355
+ body: body.join('\n'),
356
+ locale: lang,
357
+ });
358
+ }
359
+
360
+ /**
361
+ * Render the one page that ever shows an outbound secret. It is produced once,
362
+ * after the reveal burned the link, and carries the copy button.
363
+ * @param share - the share that was just revealed.
364
+ * @param options - `value` is the decrypted secret, `locale` picks the wording.
365
+ */
366
+ export function renderRevealedView(share, { value, locale } = {}) {
367
+ const { locale: lang, messages } = localized(locale);
368
+ const script = `(function () {
369
+ var button = document.getElementById('copy');
370
+ var box = document.getElementById('secret');
371
+ if (!button || !box) return;
372
+ var done = function () { button.textContent = ${scriptLiteral(messages.copied)}; };
373
+ var fallback = function () {
374
+ var range = document.createRange();
375
+ range.selectNodeContents(box);
376
+ var selection = window.getSelection();
377
+ if (!selection) return;
378
+ selection.removeAllRanges();
379
+ selection.addRange(range);
380
+ try { document.execCommand('copy'); done(); } catch (error) {}
381
+ };
382
+ button.addEventListener('click', function () {
383
+ if (navigator.clipboard && navigator.clipboard.writeText) {
384
+ navigator.clipboard.writeText(box.textContent || '').then(done, fallback);
385
+ return;
386
+ }
387
+ fallback();
388
+ });
389
+ })();`;
390
+ const body = [
391
+ `<h1>${escapeHtml(share.label)}</h1>`,
392
+ `<pre class="secret" id="secret">${escapeHtml(value)}</pre>`,
393
+ `<button class="copy" type="button" id="copy">${escapeHtml(messages.copy)}</button>`,
394
+ `<p class="meta">${escapeHtml(messages.burnNote)}</p>`,
395
+ ].filter((part) => part !== '');
396
+ return shell({
397
+ title: share.label,
398
+ body: body.join('\n'),
399
+ script,
400
+ locale: lang,
401
+ });
402
+ }
403
+
297
404
  /** Send an HTML response with the security headers and an exact length. */
298
405
  export function sendHtml(res, status, html, { head = false } = {}) {
299
406
  const body = Buffer.from(html, 'utf8');
package/lib/shares.mjs ADDED
@@ -0,0 +1,312 @@
1
+ // The outbound half: a secret the model hands to the human.
2
+ //
3
+ // The link may be opened any number of times — a link that stops working
4
+ // because the browser refreshed is worse than useless — but the reveal button
5
+ // works exactly once. The value is written encrypted with a one-shot AES-256-GCM
6
+ // key that lives in its own row; revealing reads both rows, hands the value to
7
+ // the one page, and deletes them. Expiry and cancellation delete them too, so
8
+ // after the link is spent there is nothing left on disk to decrypt.
9
+ //
10
+ // The key next to the ciphertext protects a copy of the database that left the
11
+ // machine with only one of the two rows in it, or a single row surviving a crash
12
+ // mid-delete. It is not a defence against someone who can read both rows while
13
+ // the link is still open — that person owns the host anyway.
14
+ import { createCipheriv, createDecipheriv, randomBytes, randomUUID } from 'node:crypto';
15
+
16
+ import {
17
+ MAX_TTL_SECONDS,
18
+ clampTtl,
19
+ hashToken,
20
+ normalizeData,
21
+ normalizeDescription,
22
+ normalizeLabel,
23
+ } from './forms.mjs';
24
+
25
+ export const SHARE_STATUS = Object.freeze({
26
+ pending: 'pending',
27
+ revealed: 'revealed',
28
+ cancelled: 'cancelled',
29
+ expired: 'expired',
30
+ });
31
+
32
+ export const SHARE_ALG = 'aes-256-gcm';
33
+ export const SHARE_KINDS = Object.freeze(['single', 'multi']);
34
+
35
+ function invalid(message) {
36
+ const error = new TypeError(message);
37
+ error.code = 'secret-share-invalid';
38
+ return error;
39
+ }
40
+
41
+ function normalizeShareKind(kind) {
42
+ if (!SHARE_KINDS.includes(kind)) throw invalid(`kind must be one of: ${SHARE_KINDS.join(', ')}`);
43
+ return kind;
44
+ }
45
+
46
+ /** Encrypt one value; the key is returned separately so it can get its own row. */
47
+ export function sealValue(value) {
48
+ const key = randomBytes(32);
49
+ const iv = randomBytes(12);
50
+ const cipher = createCipheriv(SHARE_ALG, key, iv);
51
+ const ciphertext = Buffer.concat([cipher.update(String(value), 'utf8'), cipher.final()]);
52
+ return {
53
+ alg: SHARE_ALG,
54
+ key: key.toString('base64'),
55
+ iv: iv.toString('base64'),
56
+ tag: cipher.getAuthTag().toString('base64'),
57
+ ciphertext: ciphertext.toString('base64'),
58
+ };
59
+ }
60
+
61
+ /** Decrypt a sealed value; a missing or tampered part throws. */
62
+ export function openValue({ alg, key, iv, tag, ciphertext }) {
63
+ if (alg !== SHARE_ALG) throw new Error(`unsupported cipher ${String(alg)}`);
64
+ const decipher = createDecipheriv(SHARE_ALG, Buffer.from(key, 'base64'), Buffer.from(iv, 'base64'));
65
+ decipher.setAuthTag(Buffer.from(tag, 'base64'));
66
+ return Buffer.concat([decipher.update(Buffer.from(ciphertext, 'base64')), decipher.final()]).toString('utf8');
67
+ }
68
+
69
+ function parseJson(text, fallback) {
70
+ if (typeof text !== 'string' || text === '') return fallback;
71
+ try {
72
+ return JSON.parse(text);
73
+ } catch {
74
+ return fallback;
75
+ }
76
+ }
77
+
78
+ function rowToShare(row) {
79
+ return {
80
+ uuid: row.uuid,
81
+ label: row.label,
82
+ kind: row.kind,
83
+ description: row.description ?? undefined,
84
+ data: parseJson(row.data, {}),
85
+ source: row.source,
86
+ fileName: row.file_name ?? undefined,
87
+ ttlSeconds: row.ttl_seconds,
88
+ createdAt: row.created_at,
89
+ expiresAt: row.expires_at,
90
+ status: row.status,
91
+ views: row.views,
92
+ revealedAt: row.revealed_at ?? undefined,
93
+ finishedAt: row.finished_at ?? undefined,
94
+ sessionId: row.session_id ?? null,
95
+ notify: row.notify === 1,
96
+ notifiedAt: row.notified_at ?? undefined,
97
+ };
98
+ }
99
+
100
+ /** Project a share into one `secret_list` row. */
101
+ export function publicShareSummary(share) {
102
+ return {
103
+ uuid: share.uuid,
104
+ type: 'share',
105
+ label: share.label,
106
+ status: share.status,
107
+ views: share.views,
108
+ createdAt: new Date(share.createdAt).toISOString(),
109
+ expiresAt: new Date(share.expiresAt).toISOString(),
110
+ data: share.data,
111
+ };
112
+ }
113
+
114
+ /** Project a share into the `secret_result` answer. */
115
+ export function publicShareResult(share) {
116
+ return {
117
+ type: 'share',
118
+ status: share.status,
119
+ label: share.label,
120
+ views: share.views,
121
+ data: share.data,
122
+ ...(share.revealedAt === undefined ? {} : { revealedAt: new Date(share.revealedAt).toISOString() }),
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Create the outbound registry over an open database.
128
+ * @param options - `db` (opened by lib/db.mjs), `now`, `defaultTtlSeconds`.
129
+ */
130
+ export function createShareStore({ db, now = () => Date.now(), defaultTtlSeconds = 300 } = {}) {
131
+ if (db === undefined || typeof db.prepare !== 'function') {
132
+ throw new TypeError('dsh-secret-form: the share store needs an open database');
133
+ }
134
+ const sql = {
135
+ insert: db.prepare(`INSERT INTO share (
136
+ uuid, token_hash, label, kind, description, data, source, file_name,
137
+ ttl_seconds, created_at, expires_at, status, views, session_id, notify
138
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, ?, ?)`),
139
+ insertSecret: db.prepare('INSERT INTO share_secret (uuid, alg, iv, tag, ciphertext) VALUES (?, ?, ?, ?, ?)'),
140
+ insertKey: db.prepare('INSERT INTO share_key (uuid, key) VALUES (?, ?)'),
141
+ byToken: db.prepare('SELECT * FROM share WHERE token_hash = ?'),
142
+ byUuid: db.prepare('SELECT * FROM share WHERE uuid = ?'),
143
+ all: db.prepare('SELECT * FROM share ORDER BY created_at'),
144
+ secret: db.prepare('SELECT * FROM share_secret WHERE uuid = ?'),
145
+ key: db.prepare('SELECT * FROM share_key WHERE uuid = ?'),
146
+ dropSecret: db.prepare('DELETE FROM share_secret WHERE uuid = ?'),
147
+ dropKey: db.prepare('DELETE FROM share_key WHERE uuid = ?'),
148
+ due: db.prepare("UPDATE share SET status = 'expired', finished_at = ? WHERE status = 'pending' AND expires_at <= ?"),
149
+ dueWithSecret: db.prepare("SELECT uuid FROM share WHERE status = 'expired'"),
150
+ purge: db.prepare('DELETE FROM share WHERE status <> ? AND finished_at IS NOT NULL AND finished_at <= ?'),
151
+ view: db.prepare('UPDATE share SET views = views + 1 WHERE uuid = ?'),
152
+ reveal: db.prepare("UPDATE share SET status = 'revealed', revealed_at = ?, finished_at = ? WHERE uuid = ? AND status = 'pending'"),
153
+ cancel: db.prepare("UPDATE share SET status = 'cancelled', finished_at = ? WHERE uuid = ? AND status = 'pending'"),
154
+ notified: db.prepare('UPDATE share SET notified_at = ? WHERE uuid = ?'),
155
+ };
156
+
157
+ const dropMaterial = (uuid) => {
158
+ sql.dropSecret.run(uuid);
159
+ sql.dropKey.run(uuid);
160
+ };
161
+
162
+ const expireIfDue = (share) => {
163
+ if (share.status !== SHARE_STATUS.pending) return share;
164
+ if (now() < share.expiresAt) return share;
165
+ const at = now();
166
+ db.prepare("UPDATE share SET status = 'expired', finished_at = ? WHERE uuid = ? AND status = 'pending'").run(at, share.uuid);
167
+ dropMaterial(share.uuid);
168
+ share.status = SHARE_STATUS.expired;
169
+ share.finishedAt = at;
170
+ return share;
171
+ };
172
+
173
+ const store = {
174
+ /**
175
+ * Create a pending share. `value` is sealed here and never kept in memory.
176
+ * @returns the share with its plain token, for the caller to build the link.
177
+ */
178
+ create(spec) {
179
+ const createdAt = now();
180
+ const ttlSeconds = clampTtl(spec.ttlSeconds, defaultTtlSeconds);
181
+ const token = randomBytes(32).toString('base64url');
182
+ const share = {
183
+ uuid: randomUUID(),
184
+ token,
185
+ label: normalizeLabel(spec.label),
186
+ kind: normalizeShareKind(spec.kind),
187
+ description: normalizeDescription(spec.description),
188
+ data: normalizeData(spec.data),
189
+ source: typeof spec.source === 'string' ? spec.source : 'file',
190
+ fileName: typeof spec.fileName === 'string' && spec.fileName !== '' ? spec.fileName : undefined,
191
+ ttlSeconds,
192
+ createdAt,
193
+ expiresAt: createdAt + ttlSeconds * 1000,
194
+ status: SHARE_STATUS.pending,
195
+ views: 0,
196
+ sessionId: typeof spec.sessionId === 'string' && spec.sessionId !== '' ? spec.sessionId : null,
197
+ notify: spec.notify === true,
198
+ };
199
+ if (share.expiresAt - createdAt > MAX_TTL_SECONDS * 1000) throw invalid('ttlSeconds is out of range');
200
+ const sealed = sealValue(spec.value);
201
+ sql.insert.run(
202
+ share.uuid,
203
+ hashToken(token),
204
+ share.label,
205
+ share.kind,
206
+ share.description ?? null,
207
+ JSON.stringify(share.data),
208
+ share.source,
209
+ share.fileName ?? null,
210
+ share.ttlSeconds,
211
+ share.createdAt,
212
+ share.expiresAt,
213
+ share.sessionId,
214
+ share.notify ? 1 : 0,
215
+ );
216
+ sql.insertSecret.run(share.uuid, sealed.alg, sealed.iv, sealed.tag, sealed.ciphertext);
217
+ sql.insertKey.run(share.uuid, sealed.key);
218
+ return share;
219
+ },
220
+
221
+ /** Resolve a link token, expiring it first when its window has passed. */
222
+ lookup(token) {
223
+ if (typeof token !== 'string' || token === '') return undefined;
224
+ const row = sql.byToken.get(hashToken(token));
225
+ if (row === undefined) return undefined;
226
+ return expireIfDue(rowToShare(row));
227
+ },
228
+
229
+ /** Resolve a share by the uuid the model holds. */
230
+ require(uuid) {
231
+ const row = typeof uuid === 'string' ? sql.byUuid.get(uuid) : undefined;
232
+ if (row === undefined) throw invalid(`unknown secret link ${JSON.stringify(uuid ?? null)}`);
233
+ return expireIfDue(rowToShare(row));
234
+ },
235
+
236
+ /** Every share the database still holds, oldest first. */
237
+ list() {
238
+ store.sweep();
239
+ return sql.all.all().map(rowToShare);
240
+ },
241
+
242
+ /** Count one page open. Cheap, and it tells the model whether anyone looked. */
243
+ countView(share) {
244
+ if (share.status !== SHARE_STATUS.pending) return share;
245
+ sql.view.run(share.uuid);
246
+ share.views += 1;
247
+ return share;
248
+ },
249
+
250
+ /**
251
+ * Burn the link and hand the value to the one page that asked for it.
252
+ * @returns `{ status, value }`; `value` is present only on a successful reveal.
253
+ */
254
+ reveal(share) {
255
+ expireIfDue(share);
256
+ if (share.status !== SHARE_STATUS.pending) return { status: share.status };
257
+ const at = now();
258
+ const changed = sql.reveal.run(at, at, share.uuid);
259
+ if (changed.changes !== 1) return { status: store.require(share.uuid).status };
260
+ share.status = SHARE_STATUS.revealed;
261
+ share.revealedAt = at;
262
+ share.finishedAt = at;
263
+ const secretRow = sql.secret.get(share.uuid);
264
+ const keyRow = sql.key.get(share.uuid);
265
+ dropMaterial(share.uuid);
266
+ if (secretRow === undefined || keyRow === undefined) {
267
+ throw new Error('the sealed value is missing: it was already revealed or removed');
268
+ }
269
+ return {
270
+ status: SHARE_STATUS.revealed,
271
+ value: openValue({ ...secretRow, key: keyRow.key }),
272
+ };
273
+ },
274
+
275
+ /** Cancel a pending share; a finished one reports its current status. */
276
+ cancel(share) {
277
+ expireIfDue(share);
278
+ if (share.status !== SHARE_STATUS.pending) return share;
279
+ const at = now();
280
+ sql.cancel.run(at, share.uuid);
281
+ dropMaterial(share.uuid);
282
+ share.status = SHARE_STATUS.cancelled;
283
+ share.finishedAt = at;
284
+ return share;
285
+ },
286
+
287
+ /** Record that the note about this share was delivered. */
288
+ markNotified(share, at = now()) {
289
+ share.notifiedAt = at;
290
+ sql.notified.run(at, share.uuid);
291
+ return share;
292
+ },
293
+
294
+ /** Expire overdue shares and drop finished ones past their retention. */
295
+ sweep({ retainMs = 3_600_000 } = {}) {
296
+ const at = now();
297
+ sql.due.run(at, at);
298
+ // A share that expired while the process was down still has its sealed
299
+ // rows: tear them down now rather than waiting for the purge.
300
+ for (const row of sql.dueWithSecret.all()) {
301
+ if (sql.secret.get(row.uuid) !== undefined || sql.key.get(row.uuid) !== undefined) dropMaterial(row.uuid);
302
+ }
303
+ sql.purge.run(SHARE_STATUS.pending, at - retainMs);
304
+ return store;
305
+ },
306
+
307
+ get size() {
308
+ return db.prepare('SELECT COUNT(*) AS n FROM share').get().n;
309
+ },
310
+ };
311
+ return store;
312
+ }
package/lib/upload.mjs ADDED
@@ -0,0 +1,179 @@
1
+ // File uploads without a framework.
2
+ //
3
+ // A `kind: "file"` form is the one place where the browser sends
4
+ // `multipart/form-data` here, so the parser handles exactly that: one boundary,
5
+ // parts made of headers and bytes, no nested encodings, no chunked streaming.
6
+ // The body is already bounded by the caller, which is what makes a whole-buffer
7
+ // parse acceptable.
8
+ import { createHash } from 'node:crypto';
9
+ import { chmod, mkdir, open, rename, rm } from 'node:fs/promises';
10
+ import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path';
11
+
12
+ export const DEFAULT_MAX_UPLOAD_BYTES = 64 * 1024 * 1024;
13
+
14
+ const CRLF = Buffer.from('\r\n');
15
+ const HEADER_END = Buffer.from('\r\n\r\n');
16
+
17
+ /** Pull the boundary out of a `multipart/form-data` content type. */
18
+ export function boundaryOf(contentType) {
19
+ if (typeof contentType !== 'string') return undefined;
20
+ const [type, ...params] = contentType.split(';');
21
+ if (type.trim().toLowerCase() !== 'multipart/form-data') return undefined;
22
+ for (const param of params) {
23
+ const index = param.indexOf('=');
24
+ if (index === -1) continue;
25
+ if (param.slice(0, index).trim().toLowerCase() !== 'boundary') continue;
26
+ let value = param.slice(index + 1).trim();
27
+ if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
28
+ return value === '' ? undefined : value;
29
+ }
30
+ return undefined;
31
+ }
32
+
33
+ function parseHeaders(text) {
34
+ // latin1 keeps the bytes of a filename intact for the ASCII case; the
35
+ // RFC 5987 form is decoded below when the browser sends it.
36
+ const headers = {};
37
+ for (const line of text.split('\r\n')) {
38
+ const index = line.indexOf(':');
39
+ if (index === -1) continue;
40
+ headers[line.slice(0, index).trim().toLowerCase()] = line.slice(index + 1).trim();
41
+ }
42
+ return headers;
43
+ }
44
+
45
+ function dispositionParams(value) {
46
+ const params = {};
47
+ for (const part of String(value).split(';').slice(1)) {
48
+ const index = part.indexOf('=');
49
+ if (index === -1) continue;
50
+ const key = part.slice(0, index).trim().toLowerCase();
51
+ let raw = part.slice(index + 1).trim();
52
+ if (raw.startsWith('"') && raw.endsWith('"')) raw = raw.slice(1, -1);
53
+ params[key] = raw;
54
+ }
55
+ return params;
56
+ }
57
+
58
+ function decodeExtended(value) {
59
+ // `UTF-8''%D0%B8%D0%BC%D1%8F` — the charset is always UTF-8 in practice.
60
+ const match = /^([^']*)'[^']*'(.*)$/.exec(String(value));
61
+ if (match === null) return undefined;
62
+ try {
63
+ return decodeURIComponent(match[2]);
64
+ } catch {
65
+ return undefined;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Parse a bounded multipart body.
71
+ * @returns `{ fields: Map<string,string>, files: Array<{name, filename, contentType, data}> }`
72
+ */
73
+ export function parseMultipart(buffer, boundary) {
74
+ const fields = new Map();
75
+ const files = [];
76
+ if (typeof boundary !== 'string' || boundary === '') return { fields, files };
77
+ const delimiter = Buffer.from(`--${boundary}`);
78
+ let cursor = buffer.indexOf(delimiter);
79
+ if (cursor === -1) return { fields, files };
80
+ while (cursor !== -1) {
81
+ let start = cursor + delimiter.length;
82
+ // `--` straight after the delimiter closes the body.
83
+ if (buffer[start] === 0x2d && buffer[start + 1] === 0x2d) break;
84
+ if (buffer[start] === 0x0d && buffer[start + 1] === 0x0a) start += 2;
85
+ const next = buffer.indexOf(delimiter, start);
86
+ if (next === -1) break;
87
+ let end = next;
88
+ if (end - 2 >= start && buffer[end - 2] === 0x0d && buffer[end - 1] === 0x0a) end -= 2;
89
+ const part = buffer.subarray(start, end);
90
+ const split = part.indexOf(HEADER_END);
91
+ const headerText = (split === -1 ? part : part.subarray(0, split)).toString('utf8');
92
+ const data = split === -1 ? Buffer.alloc(0) : part.subarray(split + HEADER_END.length);
93
+ const headers = parseHeaders(headerText);
94
+ const disposition = headers['content-disposition'];
95
+ if (typeof disposition === 'string') {
96
+ const params = dispositionParams(disposition);
97
+ const name = params.name;
98
+ if (name !== undefined) {
99
+ if (params.filename !== undefined || params['filename*'] !== undefined) {
100
+ const filename = params['filename*'] !== undefined
101
+ ? (decodeExtended(params['filename*']) ?? params.filename ?? '')
102
+ : params.filename;
103
+ files.push({ name, filename, contentType: headers['content-type'], data: Buffer.from(data) });
104
+ } else {
105
+ fields.set(name, data.toString('utf8'));
106
+ }
107
+ }
108
+ }
109
+ cursor = next;
110
+ }
111
+ return { fields, files };
112
+ }
113
+
114
+ /**
115
+ * Reduce a browser-supplied file name to something safe to create in a
116
+ * directory the model chose.
117
+ */
118
+ export function safeFileName(name, fallback = 'upload.bin') {
119
+ let text = String(name ?? '');
120
+ // Some browsers (and every Windows one) send a full path.
121
+ text = text.split(/[\\/]/).pop() ?? '';
122
+ text = text.replace(/[\u0000-\u001f\u007f]/g, '').trim();
123
+ if (text === '' || text === '.' || text === '..') return fallback;
124
+ if (text.length > 200) text = text.slice(0, 200);
125
+ return text;
126
+ }
127
+
128
+ /** Validate the `upload.dir` of a file form: an absolute directory path. */
129
+ export function normalizeUploadDir(dir) {
130
+ if (typeof dir !== 'string' || dir.trim() === '') throw new TypeError('upload.dir must be a non-empty string');
131
+ if (dir.includes('\0')) throw new TypeError('upload.dir must not contain a NUL byte');
132
+ if (!isAbsolute(dir)) throw new TypeError(`upload.dir must be an absolute path, got ${JSON.stringify(dir)}`);
133
+ return resolve(dir);
134
+ }
135
+
136
+ // A half-received file is worse than a failed form: write beside the target,
137
+ // flush, then rename over it in one step.
138
+ async function writeAtomic(file, data) {
139
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
140
+ const temp = join(dirname(file), `.${basename(file)}.${Date.now().toString(36)}.part`);
141
+ let handle;
142
+ try {
143
+ handle = await open(temp, 'wx', 0o600);
144
+ await handle.writeFile(data);
145
+ await handle.sync();
146
+ await handle.close();
147
+ handle = undefined;
148
+ await rename(temp, file);
149
+ } catch (error) {
150
+ if (handle !== undefined) await handle.close().catch(() => {});
151
+ await rm(temp, { force: true }).catch(() => {});
152
+ throw error;
153
+ }
154
+ await chmod(file, 0o600);
155
+ }
156
+
157
+ /**
158
+ * Store an uploaded part inside the directory the form was created with.
159
+ * @param input - `dir`, the requested `name` (optional), and the received bytes.
160
+ * @returns facts about the stored file, never its content.
161
+ */
162
+ export async function saveUpload({ dir, name, data }) {
163
+ const root = normalizeUploadDir(dir);
164
+ const fileName = safeFileName(name, 'upload.bin');
165
+ const path = join(root, fileName);
166
+ const resolved = resolve(path);
167
+ // `safeFileName` already drops separators, but a resolved-path check is the
168
+ // one that actually bounds the write.
169
+ if (resolved !== path || !resolved.startsWith(`${root}${sep}`)) {
170
+ throw new TypeError(`upload name ${JSON.stringify(name)} escapes ${root}`);
171
+ }
172
+ await writeAtomic(resolved, data);
173
+ return {
174
+ path: resolved,
175
+ fileName,
176
+ size: data.length,
177
+ sha256: createHash('sha256').update(data).digest('hex'),
178
+ };
179
+ }
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "Secret forms",
4
- "description": "One-time web links where the human types a secret into a form instead of the chat; the value lands in the credential store or a file."
3
+ "title": "Secret links",
4
+ "description": "One-time web links in both directions: the human types a secret into a form instead of the chat, and the model hands one over through a link whose reveal button works once. Durable in SQLite, with file uploads and a note to the session that asked."
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dr-co/dsh-secret-form",
3
- "version": "0.3.0",
4
- "description": "One-time secret links for DeepSeek Harness: the model asks, the human types into a web form, the value lands in the credential store or a file.",
3
+ "version": "0.4.1",
4
+ "description": "Secret links in both directions for DeepSeek Harness: the human types a secret into a one-time form, or the model hands one over through a link whose reveal button works exactly once. Durable in SQLite, with file uploads and a note to the session that asked.",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "exports": {
@@ -28,7 +28,7 @@
28
28
  "credentials"
29
29
  ],
30
30
  "engines": {
31
- "node": ">=22"
31
+ "node": ">=22.13.0"
32
32
  },
33
33
  "publishConfig": {
34
34
  "access": "public"