@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/index.mjs CHANGED
@@ -1,15 +1,29 @@
1
1
  // One-time secret links for DeepSeek Harness.
2
2
  //
3
- // The model never receives the secret. It asks for a link, a human opens it and
4
- // types the value into the browser, and the plugin writes it straight into the
5
- // credential store or a document file. The model only learns aggregate facts
6
- // (status, length, line count), because anything it can read ends up in the
7
- // session log, the transcript, and every provider request built from them.
3
+ // Two directions, one surface:
8
4
  //
9
- // Two HTTP surfaces on the Web GUI host: `GET <prefix>/<token>` renders the
10
- // form and `POST <prefix>/<token>` accepts it as form-urlencoded. The token is
11
- // the credential — single use, swept from memory by TTL.
5
+ // * `secret_create` asks the human for a value (or a file). The value never
6
+ // reaches the model: the page writes it straight into the credential store
7
+ // or a document file, and the model learns aggregate facts only.
8
+ // * `secret_share` hands a secret to the human: the link may be opened many
9
+ // times, the reveal button works exactly once, and the sealed value is
10
+ // deleted as soon as it was shown.
11
+ //
12
+ // Both directions live in SQLite (`lib/db.mjs`), so a form created before a
13
+ // restart still accepts its submission afterwards, and its token is stored as a
14
+ // hash. A finished direction wakes the session that asked for it through the
15
+ // schedule service (`lib/notify.mjs`) — the same route the graceful-restart
16
+ // plugin uses for its post-restart note.
17
+ //
18
+ // Two HTTP surfaces on the Web GUI host: `GET <prefix>/<token>` renders the page
19
+ // and `POST <prefix>/<token>` accepts it (urlencoded, or multipart for a file).
20
+ // The token is the capability: single use for a form, single reveal for a share.
21
+ import { readFile } from 'node:fs/promises';
22
+ import { basename, resolve } from 'node:path';
23
+
24
+ import { closeDatabase, defaultDatabasePath, openDatabase } from './lib/db.mjs';
12
25
  import {
26
+ KINDS,
13
27
  MAX_WAIT_SECONDS,
14
28
  STATUS,
15
29
  clampTtl,
@@ -19,28 +33,55 @@ import {
19
33
  publicSummary,
20
34
  } from './lib/forms.mjs';
21
35
  import { SUPPORTED_LOCALES, format, messagesFor, normalizeLocale, resolveLocale } from './lib/i18n.mjs';
22
- import { renderFormView, renderNotice, sendHtml, sendText } from './lib/page.mjs';
36
+ import { NOTE_KINDS, createNotifier } from './lib/notify.mjs';
37
+ import {
38
+ renderFormView,
39
+ renderNotice,
40
+ renderRevealedView,
41
+ renderShareView,
42
+ sendHtml,
43
+ sendText,
44
+ } from './lib/page.mjs';
45
+ import { SHARE_STATUS, createShareStore, publicShareResult, publicShareSummary } from './lib/shares.mjs';
23
46
  import { assertRefForTarget, normalizeTarget, writeSecret } from './lib/targets.mjs';
47
+ import { DEFAULT_MAX_UPLOAD_BYTES, boundaryOf, normalizeUploadDir, parseMultipart, saveUpload } from './lib/upload.mjs';
24
48
 
25
49
  export const name = 'dsh-secret-form';
26
50
  // A form without a page cannot be filled in, and a form without tools cannot be
27
- // requested. `credentials` is resolved lazily: a host that only writes to files
28
- // should not be forced to mount a credential provider.
51
+ // requested. Everything else is optional and looked up lazily: `credentials` is
52
+ // needed only for a credential target or a credential share, `schedule` only to
53
+ // wake a session with a note.
29
54
  export const inject = ['tools', 'webServer'];
30
55
 
31
56
  const DEFAULT_ROUTE_PREFIX = '/secret';
32
57
  const DEFAULT_TTL_SECONDS = 300;
33
58
  const DEFAULT_LOCALE = 'en';
59
+ const DEFAULT_LANGUAGE = 'en';
60
+ const DEFAULT_RETAIN_SECONDS = 3600;
34
61
  const MAX_BODY_BYTES = 64 * 1024;
62
+ const MAX_SHARE_SECRET_BYTES = 256 * 1024;
63
+ const LANGUAGES = Object.freeze(['en', 'ru', 'zh']);
35
64
 
36
65
  function invalidConfig(message) {
37
66
  return new TypeError(`dsh-secret-form: ${message}`);
38
67
  }
39
68
 
69
+ function booleanOr(value, fallback) {
70
+ return typeof value === 'boolean' ? value : fallback;
71
+ }
72
+
73
+ /** Clamp a number into a window; a non-number is a config error, not a default. */
74
+ function clampNumber(value, { min, max, fallback, field }) {
75
+ if (value === undefined || value === null) return fallback;
76
+ if (typeof value !== 'number' || !Number.isFinite(value)) throw invalidConfig(`${field} must be a number`);
77
+ return Math.min(max, Math.max(min, Math.round(value)));
78
+ }
79
+
40
80
  /**
41
81
  * Validate the plugin config.
42
- * @param config - `routePrefix` (default `/secret`), `defaultTtlSeconds`
43
- * (default 300, clamped to 30..3600) and `defaultLocale` (default `en`).
82
+ * @param config - `routePrefix`, `defaultTtlSeconds`, `defaultLocale`,
83
+ * `publicUrl`, `database`, `language`, `notify`, `maxUploadBytes` and
84
+ * `retainSeconds`.
44
85
  */
45
86
  export function normalizeConfig(config = {}) {
46
87
  const prefixRaw = config?.routePrefix ?? DEFAULT_ROUTE_PREFIX;
@@ -76,7 +117,33 @@ export function normalizeConfig(config = {}) {
76
117
  if (defaultLocale === undefined) {
77
118
  throw invalidConfig(`defaultLocale must be one of: ${SUPPORTED_LOCALES.join(', ')}`);
78
119
  }
79
- return { routePrefix: prefix, defaultTtlSeconds: ttl, publicUrl, defaultLocale };
120
+ const databaseRaw = config?.database ?? defaultDatabasePath();
121
+ if (typeof databaseRaw !== 'string' || databaseRaw.trim() === '') {
122
+ throw invalidConfig('database must be a file path');
123
+ }
124
+ const languageRaw = String(config?.language ?? DEFAULT_LANGUAGE).trim().toLowerCase();
125
+ const language = LANGUAGES.includes(languageRaw) ? languageRaw : DEFAULT_LANGUAGE;
126
+ return {
127
+ routePrefix: prefix,
128
+ defaultTtlSeconds: ttl,
129
+ publicUrl,
130
+ defaultLocale,
131
+ database: resolve(databaseRaw.trim()),
132
+ language,
133
+ notify: booleanOr(config?.notify, true),
134
+ maxUploadBytes: clampNumber(config?.maxUploadBytes, {
135
+ min: 1024,
136
+ max: 1024 * 1024 * 1024,
137
+ fallback: DEFAULT_MAX_UPLOAD_BYTES,
138
+ field: 'maxUploadBytes',
139
+ }),
140
+ retainSeconds: clampNumber(config?.retainSeconds, {
141
+ min: 60,
142
+ max: 7 * 24 * 3600,
143
+ fallback: DEFAULT_RETAIN_SECONDS,
144
+ field: 'retainSeconds',
145
+ }),
146
+ };
80
147
  }
81
148
 
82
149
  function resolveLogger(ctx) {
@@ -91,10 +158,10 @@ function resolveLogger(ctx) {
91
158
  return ctx?.logger ?? console;
92
159
  }
93
160
 
94
- // Only the first eight characters of a token are ever logged: the rest is the
95
- // capability itself.
96
- function tokenTag(token) {
97
- return typeof token === 'string' ? token.slice(0, 8) : '????????';
161
+ // Only the first eight characters of an identifier are ever logged: a token's
162
+ // tail is the capability itself, so records are logged by their uuid.
163
+ function recordTag(record) {
164
+ return typeof record?.uuid === 'string' ? record.uuid.slice(0, 8) : '????????';
98
165
  }
99
166
 
100
167
  function resolveOrigin(ctx, settings) {
@@ -110,12 +177,94 @@ function resolveOrigin(ctx, settings) {
110
177
  }
111
178
  }
112
179
 
180
+ // Where a submitted value went, said in the language of the note that carries
181
+ // it: a Russian note with an English half-sentence reads like a bug.
182
+ const TARGET_PHRASES = {
183
+ en: {
184
+ credentials: (ref) => `the credential store as ${ref}`,
185
+ upload: (dir) => `the directory ${dir}`,
186
+ file: (path, format) => `the file ${path} (${format})`,
187
+ },
188
+ ru: {
189
+ credentials: (ref) => `хранилище учётных данных, ключ ${ref}`,
190
+ upload: (dir) => `каталог ${dir}`,
191
+ file: (path, format) => `файл ${path} (${format})`,
192
+ },
193
+ zh: {
194
+ credentials: (ref) => `凭据库中的 ${ref}`,
195
+ upload: (dir) => `目录 ${dir}`,
196
+ file: (path, format) => `文件 ${path}(${format})`,
197
+ },
198
+ };
199
+
200
+ /** A human phrase for where a submitted value went; used in notes. */
201
+ export function describeTarget(target, ref, language = 'en') {
202
+ const phrases = TARGET_PHRASES[language] ?? TARGET_PHRASES.en;
203
+ if (target.kind === 'credentials') return phrases.credentials(ref);
204
+ if (target.kind === 'upload') return phrases.upload(target.dir);
205
+ return phrases.file(target.path, target.format);
206
+ }
207
+
208
+ const NOTE_TARGET_LIMIT = 160;
209
+
210
+ /**
211
+ * Read the value of an outbound secret from its source.
212
+ * The value never travels through the tool arguments: either a file on the host
213
+ * or a credential reference is named, and the bytes are read here.
214
+ */
215
+ async function readShareValue(args, ctx) {
216
+ const file = typeof args.file === 'string' && args.file.trim() !== '' ? args.file.trim() : undefined;
217
+ const credential = typeof args.credential === 'string' && args.credential.trim() !== ''
218
+ ? args.credential.trim()
219
+ : undefined;
220
+ if ((file === undefined) === (credential === undefined)) {
221
+ throw new TypeError('name exactly one source: file (a path on this host) or credential (a reference name)');
222
+ }
223
+ if (file !== undefined) {
224
+ const path = resolve(file);
225
+ let data;
226
+ try {
227
+ data = await readFile(path);
228
+ } catch (error) {
229
+ throw new TypeError(`cannot read ${path}: ${error.code ?? error.message}`);
230
+ }
231
+ if (data.length > MAX_SHARE_SECRET_BYTES) {
232
+ throw new TypeError(`${path} is ${data.length} bytes; a share carries at most ${MAX_SHARE_SECRET_BYTES}`);
233
+ }
234
+ const text = data.toString('utf8');
235
+ if (text.includes('\u0000')) {
236
+ throw new TypeError(`${path} looks like a binary file; pass a text secret`);
237
+ }
238
+ const value = text.trim();
239
+ if (value === '') throw new TypeError(`${path} is empty`);
240
+ return { value, source: 'file', fileName: basename(path) };
241
+ }
242
+ const credentials = typeof ctx?.get === 'function' ? ctx.get('credentials') : ctx?.credentials;
243
+ if (credentials === undefined || typeof credentials.resolve !== 'function') {
244
+ throw new Error('the credentials service is not mounted, so a credential share has no source');
245
+ }
246
+ const resolvedValue = await credentials.resolve(credential);
247
+ if (resolvedValue === undefined || typeof resolvedValue.value !== 'string' || resolvedValue.value === '') {
248
+ throw new TypeError(`credential ${credential} is not set in this host`);
249
+ }
250
+ return { value: resolvedValue.value, source: 'credential', fileName: undefined };
251
+ }
252
+
253
+ /** Merge both stores into one `secret_list` answer, oldest first. */
254
+ function mergedList(forms, shares) {
255
+ const rows = [
256
+ ...forms.list().map((form) => ({ createdAt: form.createdAt, row: publicSummary(form) })),
257
+ ...shares.list().map((share) => ({ createdAt: share.createdAt, row: publicShareSummary(share) })),
258
+ ];
259
+ return rows.sort((left, right) => left.createdAt - right.createdAt).map((entry) => entry.row);
260
+ }
261
+
113
262
  /**
114
- * Register the four tools.
263
+ * Register the tools.
115
264
  * @param ctx - host context carrying `tools`.
116
- * @param deps - store, settings, logger, and the lazy credentials lookup.
265
+ * @param deps - stores, settings, logger, notifier and the session-aware helpers.
117
266
  */
118
- export function registerTools(ctx, { store, settings, logger }) {
267
+ export function registerTools(ctx, { forms, shares, settings, logger, notifier, ctx: hostCtx = ctx }) {
119
268
  const tools = ctx?.tools;
120
269
  if (typeof tools?.register !== 'function') {
121
270
  throw new TypeError('dsh-secret-form: the tools service is required');
@@ -131,7 +280,7 @@ export function registerTools(ctx, { store, settings, logger }) {
131
280
 
132
281
  tools.register({
133
282
  name: 'secret_create',
134
- description: "Ask the human for a secret through a one-time web form instead of having it typed into the chat: chat history, transcripts and every provider request would keep a pasted key forever, while a form writes the value straight to the host.\n\nCreate the form, then put the returned url in your own reply to the human — that message is how they learn about the link. Call secret_result with the returned uuid to find out whether the value arrived; the value itself is never returned to you.\n\nThe link is built from the host public URL when one is configured, and otherwise from the web server own listener origin, such as http://127.0.0.1:3080, which resolves only on the host itself. Hand the url over exactly as returned and never rewrite it; if it points at loopback the human may not be able to open it, and saying that plainly is better than inventing a hostname.\n\nref names the key the value is stored under. With the default credentials target it is the credential name, for example OPENAI_API_KEY, and every other tool reads it by that name. With a file target it is the path inside that document: a flat .env takes a bare key (OPENAI_API_KEY), while structured .yaml and .json documents take a dotted path to the value, so ref.fooname writes a nested object and a single segment writes a top-level key.\n\nThe link accepts input for ttlSeconds (default 300) and works exactly once.",
283
+ description: "Ask the human for a secret through a form link instead of having it typed into the chat: chat history, transcripts and every provider request would keep a pasted key forever, while a form writes the value straight to the host.\n\nCreate the form, then put the returned url in your own reply to the human — that message is how they learn about the link. Call secret_result with the returned uuid to find out whether the value arrived; the value itself is never returned to you. The session that created the form is remembered and woken with a note when the form is filled in, cancelled, or a shared secret is collected, unless you pass notify=false.\n\nkinds: single (one-line value, e.g. an API key), multi (a textarea for certificates and multi-line secrets), file (the human picks a file; requires upload { dir } and nothing is sent to the chat).\n\nThe link is built from the host public URL when one is configured, and otherwise from the web server own listener origin. Hand the url over exactly as returned and never rewrite it.\n\nref names the key the value is stored under. With the default credentials target it is the credential name, for example OPENAI_API_KEY. With a file target it is the path inside that document: a flat .env takes a bare key, while structured .yaml and .json documents take a dotted path. For kind=file ref is only a label unless upload.name is omitted, when it becomes the file name.\n\nThe form is stored in SQLite and survives a restart of the harness; its token is stored only as a hash.",
135
284
  parameters: {
136
285
  type: 'object',
137
286
  additionalProperties: false,
@@ -146,8 +295,8 @@ export function registerTools(ctx, { store, settings, logger }) {
146
295
  },
147
296
  kind: {
148
297
  type: 'string',
149
- enum: ['single', 'multi'],
150
- description: 'One-line input (single) or a textarea (multi) for multi-line secrets such as certificates or key files.',
298
+ enum: KINDS,
299
+ description: 'single (one-line value), multi (textarea, for certificates and other multi-line secrets), or file (the human uploads a file). Default single.',
151
300
  },
152
301
  description: {
153
302
  type: 'string',
@@ -156,7 +305,17 @@ export function registerTools(ctx, { store, settings, logger }) {
156
305
  save: {
157
306
  type: 'object',
158
307
  additionalProperties: true,
159
- description: 'Where the value goes. Default credentials. A file target is { kind: "file", path }; the extension picks the format — .yaml, .yml, .json or .env — and anything else is rejected. Missing directories are created, the file is written atomically with mode 0600, and unrelated keys in it are preserved.',
308
+ description: 'Where the value goes for kind=single|multi. Default credentials. A file target is { kind: "file", path }; the extension picks the format — .yaml, .yml, .json or .env. Missing directories are created, the file is written atomically with mode 0600, and unrelated keys in it are preserved.',
309
+ },
310
+ upload: {
311
+ type: 'object',
312
+ additionalProperties: false,
313
+ description: 'Required for kind=file: { dir, name? }. dir is an absolute directory on this host that receives the file (created when missing, mode 0700); name is the file name to write, and defaults to the name the browser sent.',
314
+ properties: {
315
+ dir: { type: 'string', description: 'Absolute path of the directory that receives the uploaded file.' },
316
+ name: { type: 'string', description: 'File name to write inside dir. Default: the name the browser sent.' },
317
+ },
318
+ required: ['dir'],
160
319
  },
161
320
  ttlSeconds: {
162
321
  type: 'integer',
@@ -164,107 +323,258 @@ export function registerTools(ctx, { store, settings, logger }) {
164
323
  },
165
324
  allowEmpty: {
166
325
  type: 'boolean',
167
- description: 'Accept an empty submission and report it as empty. Default false: the page refuses to submit nothing. Set it when an empty answer is itself meaningful.',
326
+ description: 'Accept an empty submission and report it as empty. Default false: the page refuses to submit nothing.',
168
327
  },
169
328
  expect: {
170
329
  type: 'string',
171
330
  description: 'Optional regular expression, as text, the submitted value should match. Reported back as matchesExpect; it never blocks a save.',
172
331
  },
332
+ notify: {
333
+ type: 'boolean',
334
+ description: 'Wake the creating session with a note when the form is filled in or cancelled. Default: the plugin setting (on).',
335
+ },
173
336
  data: {
174
337
  type: 'object',
175
338
  additionalProperties: true,
176
339
  description: 'Optional JSON object, at most 1 KB, of bookkeeping for yourself — a workflow id, a provider name, anything you want back later. Echoed by secret_result and secret_list and never shown on the page.',
177
340
  },
178
341
  },
179
- required: ['ref', 'label', 'kind'],
342
+ required: ['label'],
180
343
  },
181
344
  output: textOutput,
182
- async execute(args) {
183
- const target = normalizeTarget(args.save);
184
- const ref = assertRefForTarget(target, args.ref);
185
- const form = store.create({
345
+ async execute(args, exec) {
346
+ const kind = args.kind ?? 'single';
347
+ if (!KINDS.includes(kind)) throw new TypeError(`kind must be one of: ${KINDS.join(', ')}`);
348
+ const sessionId = exec?.agent?.session?.id ?? null;
349
+ const notify = args.notify === undefined ? settings.notify : args.notify === true;
350
+ let target;
351
+ let ref;
352
+ if (kind === 'file') {
353
+ target = { kind: 'upload', dir: normalizeUploadDir(args.upload?.dir), name: args.upload?.name };
354
+ ref = typeof args.ref === 'string' && args.ref.trim() !== ''
355
+ ? args.ref.trim()
356
+ : (typeof target.name === 'string' && target.name !== '' ? target.name : 'file');
357
+ } else {
358
+ target = normalizeTarget(args.save);
359
+ ref = assertRefForTarget(target, args.ref);
360
+ }
361
+ const form = forms.create({
186
362
  ref,
187
363
  target,
188
364
  label: args.label,
189
- kind: args.kind,
365
+ kind,
190
366
  description: args.description,
191
367
  ttlSeconds: args.ttlSeconds,
192
368
  allowEmpty: args.allowEmpty,
193
369
  expect: args.expect,
194
370
  data: args.data,
371
+ sessionId,
372
+ notify,
195
373
  });
196
- const url = `${resolveOrigin(ctx, settings)}${settings.routePrefix}/${form.token}`;
197
- logger?.info?.(`[dsh-secret-form] created ${tokenTag(form.token)} for ${ref}`);
374
+ const url = `${resolveOrigin(hostCtx, settings)}${settings.routePrefix}/${form.token}`;
375
+ logger?.info?.(`created form ${recordTag(form)} for ${ref} (${kind})`);
198
376
  return {
199
377
  uuid: form.uuid,
200
378
  url,
201
379
  expiresAt: new Date(form.expiresAt).toISOString(),
380
+ kind,
202
381
  data: form.data,
203
382
  };
204
383
  },
205
384
  });
206
385
 
386
+ tools.register({
387
+ name: 'secret_share',
388
+ description: 'Hand a secret to the human through a one-time link. The value does not pass through this call: name a source — file (a path on this host) or credential (a reference name) — and the plugin reads the bytes itself, seals them with a one-shot key and stores both in SQLite.\n\nThe link may be opened any number of times; the reveal button on it works exactly once. After the reveal the link is dead and the sealed value with its key is deleted. If nobody reveals it before ttlSeconds, the value is deleted on expiry too. Only text secrets are carried: a file must be readable text of at most 256 KiB.\n\nPut the returned url in your own reply. The session that created the share is woken with a note when the human collects the secret, unless notify=false. secret_result(uuid) reports whether it was collected.',
389
+ parameters: {
390
+ type: 'object',
391
+ additionalProperties: false,
392
+ properties: {
393
+ label: {
394
+ type: 'string',
395
+ description: 'Page title, 2 to 5 words, shown to the human.',
396
+ },
397
+ kind: {
398
+ type: 'string',
399
+ enum: ['single', 'multi'],
400
+ description: 'single for a one-line value, multi for a multi-line one. Default single.',
401
+ },
402
+ file: {
403
+ type: 'string',
404
+ description: 'Absolute path of a text file on this host whose contents are the secret. Exactly one of file or credential.',
405
+ },
406
+ credential: {
407
+ type: 'string',
408
+ description: 'Name of a stored credential, e.g. OPENAI_API_KEY, whose value is the secret. Exactly one of file or credential.',
409
+ },
410
+ description: {
411
+ type: 'string',
412
+ description: 'Optional one or two sentences shown under the title, at most 300 characters.',
413
+ },
414
+ ttlSeconds: {
415
+ type: 'integer',
416
+ description: 'How long the link lives, 30 to 3600 seconds. Default 300. After that the value is deleted unread.',
417
+ },
418
+ notify: {
419
+ type: 'boolean',
420
+ description: 'Wake the creating session with a note when the human collects the secret. Default: the plugin setting (on).',
421
+ },
422
+ data: {
423
+ type: 'object',
424
+ additionalProperties: true,
425
+ description: 'Optional JSON object, at most 1 KB, of bookkeeping for yourself. Echoed back by secret_result and secret_list.',
426
+ },
427
+ },
428
+ required: ['label'],
429
+ },
430
+ output: textOutput,
431
+ async execute(args, exec) {
432
+ const source = await readShareValue(args, hostCtx);
433
+ const sessionId = exec?.agent?.session?.id ?? null;
434
+ const notify = args.notify === undefined ? settings.notify : args.notify === true;
435
+ const share = shares.create({
436
+ label: args.label,
437
+ kind: args.kind ?? 'single',
438
+ description: args.description,
439
+ data: args.data,
440
+ value: source.value,
441
+ source: source.source,
442
+ fileName: source.fileName,
443
+ ttlSeconds: args.ttlSeconds,
444
+ sessionId,
445
+ notify,
446
+ });
447
+ const url = `${resolveOrigin(hostCtx, settings)}${settings.routePrefix}/${share.token}`;
448
+ logger?.info?.(`created share ${recordTag(share)} (${source.source}, ${source.value.length} chars)`);
449
+ return {
450
+ uuid: share.uuid,
451
+ url,
452
+ expiresAt: new Date(share.expiresAt).toISOString(),
453
+ source: source.source,
454
+ length: source.value.length,
455
+ data: share.data,
456
+ };
457
+ },
458
+ });
459
+
207
460
  tools.register({
208
461
  name: 'secret_result',
209
- description: "Read the state of a form created by secret_create. The value is never returned: you learn whether it arrived and how it looks, which is normally enough to keep going.\n\nstatus is one of: pending (nobody has submitted or cancelled yet; no other fields are present, so an answer that carries only status and the booked data means the human has not acted), saved (the value was written), empty (an empty value was submitted under allowEmpty and nothing was written), cancelled (the human pressed Cancel or you called secret_cancel; nothing was written), expired (the link outlived ttlSeconds; nothing was written).\n\nFor saved and empty the answer also carries length in characters, lines, trimmed (whether surrounding whitespace was stripped) and, when the form was created with expect, matchesExpect.\n\nWith waitSeconds above zero the call waits for the form to leave pending, up to that many seconds, and then reports whatever state it holds — useful when the human is expected to submit right away. With the default of 0 it answers immediately.",
462
+ description: "Read the state of a form from secret_create or a link from secret_share. The value is never returned: you learn whether it arrived and how it looks, which is normally enough to keep going.\n\nFor a form, status is one of: pending (nobody has submitted or cancelled yet), saved (the value was written), empty (an empty value was submitted under allowEmpty and nothing was written), cancelled, expired. For saved and empty the answer also carries length, lines, trimmed and, for a file form, fileName, size, sha256 and path.\n\nFor a share, status is one of: pending (not collected yet), revealed (the human pressed the button; the value and its key are deleted), cancelled, expired. views counts how often the link page was opened, so pending with views>0 means the human looked but did not press the button.\n\nWith waitSeconds above zero the call waits for the record to leave pending, up to that many seconds.",
210
463
  parameters: {
211
464
  type: 'object',
212
465
  additionalProperties: false,
213
466
  properties: {
214
- uuid: { type: 'string', description: 'The uuid returned by secret_create.' },
467
+ uuid: { type: 'string', description: 'The uuid returned by secret_create or secret_share.' },
215
468
  waitSeconds: {
216
469
  type: 'integer',
217
- description: `How long to wait for the form to leave pending, 0 to ${MAX_WAIT_SECONDS} seconds. Default 0: report the current state without waiting.`,
470
+ description: `How long to wait for the record to leave pending, 0 to ${MAX_WAIT_SECONDS} seconds. Default 0: report the current state without waiting.`,
218
471
  },
219
472
  },
220
473
  required: ['uuid'],
221
474
  },
222
475
  output: textOutput,
223
476
  async execute(args) {
224
- const form = store.require(args.uuid);
225
477
  const waitSeconds = normalizeWait(args.waitSeconds);
226
- const settled = await store.settle(form, waitSeconds * 1000);
227
- return publicResult(settled);
478
+ const found = requireRecord(forms, shares, args.uuid);
479
+ if (found.form !== undefined) {
480
+ const settled = await forms.settle(found.form, waitSeconds * 1000);
481
+ return publicResult(settled);
482
+ }
483
+ const { share } = found;
484
+ const ms = waitSeconds * 1000;
485
+ if (share.status === SHARE_STATUS.pending && ms > 0) {
486
+ const deadline = Date.now() + ms;
487
+ while (Date.now() < deadline) {
488
+ await new Promise((done) => {
489
+ const timer = setTimeout(done, Math.min(500, Math.max(50, deadline - Date.now())));
490
+ timer.unref?.();
491
+ });
492
+ if (shares.require(args.uuid).status !== SHARE_STATUS.pending) break;
493
+ }
494
+ }
495
+ return publicShareResult(shares.require(args.uuid));
228
496
  },
229
497
  });
230
498
 
231
499
  tools.register({
232
500
  name: 'secret_list',
233
- description: "List the forms this process still knows about, oldest first, with uuid, ref, label, status, createdAt, expiresAt and the data booked at creation. Submitted values are never included. Forms live in process memory, so after a restart every pending form is gone and its link reads as expired; check this list before creating a second form for the same purpose.",
501
+ description: 'List every form and share the plugin still holds, oldest first: uuid, type (form or share), ref or label, status, createdAt, expiresAt, and the data booked at creation. Submitted values and sealed secrets are never included. The list is read from SQLite, so it also holds records created before a restart. Check it before creating a second record for the same purpose.',
234
502
  parameters: { type: 'object', additionalProperties: false, properties: {} },
235
503
  output: listOutput,
236
504
  execute() {
237
- return store.list().map(publicSummary);
505
+ return mergedList(forms, shares);
238
506
  },
239
507
  });
240
508
 
241
509
  tools.register({
242
510
  name: 'secret_cancel',
243
- description: "Cancel a pending form so its link stops accepting input and nothing is written. Use it when the request no longer stands: the workflow moved on, the human declined, or a new form replaces this one. Cancelling a form that already finished changes nothing and reports the status it already has.",
511
+ description: 'Cancel a pending form or share so its link stops working and nothing is written or revealed. Use it when the request no longer stands: the workflow moved on, the human declined, or a new link replaces this one. For a share this also deletes the sealed value and its key. Cancelling something that already finished changes nothing and reports the status it already has.',
244
512
  parameters: {
245
513
  type: 'object',
246
514
  additionalProperties: false,
247
515
  properties: {
248
- uuid: { type: 'string', description: 'The uuid returned by secret_create.' },
516
+ uuid: { type: 'string', description: 'The uuid returned by secret_create or secret_share.' },
249
517
  },
250
518
  required: ['uuid'],
251
519
  },
252
520
  output: textOutput,
253
521
  async execute(args) {
254
- const form = store.cancel(store.require(args.uuid));
255
- logger?.info?.(`[dsh-secret-form] cancelled ${form.uuid}`);
256
- return publicResult(form);
522
+ const found = requireRecord(forms, shares, args.uuid);
523
+ if (found.form !== undefined) {
524
+ const cancelled = forms.cancel(found.form);
525
+ logger?.info?.(`cancelled form ${cancelled.uuid}`);
526
+ if (cancelled.status === STATUS.cancelled && cancelled.notify && notifier !== undefined) {
527
+ notifier.queue({
528
+ kind: NOTE_KINDS.formCancelled,
529
+ uuid: cancelled.uuid,
530
+ sessionId: cancelled.sessionId,
531
+ variables: { label: cancelled.label, ref: cancelled.ref },
532
+ });
533
+ forms.markNotified(cancelled);
534
+ }
535
+ return publicResult(cancelled);
536
+ }
537
+ const share = shares.cancel(found.share);
538
+ logger?.info?.(`cancelled share ${share.uuid}`);
539
+ return publicShareResult(share);
257
540
  },
258
541
  });
259
542
  }
260
543
 
261
- function noticeFor(status) {
262
- return status === STATUS.saved || status === STATUS.empty ? 'used' : status;
544
+ /** Find a form by uuid, or undefined when the uuid names a share instead. */
545
+ function findForm(forms, uuid) {
546
+ try {
547
+ return forms.require(uuid);
548
+ } catch {
549
+ return undefined;
550
+ }
263
551
  }
264
552
 
265
- async function readFormBody(request) {
553
+ /** Resolve one uuid against both stores, or refuse with one sentence. */
554
+ function requireRecord(forms, shares, uuid) {
555
+ const form = findForm(forms, uuid);
556
+ if (form !== undefined) return { form };
557
+ try {
558
+ return { share: shares.require(uuid) };
559
+ } catch {
560
+ throw new TypeError(`unknown secret form or link ${JSON.stringify(uuid ?? null)}`);
561
+ }
562
+ }
563
+
564
+ function noticeFor(status, kind) {
565
+ if (status === STATUS.saved) return kind === 'file' ? 'uploaded' : 'used';
566
+ if (status === STATUS.empty) return 'used';
567
+ return status;
568
+ }
569
+
570
+ function noticeForShare(status) {
571
+ if (status === SHARE_STATUS.revealed) return 'revealed';
572
+ return status;
573
+ }
574
+
575
+ async function readBody(request, limit) {
266
576
  const declared = Number(request.headers['content-length']);
267
- if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
577
+ if (Number.isFinite(declared) && declared > limit) {
268
578
  const error = new Error('payload too large');
269
579
  error.status = 413;
270
580
  throw error;
@@ -274,14 +584,14 @@ async function readFormBody(request) {
274
584
  for await (const chunk of request) {
275
585
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
276
586
  length += buffer.length;
277
- if (length > MAX_BODY_BYTES) {
587
+ if (length > limit) {
278
588
  const error = new Error('payload too large');
279
589
  error.status = 413;
280
590
  throw error;
281
591
  }
282
592
  chunks.push(buffer);
283
593
  }
284
- return new URLSearchParams(Buffer.concat(chunks, length).toString('utf8'));
594
+ return Buffer.concat(chunks, length);
285
595
  }
286
596
 
287
597
  function isFormPost(request) {
@@ -292,126 +602,288 @@ function isFormPost(request) {
292
602
 
293
603
  /**
294
604
  * Build the HTTP handler for the route prefix.
295
- * @param deps - store, settings, logger, credentials lookup, and the clock.
605
+ * @param deps - stores, settings, logger, credentials lookup, notifier and the clock.
296
606
  */
297
- export function createRouteHandler({ store, settings, logger, credentialsOf, now = Date.now }) {
607
+ export function createRouteHandler({
608
+ forms,
609
+ shares,
610
+ settings,
611
+ logger,
612
+ credentialsOf,
613
+ notifier,
614
+ now = Date.now,
615
+ }) {
298
616
  const { routePrefix } = settings;
299
617
 
300
- const pageFor = (form, locale, extra = {}) => renderFormView(form, {
301
- actionPath: `${routePrefix}/${form.token}`,
618
+ // A record read from the database carries no token — that is the point — so
619
+ // the action of its page comes from the request that resolved it.
620
+ const pageFor = (form, actionPath, locale, extra = {}) => renderFormView(form, {
621
+ actionPath,
302
622
  remainingSeconds: Math.max(0, Math.round((form.expiresAt - now()) / 1000)),
303
623
  locale,
304
624
  ...extra,
305
625
  });
306
626
 
307
- return async function secretFormRoute(request, response) {
308
- const target = String(request.url ?? '/');
309
- const queryIndex = target.indexOf('?');
310
- const path = queryIndex === -1 ? target : target.slice(0, queryIndex);
311
- const query = new URLSearchParams(queryIndex === -1 ? '' : target.slice(queryIndex + 1));
312
- const acceptLanguage = request.headers['accept-language'];
313
- const localeFor = (lang) => resolveLocale({ lang, acceptLanguage, defaultLocale: settings.defaultLocale });
314
- if (!path.startsWith(`${routePrefix}/`)) {
315
- sendText(response, 404, 'Not found');
627
+ const sharePageFor = (share, actionPath, locale, extra = {}) => renderShareView(share, {
628
+ actionPath,
629
+ remainingSeconds: Math.max(0, Math.round((share.expiresAt - now()) / 1000)),
630
+ locale,
631
+ ...extra,
632
+ });
633
+
634
+ /** Tell the creating session what happened, if the record asked for it. */
635
+ const noteForm = (kind, form, variables) => {
636
+ if (notifier === undefined || !form.notify || typeof form.sessionId !== 'string') return;
637
+ notifier.queue({ kind, uuid: form.uuid, sessionId: form.sessionId, variables });
638
+ forms.markNotified(form);
639
+ };
640
+
641
+ const noteShare = (kind, share, variables) => {
642
+ if (notifier === undefined || !share.notify || typeof share.sessionId !== 'string') return;
643
+ notifier.queue({ kind, uuid: share.uuid, sessionId: share.sessionId, variables });
644
+ shares.markNotified(share);
645
+ };
646
+
647
+ async function handleUpload(request, response, form, actionPath, locale) {
648
+ const boundary = boundaryOf(request.headers['content-type']);
649
+ if (boundary === undefined) {
650
+ sendText(response, 415, 'Expected multipart/form-data');
316
651
  return;
317
652
  }
318
- let token;
653
+ let body;
319
654
  try {
320
- token = decodeURIComponent(path.slice(routePrefix.length + 1));
321
- } catch {
322
- sendText(response, 404, 'Not found');
655
+ body = await readBody(request, settings.maxUploadBytes + MAX_BODY_BYTES);
656
+ } catch (error) {
657
+ sendText(response, error.status ?? 400, error.message);
323
658
  return;
324
659
  }
325
- if (token === '' || token.includes('/')) {
326
- sendText(response, 404, 'Not found');
660
+ const parsed = parseMultipart(body, boundary);
661
+ const action = parsed.fields.get('action') ?? 'save';
662
+ const effectiveLocale = parsed.fields.get('lang') === undefined
663
+ ? locale
664
+ : resolveLocale({ lang: parsed.fields.get('lang'), defaultLocale: settings.defaultLocale });
665
+ const dict = messagesFor(effectiveLocale);
666
+ if (action === 'cancel') {
667
+ forms.cancel(form);
668
+ logger?.info?.(`cancelled form ${recordTag(form)}`);
669
+ sendHtml(response, 200, renderNotice('cancelled', undefined, { locale: effectiveLocale }));
670
+ noteForm(NOTE_KINDS.formCancelled, form, { label: form.label, ref: form.ref });
327
671
  return;
328
672
  }
329
- const method = String(request.method ?? 'GET').toUpperCase();
330
- if (method !== 'GET' && method !== 'HEAD' && method !== 'POST') {
331
- sendText(response, 405, 'Method not allowed', { Allow: 'GET, HEAD, POST' });
673
+ const part = parsed.files.find((candidate) => candidate.name === 'file');
674
+ if (part === undefined || part.data.length === 0) {
675
+ const extra = { error: dict.errors.nofile };
676
+ sendHtml(response, 422, pageFor(form, actionPath, effectiveLocale, extra));
332
677
  return;
333
678
  }
334
-
335
- // A link the model pinned with `?lang=` keeps that language for the whole
336
- // exchange: the form carries it in a hidden field that outranks the header.
337
- let locale = localeFor(query.get('lang') ?? undefined);
338
-
339
- const form = store.lookup(token);
340
- if (form === undefined) {
341
- sendHtml(response, 404, renderNotice('unknown', undefined, { locale }));
679
+ if (part.data.length > settings.maxUploadBytes) {
680
+ sendText(response, 413, 'payload too large');
342
681
  return;
343
682
  }
344
-
345
- if (method !== 'POST') {
346
- if (form.status !== STATUS.pending) {
347
- sendHtml(response, 200, renderNotice(noticeFor(form.status), undefined, { locale }), { head: method === 'HEAD' });
348
- return;
349
- }
350
- sendHtml(response, 200, pageFor(form, locale), { head: method === 'HEAD' });
683
+ const started = forms.beginUpload(form);
684
+ if (started.outcome === 'busy') {
685
+ sendHtml(response, 409, pageFor(form, actionPath, effectiveLocale, { error: dict.errors.busy }));
351
686
  return;
352
687
  }
688
+ if (started.outcome !== 'ready') {
689
+ sendHtml(response, 410, renderNotice(noticeFor(form.status, form.kind), undefined, { locale: effectiveLocale }));
690
+ return;
691
+ }
692
+ let facts;
693
+ try {
694
+ facts = await saveUpload({
695
+ dir: form.target.dir,
696
+ name: form.target.name ?? part.filename,
697
+ data: part.data,
698
+ });
699
+ } catch (error) {
700
+ forms.abortSubmit(form);
701
+ logger?.warn?.(`${recordTag(form)} upload refused: ${error.message}`);
702
+ const detail = String(error.message).slice(0, 300);
703
+ sendHtml(response, 500, pageFor(form, actionPath, effectiveLocale, { error: format(dict.errors.upload, { detail }) }));
704
+ return;
705
+ }
706
+ forms.completeSubmit(form, { empty: false, trimmed: false, length: 0, lines: 0, file: facts });
707
+ logger?.info?.(`${recordTag(form)} stored ${facts.size} bytes as ${facts.path}`);
708
+ sendHtml(response, 200, renderNotice('uploaded', undefined, { locale: effectiveLocale }));
709
+ noteForm(NOTE_KINDS.formUploaded, form, {
710
+ label: form.label,
711
+ fileName: facts.fileName,
712
+ size: facts.size,
713
+ path: facts.path,
714
+ sha256: facts.sha256,
715
+ });
716
+ }
353
717
 
354
- if (form.status !== STATUS.pending) {
355
- sendHtml(response, 410, renderNotice(noticeFor(form.status), undefined, { locale }));
718
+ async function handleFormPost(request, response, form, actionPath, locale) {
719
+ if (form.kind === 'file') {
720
+ await handleUpload(request, response, form, actionPath, locale);
356
721
  return;
357
722
  }
358
723
  if (!isFormPost(request)) {
359
724
  sendText(response, 415, 'Expected application/x-www-form-urlencoded');
360
725
  return;
361
726
  }
362
-
363
727
  let body;
364
728
  try {
365
- body = await readFormBody(request);
729
+ body = new URLSearchParams((await readBody(request, MAX_BODY_BYTES)).toString('utf8'));
366
730
  } catch (error) {
367
731
  sendText(response, error.status ?? 400, error.message);
368
732
  return;
369
733
  }
370
-
371
734
  // The hidden field wins over the header: it is what the reader actually saw.
372
- locale = localeFor(body.get('lang') ?? query.get('lang') ?? undefined);
373
- const messages = messagesFor(locale);
374
-
735
+ const effectiveLocale = resolveLocale({
736
+ lang: body.get('lang') ?? locale,
737
+ defaultLocale: settings.defaultLocale,
738
+ });
739
+ const messages = messagesFor(effectiveLocale);
375
740
  const action = body.get('action');
376
741
  if (action === 'cancel') {
377
- store.cancel(form);
378
- logger?.info?.(`[dsh-secret-form] cancelled ${tokenTag(token)}`);
379
- sendHtml(response, 200, renderNotice('cancelled', undefined, { locale }));
742
+ forms.cancel(form);
743
+ logger?.info?.(`cancelled ${recordTag(form)}`);
744
+ sendHtml(response, 200, renderNotice('cancelled', undefined, { locale: effectiveLocale }));
745
+ noteForm(NOTE_KINDS.formCancelled, form, { label: form.label, ref: form.ref });
380
746
  return;
381
747
  }
382
748
  if (action !== 'save') {
383
- sendHtml(response, 400, pageFor(form, locale, { error: messages.errors.action }));
749
+ sendHtml(response, 400, pageFor(form, actionPath, effectiveLocale, { error: messages.errors.action }));
384
750
  return;
385
751
  }
386
-
387
- const submission = store.beginSubmit(form, body.get('value') ?? '');
752
+ const submission = forms.beginSubmit(form, body.get('value') ?? '');
388
753
  if (submission.outcome === 'invalid') {
389
- sendHtml(response, 422, pageFor(form, locale, { error: messages.errors.empty }));
754
+ sendHtml(response, 422, pageFor(form, actionPath, effectiveLocale, { error: messages.errors.empty }));
390
755
  return;
391
756
  }
392
757
  if (submission.outcome === 'busy') {
393
- sendHtml(response, 409, pageFor(form, locale, { error: messages.errors.busy }));
758
+ sendHtml(response, 409, pageFor(form, actionPath, effectiveLocale, { error: messages.errors.busy }));
394
759
  return;
395
760
  }
396
761
  if (submission.outcome !== 'ready') {
397
- sendHtml(response, 410, renderNotice(noticeFor(form.status), undefined, { locale }));
762
+ sendHtml(response, 410, renderNotice(noticeFor(form.status, form.kind), undefined, { locale: effectiveLocale }));
398
763
  return;
399
764
  }
400
-
401
765
  try {
402
766
  await writeSecret(form.target, form.ref, submission.value, { credentials: credentialsOf() });
403
767
  } catch (error) {
404
- store.abortSubmit(form);
405
- logger?.warn?.(`[dsh-secret-form] ${tokenTag(token)} could not be stored: ${error.message}`);
768
+ forms.abortSubmit(form);
769
+ logger?.warn?.(`${recordTag(form)} could not be stored: ${error.message}`);
406
770
  const detail = String(error.message).slice(0, 300);
407
- sendHtml(response, 500, pageFor(form, locale, { error: format(messages.errors.store, { detail }) }));
771
+ sendHtml(response, 500, pageFor(form, actionPath, effectiveLocale, { error: format(messages.errors.store, { detail }) }));
408
772
  return;
409
773
  }
410
-
411
- store.completeSubmit(form, submission);
412
- logger?.info?.(`[dsh-secret-form] ${tokenTag(token)} ${form.status}`);
774
+ forms.completeSubmit(form, submission);
775
+ logger?.info?.(`${recordTag(form)} ${form.status}`);
413
776
  const note = submission.matchesExpect === false ? messages.mismatchNote : undefined;
414
- sendHtml(response, 200, renderNotice(submission.empty ? 'empty' : 'saved', note, { locale }));
777
+ sendHtml(response, 200, renderNotice(submission.empty ? 'empty' : 'saved', note, { locale: effectiveLocale }));
778
+ noteForm(NOTE_KINDS.formSaved, form, {
779
+ label: form.label,
780
+ ref: form.ref,
781
+ target: describeTarget(form.target, form.ref, settings.language).slice(0, NOTE_TARGET_LIMIT),
782
+ });
783
+ }
784
+
785
+ async function handleSharePost(request, response, share, actionPath, locale) {
786
+ let effectiveLocale = locale;
787
+ if (isFormPost(request)) {
788
+ let body;
789
+ try {
790
+ body = new URLSearchParams((await readBody(request, MAX_BODY_BYTES)).toString('utf8'));
791
+ } catch (error) {
792
+ sendText(response, error.status ?? 400, error.message);
793
+ return;
794
+ }
795
+ effectiveLocale = resolveLocale({
796
+ lang: body.get('lang') ?? locale,
797
+ defaultLocale: settings.defaultLocale,
798
+ });
799
+ if (body.get('action') !== 'reveal') {
800
+ const messages = messagesFor(effectiveLocale);
801
+ sendHtml(response, 400, sharePageFor(share, actionPath, effectiveLocale, { error: messages.errors.action }));
802
+ return;
803
+ }
804
+ }
805
+ const at = now();
806
+ const revealed = shares.reveal(share);
807
+ if (revealed.value === undefined) {
808
+ logger?.info?.(`share ${recordTag(share)} not revealed: ${revealed.status}`);
809
+ sendHtml(response, 410, renderNotice(noticeForShare(revealed.status), undefined, { locale: effectiveLocale }));
810
+ return;
811
+ }
812
+ logger?.info?.(`share ${recordTag(share)} revealed at ${new Date(at).toISOString()}`);
813
+ sendHtml(response, 200, renderRevealedView(share, { value: revealed.value, locale: effectiveLocale }));
814
+ noteShare(NOTE_KINDS.shareRevealed, share, { label: share.label });
815
+ }
816
+
817
+ return async function secretFormRoute(request, response) {
818
+ const target = String(request.url ?? '/');
819
+ const queryIndex = target.indexOf('?');
820
+ const path = queryIndex === -1 ? target : target.slice(0, queryIndex);
821
+ const query = new URLSearchParams(queryIndex === -1 ? '' : target.slice(queryIndex + 1));
822
+ const acceptLanguage = request.headers['accept-language'];
823
+ const localeFor = (lang) => resolveLocale({ lang, acceptLanguage, defaultLocale: settings.defaultLocale });
824
+ if (!path.startsWith(`${routePrefix}/`)) {
825
+ sendText(response, 404, 'Not found');
826
+ return;
827
+ }
828
+ let token;
829
+ try {
830
+ token = decodeURIComponent(path.slice(routePrefix.length + 1));
831
+ } catch {
832
+ sendText(response, 404, 'Not found');
833
+ return;
834
+ }
835
+ if (token === '' || token.includes('/')) {
836
+ sendText(response, 404, 'Not found');
837
+ return;
838
+ }
839
+ const actionPath = `${routePrefix}/${encodeURIComponent(token)}`;
840
+ const method = String(request.method ?? 'GET').toUpperCase();
841
+ if (method !== 'GET' && method !== 'HEAD' && method !== 'POST') {
842
+ sendText(response, 405, 'Method not allowed', { Allow: 'GET, HEAD, POST' });
843
+ return;
844
+ }
845
+
846
+ // A link the model pinned with `?lang=` keeps that language for the whole
847
+ // exchange: the form carries it in a hidden field that outranks the header.
848
+ const locale = localeFor(query.get('lang') ?? undefined);
849
+
850
+ const form = forms?.lookup(token);
851
+ if (form !== undefined) {
852
+ if (method !== 'POST') {
853
+ if (form.status !== STATUS.pending) {
854
+ sendHtml(response, 200, renderNotice(noticeFor(form.status, form.kind), undefined, { locale }), { head: method === 'HEAD' });
855
+ return;
856
+ }
857
+ sendHtml(response, 200, pageFor(form, actionPath, locale), { head: method === 'HEAD' });
858
+ return;
859
+ }
860
+ if (form.status !== STATUS.pending) {
861
+ sendHtml(response, 410, renderNotice(noticeFor(form.status, form.kind), undefined, { locale }));
862
+ return;
863
+ }
864
+ await handleFormPost(request, response, form, actionPath, locale);
865
+ return;
866
+ }
867
+
868
+ const share = shares?.lookup(token);
869
+ if (share === undefined) {
870
+ sendHtml(response, 404, renderNotice('unknown', undefined, { locale }));
871
+ return;
872
+ }
873
+ if (method !== 'POST') {
874
+ if (share.status !== SHARE_STATUS.pending) {
875
+ sendHtml(response, 200, renderNotice(noticeForShare(share.status), undefined, { locale }), { head: method === 'HEAD' });
876
+ return;
877
+ }
878
+ shares.countView(share);
879
+ sendHtml(response, 200, sharePageFor(share, actionPath, locale), { head: method === 'HEAD' });
880
+ return;
881
+ }
882
+ if (share.status !== SHARE_STATUS.pending) {
883
+ sendHtml(response, 410, renderNotice(noticeForShare(share.status), undefined, { locale }));
884
+ return;
885
+ }
886
+ await handleSharePost(request, response, share, actionPath, locale);
415
887
  };
416
888
  }
417
889
 
@@ -422,10 +894,36 @@ export function createRouteHandler({ store, settings, logger, credentialsOf, now
422
894
  */
423
895
  export function apply(ctx, config = {}) {
424
896
  const settings = normalizeConfig(config);
425
- const store = createFormStore({ defaultTtlSeconds: settings.defaultTtlSeconds });
426
897
  const logger = resolveLogger(ctx);
898
+ const db = openDatabase(settings.database);
899
+ const forms = createFormStore({ db, defaultTtlSeconds: settings.defaultTtlSeconds });
900
+ const shares = createShareStore({ db, defaultTtlSeconds: settings.defaultTtlSeconds });
901
+ forms.sweep({ retainMs: settings.retainSeconds * 1000 });
902
+ shares.sweep({ retainMs: settings.retainSeconds * 1000 });
903
+
904
+ // `schedule` is what actually wakes a session: the service owns the timer and
905
+ // resumes the session itself. It may mount after this plugin does, which is
906
+ // why the notifier asks for it on every attempt instead of capturing it once.
907
+ //
908
+ // Cordis refuses a bare `ctx.schedule` for a service the plugin did not
909
+ // declare in `inject` — the property getter throws — so an optional service is
910
+ // read through `ctx.get`, which answers undefined instead.
911
+ let scheduling = typeof ctx?.get === 'function' ? ctx.get('schedule') : ctx?.schedule;
912
+ let notifier;
913
+ if (typeof ctx?.inject === 'function') {
914
+ ctx.inject(['schedule'], (child) => {
915
+ scheduling = child.schedule;
916
+ void notifier?.kick();
917
+ return () => {
918
+ scheduling = undefined;
919
+ };
920
+ });
921
+ }
922
+ notifier = createNotifier({ db, getSchedule: () => scheduling, language: settings.language, logger });
923
+ void notifier.kick();
924
+
427
925
  const credentialsOf = () => (typeof ctx?.get === 'function' ? ctx.get('credentials') : ctx?.credentials);
428
- const handler = createRouteHandler({ store, settings, logger, credentialsOf });
926
+ const handler = createRouteHandler({ forms, shares, settings, logger, credentialsOf, notifier });
429
927
  const route = { kind: 'prefix', path: settings.routePrefix, handler };
430
928
 
431
929
  if (typeof ctx?.webServer?.register !== 'function') {
@@ -433,10 +931,15 @@ export function apply(ctx, config = {}) {
433
931
  }
434
932
  if (typeof ctx.effect === 'function') {
435
933
  ctx.effect(() => ctx.webServer.register(route), `dsh-secret-form: ${settings.routePrefix}`);
934
+ ctx.effect(() => () => {
935
+ notifier.stop();
936
+ closeDatabase(db);
937
+ }, 'dsh-secret-form: database');
436
938
  } else {
437
939
  ctx.webServer.register(route);
438
940
  }
439
- registerTools(ctx, { store, settings, logger });
941
+ registerTools(ctx, { forms, shares, settings, logger, notifier, ctx });
942
+ logger?.info?.(`ready: ${settings.database}`);
440
943
  }
441
944
 
442
- export default Object.freeze({ name, inject, apply, normalizeConfig });
945
+ export default Object.freeze({ name, inject, apply, normalizeConfig, registerTools, createRouteHandler });