@dr-co/dsh-secret-form 0.0.0-stage → 0.2.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/index.mjs ADDED
@@ -0,0 +1,442 @@
1
+ // One-time secret links for DeepSeek Harness.
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.
8
+ //
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.
12
+ import {
13
+ MAX_WAIT_SECONDS,
14
+ STATUS,
15
+ clampTtl,
16
+ createFormStore,
17
+ normalizeWait,
18
+ publicResult,
19
+ publicSummary,
20
+ } from './lib/forms.mjs';
21
+ import { SUPPORTED_LOCALES, format, messagesFor, normalizeLocale, resolveLocale } from './lib/i18n.mjs';
22
+ import { renderFormView, renderNotice, sendHtml, sendText } from './lib/page.mjs';
23
+ import { assertRefForTarget, normalizeTarget, writeSecret } from './lib/targets.mjs';
24
+
25
+ export const name = 'dsh-secret-form';
26
+ // 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.
29
+ export const inject = ['tools', 'webServer'];
30
+
31
+ const DEFAULT_ROUTE_PREFIX = '/secret';
32
+ const DEFAULT_TTL_SECONDS = 300;
33
+ const DEFAULT_LOCALE = 'en';
34
+ const MAX_BODY_BYTES = 64 * 1024;
35
+
36
+ function invalidConfig(message) {
37
+ return new TypeError(`dsh-secret-form: ${message}`);
38
+ }
39
+
40
+ /**
41
+ * Validate the plugin config.
42
+ * @param config - `routePrefix` (default `/secret`), `defaultTtlSeconds`
43
+ * (default 300, clamped to 30..3600) and `defaultLocale` (default `en`).
44
+ */
45
+ export function normalizeConfig(config = {}) {
46
+ const prefixRaw = config?.routePrefix ?? DEFAULT_ROUTE_PREFIX;
47
+ if (typeof prefixRaw !== 'string') throw invalidConfig('routePrefix must be a string');
48
+ const prefix = prefixRaw.trim().replace(/\/+$/, '');
49
+ if (prefix === '') throw invalidConfig('routePrefix must not be empty or the server root');
50
+ if (!prefix.startsWith('/')) throw invalidConfig('routePrefix must start with "/"');
51
+ if (/[\s?#]/.test(prefix)) throw invalidConfig('routePrefix must not contain whitespace, "?" or "#"');
52
+ const ttl = clampTtl(config?.defaultTtlSeconds ?? DEFAULT_TTL_SECONDS, DEFAULT_TTL_SECONDS);
53
+ // The listener usually binds loopback behind a proxy, so its own origin is
54
+ // useless in a link meant for a phone. A public URL wins when configured.
55
+ const publicUrlRaw = config?.publicUrl;
56
+ let publicUrl;
57
+ if (publicUrlRaw !== undefined && publicUrlRaw !== null && publicUrlRaw !== '') {
58
+ if (typeof publicUrlRaw !== 'string') throw invalidConfig('publicUrl must be a string');
59
+ const trimmed = publicUrlRaw.trim().replace(/\/+$/, '');
60
+ let parsed;
61
+ try {
62
+ parsed = new URL(trimmed);
63
+ } catch {
64
+ throw invalidConfig('publicUrl must be an absolute http(s) URL');
65
+ }
66
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
67
+ throw invalidConfig('publicUrl must be an absolute http(s) URL');
68
+ }
69
+ publicUrl = trimmed;
70
+ }
71
+ // The page falls back to this locale when neither the link nor the browser
72
+ // asks for one, so a host known to serve one language can pin it.
73
+ const localeRaw = config?.defaultLocale ?? DEFAULT_LOCALE;
74
+ if (typeof localeRaw !== 'string') throw invalidConfig('defaultLocale must be a string');
75
+ const defaultLocale = normalizeLocale(localeRaw);
76
+ if (defaultLocale === undefined) {
77
+ throw invalidConfig(`defaultLocale must be one of: ${SUPPORTED_LOCALES.join(', ')}`);
78
+ }
79
+ return { routePrefix: prefix, defaultTtlSeconds: ttl, publicUrl, defaultLocale };
80
+ }
81
+
82
+ function resolveLogger(ctx) {
83
+ try {
84
+ if (typeof ctx?.logger === 'function') {
85
+ const logger = ctx.logger(name);
86
+ if (logger !== undefined && logger !== null) return logger;
87
+ }
88
+ } catch {
89
+ // A host whose logger factory rejects this name still needs the plugin.
90
+ }
91
+ return ctx?.logger ?? console;
92
+ }
93
+
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) : '????????';
98
+ }
99
+
100
+ function resolveOrigin(ctx, settings) {
101
+ if (settings?.publicUrl) return settings.publicUrl;
102
+ const server = ctx?.webServer;
103
+ if (typeof server?.getOrigin !== 'function') {
104
+ throw new Error('dsh-secret-form: this host exposes no Web GUI server, so a secret link has no origin');
105
+ }
106
+ try {
107
+ return server.getOrigin();
108
+ } catch (error) {
109
+ throw new Error(`dsh-secret-form: the web server origin is not available yet (${error.message})`);
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Register the four tools.
115
+ * @param ctx - host context carrying `tools`.
116
+ * @param deps - store, settings, logger, and the lazy credentials lookup.
117
+ */
118
+ export function registerTools(ctx, { store, settings, logger }) {
119
+ const tools = ctx?.tools;
120
+ if (typeof tools?.register !== 'function') {
121
+ throw new TypeError('dsh-secret-form: the tools service is required');
122
+ }
123
+ const textOutput = {
124
+ schema: { type: 'object', additionalProperties: true },
125
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
126
+ };
127
+ const listOutput = {
128
+ schema: { type: 'array', items: { type: 'object', additionalProperties: true } },
129
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
130
+ };
131
+
132
+ tools.register({
133
+ 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.",
135
+ parameters: {
136
+ type: 'object',
137
+ additionalProperties: false,
138
+ properties: {
139
+ ref: {
140
+ type: 'string',
141
+ description: 'Key name. Credentials target: the credential name, e.g. OPENAI_API_KEY. File target: the path inside the document — a bare key for .env, a dotted path such as ref.fooname for .yaml and .json.',
142
+ },
143
+ label: {
144
+ type: 'string',
145
+ description: 'Form title, 2 to 5 words, shown to the human.',
146
+ },
147
+ kind: {
148
+ 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.',
151
+ },
152
+ description: {
153
+ type: 'string',
154
+ description: 'Optional one or two sentences shown under the title, at most 300 characters. State what the value is for, so the human knows what to paste.',
155
+ },
156
+ save: {
157
+ type: 'object',
158
+ 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.',
160
+ },
161
+ ttlSeconds: {
162
+ type: 'integer',
163
+ description: 'How long the link accepts input, 30 to 3600 seconds. Default 300. After that the form reports expired.',
164
+ },
165
+ allowEmpty: {
166
+ 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.',
168
+ },
169
+ expect: {
170
+ type: 'string',
171
+ description: 'Optional regular expression, as text, the submitted value should match. Reported back as matchesExpect; it never blocks a save.',
172
+ },
173
+ data: {
174
+ type: 'object',
175
+ additionalProperties: true,
176
+ 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
+ },
178
+ },
179
+ required: ['ref', 'label', 'kind'],
180
+ },
181
+ output: textOutput,
182
+ async execute(args) {
183
+ const target = normalizeTarget(args.save);
184
+ const ref = assertRefForTarget(target, args.ref);
185
+ const form = store.create({
186
+ ref,
187
+ target,
188
+ label: args.label,
189
+ kind: args.kind,
190
+ description: args.description,
191
+ ttlSeconds: args.ttlSeconds,
192
+ allowEmpty: args.allowEmpty,
193
+ expect: args.expect,
194
+ data: args.data,
195
+ });
196
+ const url = `${resolveOrigin(ctx, settings)}${settings.routePrefix}/${form.token}`;
197
+ logger?.info?.(`[dsh-secret-form] created ${tokenTag(form.token)} for ${ref}`);
198
+ return {
199
+ uuid: form.uuid,
200
+ url,
201
+ expiresAt: new Date(form.expiresAt).toISOString(),
202
+ data: form.data,
203
+ };
204
+ },
205
+ });
206
+
207
+ tools.register({
208
+ 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.",
210
+ parameters: {
211
+ type: 'object',
212
+ additionalProperties: false,
213
+ properties: {
214
+ uuid: { type: 'string', description: 'The uuid returned by secret_create.' },
215
+ waitSeconds: {
216
+ 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.`,
218
+ },
219
+ },
220
+ required: ['uuid'],
221
+ },
222
+ output: textOutput,
223
+ async execute(args) {
224
+ const form = store.require(args.uuid);
225
+ const waitSeconds = normalizeWait(args.waitSeconds);
226
+ const settled = await store.settle(form, waitSeconds * 1000);
227
+ return publicResult(settled);
228
+ },
229
+ });
230
+
231
+ tools.register({
232
+ 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.",
234
+ parameters: { type: 'object', additionalProperties: false, properties: {} },
235
+ output: listOutput,
236
+ execute() {
237
+ return store.list().map(publicSummary);
238
+ },
239
+ });
240
+
241
+ tools.register({
242
+ 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.",
244
+ parameters: {
245
+ type: 'object',
246
+ additionalProperties: false,
247
+ properties: {
248
+ uuid: { type: 'string', description: 'The uuid returned by secret_create.' },
249
+ },
250
+ required: ['uuid'],
251
+ },
252
+ output: textOutput,
253
+ 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);
257
+ },
258
+ });
259
+ }
260
+
261
+ function noticeFor(status) {
262
+ return status === STATUS.saved || status === STATUS.empty ? 'used' : status;
263
+ }
264
+
265
+ async function readFormBody(request) {
266
+ const declared = Number(request.headers['content-length']);
267
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
268
+ const error = new Error('payload too large');
269
+ error.status = 413;
270
+ throw error;
271
+ }
272
+ const chunks = [];
273
+ let length = 0;
274
+ for await (const chunk of request) {
275
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
276
+ length += buffer.length;
277
+ if (length > MAX_BODY_BYTES) {
278
+ const error = new Error('payload too large');
279
+ error.status = 413;
280
+ throw error;
281
+ }
282
+ chunks.push(buffer);
283
+ }
284
+ return new URLSearchParams(Buffer.concat(chunks, length).toString('utf8'));
285
+ }
286
+
287
+ function isFormPost(request) {
288
+ const type = request.headers['content-type'];
289
+ if (typeof type !== 'string') return false;
290
+ return type.split(';', 1)[0].trim().toLowerCase() === 'application/x-www-form-urlencoded';
291
+ }
292
+
293
+ /**
294
+ * Build the HTTP handler for the route prefix.
295
+ * @param deps - store, settings, logger, credentials lookup, and the clock.
296
+ */
297
+ export function createRouteHandler({ store, settings, logger, credentialsOf, now = Date.now }) {
298
+ const { routePrefix } = settings;
299
+
300
+ const pageFor = (form, locale, extra = {}) => renderFormView(form, {
301
+ actionPath: `${routePrefix}/${form.token}`,
302
+ remainingSeconds: Math.max(0, Math.round((form.expiresAt - now()) / 1000)),
303
+ locale,
304
+ ...extra,
305
+ });
306
+
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');
316
+ return;
317
+ }
318
+ let token;
319
+ try {
320
+ token = decodeURIComponent(path.slice(routePrefix.length + 1));
321
+ } catch {
322
+ sendText(response, 404, 'Not found');
323
+ return;
324
+ }
325
+ if (token === '' || token.includes('/')) {
326
+ sendText(response, 404, 'Not found');
327
+ return;
328
+ }
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' });
332
+ return;
333
+ }
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 }));
342
+ return;
343
+ }
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' });
351
+ return;
352
+ }
353
+
354
+ if (form.status !== STATUS.pending) {
355
+ sendHtml(response, 410, renderNotice(noticeFor(form.status), undefined, { locale }));
356
+ return;
357
+ }
358
+ if (!isFormPost(request)) {
359
+ sendText(response, 415, 'Expected application/x-www-form-urlencoded');
360
+ return;
361
+ }
362
+
363
+ let body;
364
+ try {
365
+ body = await readFormBody(request);
366
+ } catch (error) {
367
+ sendText(response, error.status ?? 400, error.message);
368
+ return;
369
+ }
370
+
371
+ // 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
+
375
+ const action = body.get('action');
376
+ if (action === 'cancel') {
377
+ store.cancel(form);
378
+ logger?.info?.(`[dsh-secret-form] cancelled ${tokenTag(token)}`);
379
+ sendHtml(response, 200, renderNotice('cancelled', undefined, { locale }));
380
+ return;
381
+ }
382
+ if (action !== 'save') {
383
+ sendHtml(response, 400, pageFor(form, locale, { error: messages.errors.action }));
384
+ return;
385
+ }
386
+
387
+ const submission = store.beginSubmit(form, body.get('value') ?? '');
388
+ if (submission.outcome === 'invalid') {
389
+ sendHtml(response, 422, pageFor(form, locale, { error: messages.errors.empty }));
390
+ return;
391
+ }
392
+ if (submission.outcome === 'busy') {
393
+ sendHtml(response, 409, pageFor(form, locale, { error: messages.errors.busy }));
394
+ return;
395
+ }
396
+ if (submission.outcome !== 'ready') {
397
+ sendHtml(response, 410, renderNotice(noticeFor(form.status), undefined, { locale }));
398
+ return;
399
+ }
400
+
401
+ try {
402
+ await writeSecret(form.target, form.ref, submission.value, { credentials: credentialsOf() });
403
+ } catch (error) {
404
+ store.abortSubmit(form);
405
+ logger?.warn?.(`[dsh-secret-form] ${tokenTag(token)} could not be stored: ${error.message}`);
406
+ const detail = String(error.message).slice(0, 300);
407
+ sendHtml(response, 500, pageFor(form, locale, { error: format(messages.errors.store, { detail }) }));
408
+ return;
409
+ }
410
+
411
+ store.completeSubmit(form, submission);
412
+ logger?.info?.(`[dsh-secret-form] ${tokenTag(token)} ${form.status}`);
413
+ const note = submission.matchesExpect === false ? messages.mismatchNote : undefined;
414
+ sendHtml(response, 200, renderNotice(submission.empty ? 'empty' : 'saved', note, { locale }));
415
+ };
416
+ }
417
+
418
+ /**
419
+ * Mount the plugin: routes on the Web GUI host, tools on the agent surface.
420
+ * @param ctx - host context with `tools`, `webServer`, and an `effect` scope.
421
+ * @param config - see {@link normalizeConfig}.
422
+ */
423
+ export function apply(ctx, config = {}) {
424
+ const settings = normalizeConfig(config);
425
+ const store = createFormStore({ defaultTtlSeconds: settings.defaultTtlSeconds });
426
+ const logger = resolveLogger(ctx);
427
+ const credentialsOf = () => (typeof ctx?.get === 'function' ? ctx.get('credentials') : ctx?.credentials);
428
+ const handler = createRouteHandler({ store, settings, logger, credentialsOf });
429
+ const route = { kind: 'prefix', path: settings.routePrefix, handler };
430
+
431
+ if (typeof ctx?.webServer?.register !== 'function') {
432
+ throw new TypeError('dsh-secret-form: the webServer service is required');
433
+ }
434
+ if (typeof ctx.effect === 'function') {
435
+ ctx.effect(() => ctx.webServer.register(route), `dsh-secret-form: ${settings.routePrefix}`);
436
+ } else {
437
+ ctx.webServer.register(route);
438
+ }
439
+ registerTools(ctx, { store, settings, logger });
440
+ }
441
+
442
+ export default Object.freeze({ name, inject, apply, normalizeConfig });