@dr-co/dsh-secret-form 0.2.0 → 0.4.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/README.md +179 -74
- package/index.mjs +622 -119
- package/lib/db.mjs +168 -0
- package/lib/forms.mjs +205 -68
- package/lib/i18n.mjs +128 -0
- package/lib/notify.mjs +234 -0
- package/lib/page.mjs +113 -6
- package/lib/shares.mjs +312 -0
- package/lib/upload.mjs +179 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +5 -4
package/lib/db.mjs
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The durable side of the plugin.
|
|
2
|
+
//
|
|
3
|
+
// Until 0.4.0 every form lived in process memory: a restart turned each pending
|
|
4
|
+
// form into `expired`, and the trade was "a one-time token never touches disk".
|
|
5
|
+
// Forms now outlive the process, so the token hash is what is written, never the
|
|
6
|
+
// token: a dump of this file does not open any link.
|
|
7
|
+
//
|
|
8
|
+
// One connection, opened by `apply()` and closed with the plugin scope. Node's
|
|
9
|
+
// own `node:sqlite` is synchronous, so every store method underneath is too —
|
|
10
|
+
// which is exactly what a form POST wants: a read, a decision and a write that
|
|
11
|
+
// no second request can interleave with.
|
|
12
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
13
|
+
import { chmodSync, mkdirSync } from 'node:fs';
|
|
14
|
+
import { homedir } from 'node:os';
|
|
15
|
+
import { dirname, join } from 'node:path';
|
|
16
|
+
|
|
17
|
+
/** Bumped when a table changes shape; a mismatch is a refusal, not a migration. */
|
|
18
|
+
export const SCHEMA_VERSION = 1;
|
|
19
|
+
|
|
20
|
+
const SCHEMA = `
|
|
21
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
22
|
+
key TEXT PRIMARY KEY,
|
|
23
|
+
value TEXT NOT NULL
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
-- One inbound request: the human types (or picks) a value and it lands in the
|
|
27
|
+
-- credential store or a file. The value itself is never a column of this table.
|
|
28
|
+
CREATE TABLE IF NOT EXISTS form (
|
|
29
|
+
uuid TEXT PRIMARY KEY,
|
|
30
|
+
token_hash TEXT NOT NULL UNIQUE,
|
|
31
|
+
ref TEXT NOT NULL,
|
|
32
|
+
label TEXT NOT NULL,
|
|
33
|
+
kind TEXT NOT NULL,
|
|
34
|
+
description TEXT,
|
|
35
|
+
target TEXT NOT NULL,
|
|
36
|
+
allow_empty INTEGER NOT NULL DEFAULT 0,
|
|
37
|
+
expect TEXT,
|
|
38
|
+
data TEXT NOT NULL DEFAULT '{}',
|
|
39
|
+
ttl_seconds INTEGER NOT NULL,
|
|
40
|
+
created_at INTEGER NOT NULL,
|
|
41
|
+
expires_at INTEGER NOT NULL,
|
|
42
|
+
status TEXT NOT NULL,
|
|
43
|
+
busy INTEGER NOT NULL DEFAULT 0,
|
|
44
|
+
finished_at INTEGER,
|
|
45
|
+
result TEXT,
|
|
46
|
+
session_id TEXT,
|
|
47
|
+
notify INTEGER NOT NULL DEFAULT 1,
|
|
48
|
+
notified_at INTEGER
|
|
49
|
+
);
|
|
50
|
+
CREATE INDEX IF NOT EXISTS form_created ON form (created_at);
|
|
51
|
+
CREATE INDEX IF NOT EXISTS form_open ON form (status, expires_at);
|
|
52
|
+
|
|
53
|
+
-- One outbound secret: the model hands a value over, the human opens the link
|
|
54
|
+
-- and presses the reveal button exactly once. The value lives encrypted in
|
|
55
|
+
-- share_secret, its one-shot key in share_key; both rows are dropped the moment
|
|
56
|
+
-- the secret is revealed, cancelled or expired.
|
|
57
|
+
CREATE TABLE IF NOT EXISTS share (
|
|
58
|
+
uuid TEXT PRIMARY KEY,
|
|
59
|
+
token_hash TEXT NOT NULL UNIQUE,
|
|
60
|
+
label TEXT NOT NULL,
|
|
61
|
+
kind TEXT NOT NULL,
|
|
62
|
+
description TEXT,
|
|
63
|
+
data TEXT NOT NULL DEFAULT '{}',
|
|
64
|
+
source TEXT NOT NULL DEFAULT 'file',
|
|
65
|
+
file_name TEXT,
|
|
66
|
+
ttl_seconds INTEGER NOT NULL,
|
|
67
|
+
created_at INTEGER NOT NULL,
|
|
68
|
+
expires_at INTEGER NOT NULL,
|
|
69
|
+
status TEXT NOT NULL,
|
|
70
|
+
views INTEGER NOT NULL DEFAULT 0,
|
|
71
|
+
revealed_at INTEGER,
|
|
72
|
+
finished_at INTEGER,
|
|
73
|
+
session_id TEXT,
|
|
74
|
+
notify INTEGER NOT NULL DEFAULT 1,
|
|
75
|
+
notified_at INTEGER
|
|
76
|
+
);
|
|
77
|
+
CREATE INDEX IF NOT EXISTS share_created ON share (created_at);
|
|
78
|
+
CREATE INDEX IF NOT EXISTS share_open ON share (status, expires_at);
|
|
79
|
+
|
|
80
|
+
CREATE TABLE IF NOT EXISTS share_secret (
|
|
81
|
+
uuid TEXT PRIMARY KEY REFERENCES share (uuid) ON DELETE CASCADE,
|
|
82
|
+
alg TEXT NOT NULL,
|
|
83
|
+
iv TEXT NOT NULL,
|
|
84
|
+
tag TEXT NOT NULL,
|
|
85
|
+
ciphertext TEXT NOT NULL
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
CREATE TABLE IF NOT EXISTS share_key (
|
|
89
|
+
uuid TEXT PRIMARY KEY REFERENCES share (uuid) ON DELETE CASCADE,
|
|
90
|
+
key TEXT NOT NULL
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
-- Notes waiting for a session: placed through the schedule service, exactly the
|
|
94
|
+
-- way the graceful-restart plugin wakes a session after the host comes back.
|
|
95
|
+
CREATE TABLE IF NOT EXISTS note (
|
|
96
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
97
|
+
uuid TEXT NOT NULL,
|
|
98
|
+
kind TEXT NOT NULL,
|
|
99
|
+
session_id TEXT NOT NULL,
|
|
100
|
+
title TEXT NOT NULL,
|
|
101
|
+
prompt TEXT NOT NULL,
|
|
102
|
+
created_at INTEGER NOT NULL,
|
|
103
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
104
|
+
last_error TEXT
|
|
105
|
+
);
|
|
106
|
+
CREATE INDEX IF NOT EXISTS note_session ON note (session_id);
|
|
107
|
+
`;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Where the plugin keeps its database when the config names no file.
|
|
111
|
+
* `$DSH_HOME/storages` is the directory the other plugins already use.
|
|
112
|
+
*/
|
|
113
|
+
export function defaultDatabasePath({ home = process.env.DSH_HOME } = {}) {
|
|
114
|
+
const root = typeof home === 'string' && home.trim() !== '' ? home.trim() : join(homedir(), '.dsh');
|
|
115
|
+
return join(root, 'storages', 'dsh-secret-form.sqlite');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Open (and, on first use, create) the plugin database.
|
|
120
|
+
* @param file - absolute path, or `:memory:` for tests.
|
|
121
|
+
*/
|
|
122
|
+
export function openDatabase(file) {
|
|
123
|
+
if (typeof file !== 'string' || file.trim() === '') {
|
|
124
|
+
throw new TypeError('dsh-secret-form: database must be a file path');
|
|
125
|
+
}
|
|
126
|
+
const path = file.trim();
|
|
127
|
+
if (path !== ':memory:') {
|
|
128
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
129
|
+
// A copy of this file names every open form and holds every unclaimed
|
|
130
|
+
// outbound secret, so it is readable by its owner only.
|
|
131
|
+
try {
|
|
132
|
+
chmodSync(dirname(path), 0o700);
|
|
133
|
+
} catch {}
|
|
134
|
+
}
|
|
135
|
+
const db = new DatabaseSync(path);
|
|
136
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
137
|
+
db.exec('PRAGMA synchronous = NORMAL');
|
|
138
|
+
db.exec('PRAGMA busy_timeout = 3000');
|
|
139
|
+
db.exec('PRAGMA foreign_keys = ON');
|
|
140
|
+
db.exec(SCHEMA);
|
|
141
|
+
if (path !== ':memory:') {
|
|
142
|
+
// WAL adds `-wal` and `-shm` beside the database; the prefix keeps them
|
|
143
|
+
// under the same mode, and the database itself is set after the first write.
|
|
144
|
+
for (const suffix of ['', '-wal', '-shm']) {
|
|
145
|
+
try {
|
|
146
|
+
chmodSync(`${path}${suffix}`, 0o600);
|
|
147
|
+
} catch {}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const stored = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
151
|
+
if (stored === undefined) {
|
|
152
|
+
db.prepare("INSERT INTO meta (key, value) VALUES ('schema_version', ?)").run(String(SCHEMA_VERSION));
|
|
153
|
+
} else if (Number(stored.value) !== SCHEMA_VERSION) {
|
|
154
|
+
db.close();
|
|
155
|
+
throw new Error(
|
|
156
|
+
`dsh-secret-form: ${path} holds schema version ${stored.value}, this build needs ${SCHEMA_VERSION}; `
|
|
157
|
+
+ 'move the file aside to start a fresh one',
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
return db;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Best-effort close: a store already closed by its scope must not throw twice. */
|
|
164
|
+
export function closeDatabase(db) {
|
|
165
|
+
try {
|
|
166
|
+
db?.close();
|
|
167
|
+
} catch {}
|
|
168
|
+
}
|
package/lib/forms.mjs
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
// The
|
|
1
|
+
// The inbound form registry.
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
// caller
|
|
8
|
-
|
|
3
|
+
// A form is a request for a value: the model creates one, the human opens the
|
|
4
|
+
// link and either types the value (`single`, `multi`) or picks a file (`file`).
|
|
5
|
+
// The registry owns the state machine and the validation; it stores rows in the
|
|
6
|
+
// plugin database (see lib/db.mjs) and never stores the value itself — the
|
|
7
|
+
// caller writes that to its target and reports back the aggregate facts.
|
|
8
|
+
//
|
|
9
|
+
// Tokens are stored as SHA-256 hashes: the token is the capability, and a copy
|
|
10
|
+
// of the database must not hand it out.
|
|
11
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
9
12
|
|
|
10
13
|
export const STATUS = Object.freeze({
|
|
11
14
|
pending: 'pending',
|
|
@@ -22,11 +25,11 @@ export const DEFAULT_WAIT_SECONDS = 0;
|
|
|
22
25
|
export const MAX_WAIT_SECONDS = 30;
|
|
23
26
|
export const MAX_DATA_BYTES = 1024;
|
|
24
27
|
export const MAX_DESCRIPTION_CHARS = 300;
|
|
28
|
+
export const KINDS = Object.freeze(['single', 'multi', 'file']);
|
|
25
29
|
|
|
26
30
|
// A finished form keeps answering its link ("already used", "cancelled") for an
|
|
27
|
-
// hour past expiry; after that a
|
|
28
|
-
|
|
29
|
-
const RETAIN_MS = 3_600_000;
|
|
31
|
+
// hour past expiry; after that a sweep drops it and the link reads as unknown.
|
|
32
|
+
export const RETAIN_MS = 3_600_000;
|
|
30
33
|
|
|
31
34
|
function invalid(message) {
|
|
32
35
|
const error = new TypeError(message);
|
|
@@ -34,6 +37,11 @@ function invalid(message) {
|
|
|
34
37
|
return error;
|
|
35
38
|
}
|
|
36
39
|
|
|
40
|
+
/** SHA-256 of a link token, hex. The only form in which a token is persisted. */
|
|
41
|
+
export function hashToken(token) {
|
|
42
|
+
return createHash('sha256').update(String(token), 'utf8').digest('hex');
|
|
43
|
+
}
|
|
44
|
+
|
|
37
45
|
/**
|
|
38
46
|
* Clamp a TTL into the supported window.
|
|
39
47
|
* @param seconds - requested TTL; undefined takes the default.
|
|
@@ -55,7 +63,8 @@ export function normalizeWait(seconds) {
|
|
|
55
63
|
return seconds;
|
|
56
64
|
}
|
|
57
65
|
|
|
58
|
-
|
|
66
|
+
/** Validate the `data` bookkeeping object of `secret_create` and `secret_share`. */
|
|
67
|
+
export function normalizeData(data) {
|
|
59
68
|
if (data === undefined || data === null) return {};
|
|
60
69
|
if (typeof data !== 'object' || Array.isArray(data)) throw invalid('data must be a JSON object');
|
|
61
70
|
const clone = structuredClone(data);
|
|
@@ -76,13 +85,14 @@ function normalizeExpect(expect) {
|
|
|
76
85
|
if (expect === undefined || expect === null || expect === '') return undefined;
|
|
77
86
|
if (typeof expect !== 'string') throw invalid('expect must be a string holding a regular expression');
|
|
78
87
|
try {
|
|
79
|
-
return
|
|
88
|
+
return new RegExp(expect);
|
|
80
89
|
} catch (error) {
|
|
81
90
|
throw invalid(`expect is not a valid regular expression: ${error.message}`);
|
|
82
91
|
}
|
|
83
92
|
}
|
|
84
93
|
|
|
85
|
-
|
|
94
|
+
/** Validate the form title. */
|
|
95
|
+
export function normalizeLabel(label) {
|
|
86
96
|
if (typeof label !== 'string') throw invalid('label must be a string');
|
|
87
97
|
const text = label.trim();
|
|
88
98
|
if (text === '') throw invalid('label must not be empty');
|
|
@@ -92,7 +102,8 @@ function normalizeLabel(label) {
|
|
|
92
102
|
return text;
|
|
93
103
|
}
|
|
94
104
|
|
|
95
|
-
|
|
105
|
+
/** Validate the optional sentence under the title. */
|
|
106
|
+
export function normalizeDescription(description) {
|
|
96
107
|
if (description === undefined || description === null) return undefined;
|
|
97
108
|
if (typeof description !== 'string') throw invalid('description must be a string');
|
|
98
109
|
const text = description.trim();
|
|
@@ -104,7 +115,7 @@ function normalizeDescription(description) {
|
|
|
104
115
|
}
|
|
105
116
|
|
|
106
117
|
function normalizeKind(kind) {
|
|
107
|
-
if (kind
|
|
118
|
+
if (!KINDS.includes(kind)) throw invalid(`kind must be one of: ${KINDS.join(', ')}`);
|
|
108
119
|
return kind;
|
|
109
120
|
}
|
|
110
121
|
|
|
@@ -121,12 +132,28 @@ export function normalizeSubmission(raw, kind) {
|
|
|
121
132
|
return { value, trimmed: stripped !== text };
|
|
122
133
|
}
|
|
123
134
|
|
|
135
|
+
function countLines(value) {
|
|
136
|
+
return value === '' ? 0 : value.split('\n').length;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Facts about a stored file, as returned to the model. Never its content. */
|
|
140
|
+
function fileFacts(file) {
|
|
141
|
+
if (file === undefined || file === null) return {};
|
|
142
|
+
return {
|
|
143
|
+
fileName: file.fileName,
|
|
144
|
+
size: file.size,
|
|
145
|
+
sha256: file.sha256,
|
|
146
|
+
path: file.path,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
124
150
|
/**
|
|
125
151
|
* Project a form into the aggregate facts the model may see.
|
|
126
152
|
* The value itself never leaves this module.
|
|
127
153
|
*/
|
|
128
154
|
export function publicResult(form) {
|
|
129
155
|
return {
|
|
156
|
+
type: 'form',
|
|
130
157
|
status: form.status,
|
|
131
158
|
data: form.data,
|
|
132
159
|
ref: form.ref,
|
|
@@ -136,6 +163,7 @@ export function publicResult(form) {
|
|
|
136
163
|
lines: form.result.lines,
|
|
137
164
|
trimmed: form.result.trimmed,
|
|
138
165
|
...(form.result.matchesExpect === undefined ? {} : { matchesExpect: form.result.matchesExpect }),
|
|
166
|
+
...(form.kind === 'file' ? fileFacts(form.result.file) : {}),
|
|
139
167
|
}),
|
|
140
168
|
};
|
|
141
169
|
}
|
|
@@ -144,6 +172,7 @@ export function publicResult(form) {
|
|
|
144
172
|
export function publicSummary(form) {
|
|
145
173
|
return {
|
|
146
174
|
uuid: form.uuid,
|
|
175
|
+
type: 'form',
|
|
147
176
|
ref: form.ref,
|
|
148
177
|
label: form.label,
|
|
149
178
|
status: form.status,
|
|
@@ -153,29 +182,95 @@ export function publicSummary(form) {
|
|
|
153
182
|
};
|
|
154
183
|
}
|
|
155
184
|
|
|
185
|
+
function parseJson(text, fallback) {
|
|
186
|
+
if (typeof text !== 'string' || text === '') return fallback;
|
|
187
|
+
try {
|
|
188
|
+
return JSON.parse(text);
|
|
189
|
+
} catch {
|
|
190
|
+
return fallback;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function rowToForm(row) {
|
|
195
|
+
return {
|
|
196
|
+
uuid: row.uuid,
|
|
197
|
+
ref: row.ref,
|
|
198
|
+
label: row.label,
|
|
199
|
+
kind: row.kind,
|
|
200
|
+
description: row.description ?? undefined,
|
|
201
|
+
target: parseJson(row.target, { kind: 'credentials' }),
|
|
202
|
+
allowEmpty: row.allow_empty === 1,
|
|
203
|
+
expectSource: row.expect ?? undefined,
|
|
204
|
+
data: parseJson(row.data, {}),
|
|
205
|
+
ttlSeconds: row.ttl_seconds,
|
|
206
|
+
createdAt: row.created_at,
|
|
207
|
+
expiresAt: row.expires_at,
|
|
208
|
+
status: row.status,
|
|
209
|
+
busy: row.busy === 1,
|
|
210
|
+
finishedAt: row.finished_at ?? undefined,
|
|
211
|
+
result: parseJson(row.result, undefined),
|
|
212
|
+
sessionId: row.session_id ?? null,
|
|
213
|
+
notify: row.notify === 1,
|
|
214
|
+
notifiedAt: row.notified_at ?? undefined,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
156
218
|
/**
|
|
157
|
-
* Create the
|
|
158
|
-
* @param options - `
|
|
159
|
-
* move the clock instead of sleeping.
|
|
219
|
+
* Create the form registry over an open database.
|
|
220
|
+
* @param options - `db` (opened by lib/db.mjs), `now`, `defaultTtlSeconds`.
|
|
160
221
|
*/
|
|
161
|
-
export function createFormStore({ now = () => Date.now(), defaultTtlSeconds = DEFAULT_TTL_SECONDS } = {}) {
|
|
162
|
-
|
|
163
|
-
|
|
222
|
+
export function createFormStore({ db, now = () => Date.now(), defaultTtlSeconds = DEFAULT_TTL_SECONDS } = {}) {
|
|
223
|
+
if (db === undefined || typeof db.prepare !== 'function') {
|
|
224
|
+
throw new TypeError('dsh-secret-form: the form store needs an open database');
|
|
225
|
+
}
|
|
226
|
+
const sql = {
|
|
227
|
+
insert: db.prepare(`INSERT INTO form (
|
|
228
|
+
uuid, token_hash, ref, label, kind, description, target, allow_empty, expect, data,
|
|
229
|
+
ttl_seconds, created_at, expires_at, status, busy, session_id, notify
|
|
230
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`),
|
|
231
|
+
byToken: db.prepare('SELECT * FROM form WHERE token_hash = ?'),
|
|
232
|
+
byUuid: db.prepare('SELECT * FROM form WHERE uuid = ?'),
|
|
233
|
+
all: db.prepare('SELECT * FROM form ORDER BY created_at'),
|
|
234
|
+
due: db.prepare("UPDATE form SET status = 'expired', finished_at = ?, busy = 0 WHERE status = 'pending' AND expires_at <= ?"),
|
|
235
|
+
stale: db.prepare("UPDATE form SET busy = 0 WHERE status = 'pending' AND busy = 1"),
|
|
236
|
+
state: db.prepare('UPDATE form SET status = ?, busy = ?, finished_at = ?, result = ? WHERE uuid = ?'),
|
|
237
|
+
cancelled: db.prepare("UPDATE form SET status = 'cancelled', finished_at = ?, busy = 0 WHERE uuid = ? AND status = 'pending'"),
|
|
238
|
+
notified: db.prepare('UPDATE form SET notified_at = ? WHERE uuid = ?'),
|
|
239
|
+
purge: db.prepare('DELETE FROM form WHERE status <> ? AND finished_at IS NOT NULL AND finished_at <= ?'),
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
const waiters = new Map();
|
|
243
|
+
|
|
244
|
+
const wake = (uuid) => {
|
|
245
|
+
const set = waiters.get(uuid);
|
|
246
|
+
if (set === undefined) return;
|
|
247
|
+
for (const resume of [...set]) resume();
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const persist = (form) => {
|
|
251
|
+
sql.state.run(
|
|
252
|
+
form.status,
|
|
253
|
+
form.busy ? 1 : 0,
|
|
254
|
+
form.finishedAt ?? null,
|
|
255
|
+
form.result === undefined ? null : JSON.stringify(form.result),
|
|
256
|
+
form.uuid,
|
|
257
|
+
);
|
|
258
|
+
};
|
|
164
259
|
|
|
165
260
|
const finish = (form, status, result) => {
|
|
166
261
|
form.status = status;
|
|
167
262
|
form.finishedAt = now();
|
|
168
263
|
form.busy = false;
|
|
169
264
|
if (result !== undefined) form.result = result;
|
|
170
|
-
|
|
171
|
-
form.
|
|
265
|
+
persist(form);
|
|
266
|
+
wake(form.uuid);
|
|
267
|
+
return form;
|
|
172
268
|
};
|
|
173
269
|
|
|
174
270
|
const expireIfDue = (form) => {
|
|
175
271
|
if (form.status !== STATUS.pending) return form;
|
|
176
272
|
if (now() < form.expiresAt) return form;
|
|
177
|
-
finish(form, STATUS.expired);
|
|
178
|
-
return form;
|
|
273
|
+
return finish(form, STATUS.expired);
|
|
179
274
|
};
|
|
180
275
|
|
|
181
276
|
const store = {
|
|
@@ -183,16 +278,17 @@ export function createFormStore({ now = () => Date.now(), defaultTtlSeconds = DE
|
|
|
183
278
|
create(spec) {
|
|
184
279
|
const createdAt = now();
|
|
185
280
|
const ttlSeconds = clampTtl(spec.ttlSeconds, defaultTtlSeconds);
|
|
281
|
+
const token = randomBytes(32).toString('base64url');
|
|
186
282
|
const form = {
|
|
187
283
|
uuid: randomUUID(),
|
|
188
|
-
token
|
|
284
|
+
token,
|
|
189
285
|
ref: spec.ref,
|
|
190
286
|
label: normalizeLabel(spec.label),
|
|
191
287
|
kind: normalizeKind(spec.kind),
|
|
192
288
|
description: normalizeDescription(spec.description),
|
|
193
289
|
target: spec.target,
|
|
194
290
|
allowEmpty: spec.allowEmpty === true,
|
|
195
|
-
expect:
|
|
291
|
+
expectSource: spec.expect === undefined ? undefined : String(spec.expect),
|
|
196
292
|
data: normalizeData(spec.data),
|
|
197
293
|
ttlSeconds,
|
|
198
294
|
createdAt,
|
|
@@ -201,35 +297,55 @@ export function createFormStore({ now = () => Date.now(), defaultTtlSeconds = DE
|
|
|
201
297
|
finishedAt: undefined,
|
|
202
298
|
result: undefined,
|
|
203
299
|
busy: false,
|
|
204
|
-
|
|
300
|
+
sessionId: typeof spec.sessionId === 'string' && spec.sessionId !== '' ? spec.sessionId : null,
|
|
301
|
+
notify: spec.notify === true,
|
|
302
|
+
notifiedAt: undefined,
|
|
205
303
|
};
|
|
206
|
-
|
|
207
|
-
|
|
304
|
+
if (form.expectSource !== undefined) normalizeExpect(form.expectSource);
|
|
305
|
+
sql.insert.run(
|
|
306
|
+
form.uuid,
|
|
307
|
+
hashToken(token),
|
|
308
|
+
form.ref,
|
|
309
|
+
form.label,
|
|
310
|
+
form.kind,
|
|
311
|
+
form.description ?? null,
|
|
312
|
+
JSON.stringify(form.target),
|
|
313
|
+
form.allowEmpty ? 1 : 0,
|
|
314
|
+
form.expectSource ?? null,
|
|
315
|
+
JSON.stringify(form.data),
|
|
316
|
+
form.ttlSeconds,
|
|
317
|
+
form.createdAt,
|
|
318
|
+
form.expiresAt,
|
|
319
|
+
form.status,
|
|
320
|
+
form.sessionId,
|
|
321
|
+
form.notify ? 1 : 0,
|
|
322
|
+
);
|
|
208
323
|
return form;
|
|
209
324
|
},
|
|
210
325
|
|
|
211
326
|
/** Resolve a link token, expiring it first when its window has passed. */
|
|
212
327
|
lookup(token) {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
328
|
+
if (typeof token !== 'string' || token === '') return undefined;
|
|
329
|
+
const row = sql.byToken.get(hashToken(token));
|
|
330
|
+
if (row === undefined) return undefined;
|
|
331
|
+
return expireIfDue(rowToForm(row));
|
|
216
332
|
},
|
|
217
333
|
|
|
218
334
|
/** Resolve a form by the uuid the model holds. */
|
|
219
335
|
require(uuid) {
|
|
220
|
-
const
|
|
221
|
-
if (
|
|
222
|
-
return expireIfDue(
|
|
336
|
+
const row = typeof uuid === 'string' ? sql.byUuid.get(uuid) : undefined;
|
|
337
|
+
if (row === undefined) throw invalid(`unknown secret form ${JSON.stringify(uuid ?? null)}`);
|
|
338
|
+
return expireIfDue(rowToForm(row));
|
|
223
339
|
},
|
|
224
340
|
|
|
225
|
-
/** Every form
|
|
341
|
+
/** Every form the database still holds, oldest first. */
|
|
226
342
|
list() {
|
|
227
343
|
store.sweep();
|
|
228
|
-
return
|
|
344
|
+
return sql.all.all().map(rowToForm);
|
|
229
345
|
},
|
|
230
346
|
|
|
231
347
|
/**
|
|
232
|
-
* Start a submission. The caller stores the value and then reports the
|
|
348
|
+
* Start a text submission. The caller stores the value and then reports the
|
|
233
349
|
* outcome, so a failed write never reads as saved.
|
|
234
350
|
* @returns `{ outcome }` plus the normalised value when `outcome` is `ready`.
|
|
235
351
|
*/
|
|
@@ -242,39 +358,61 @@ export function createFormStore({ now = () => Date.now(), defaultTtlSeconds = DE
|
|
|
242
358
|
value,
|
|
243
359
|
trimmed,
|
|
244
360
|
length: [...value].length,
|
|
245
|
-
lines: value
|
|
246
|
-
matchesExpect: form.
|
|
361
|
+
lines: countLines(value),
|
|
362
|
+
matchesExpect: form.expectSource === undefined ? undefined : new RegExp(form.expectSource).test(value),
|
|
247
363
|
};
|
|
248
364
|
if (value === '' && !form.allowEmpty) return { outcome: 'invalid', ...facts };
|
|
249
365
|
form.busy = true;
|
|
366
|
+
persist(form);
|
|
250
367
|
return { outcome: 'ready', empty: value === '', ...facts };
|
|
251
368
|
},
|
|
252
369
|
|
|
253
|
-
/**
|
|
370
|
+
/** Start a file submission: the caller receives the upload and reports facts. */
|
|
371
|
+
beginUpload(form) {
|
|
372
|
+
expireIfDue(form);
|
|
373
|
+
if (form.status !== STATUS.pending) return { outcome: 'terminal' };
|
|
374
|
+
if (form.busy) return { outcome: 'busy' };
|
|
375
|
+
form.busy = true;
|
|
376
|
+
persist(form);
|
|
377
|
+
return { outcome: 'ready' };
|
|
378
|
+
},
|
|
379
|
+
|
|
380
|
+
/** Mark a submission finished after the value (or file) reached its target. */
|
|
254
381
|
completeSubmit(form, submission) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
},
|
|
264
|
-
);
|
|
265
|
-
return form;
|
|
382
|
+
const file = submission.file === undefined ? undefined : submission.file;
|
|
383
|
+
return finish(form, submission.empty ? STATUS.empty : STATUS.saved, {
|
|
384
|
+
length: file === undefined ? submission.length : 0,
|
|
385
|
+
lines: file === undefined ? submission.lines : 0,
|
|
386
|
+
trimmed: submission.trimmed === true,
|
|
387
|
+
matchesExpect: submission.matchesExpect,
|
|
388
|
+
...(file === undefined ? {} : { file }),
|
|
389
|
+
});
|
|
266
390
|
},
|
|
267
391
|
|
|
268
392
|
/** Return a form to `pending` after the target refused the write. */
|
|
269
393
|
abortSubmit(form) {
|
|
270
394
|
form.busy = false;
|
|
395
|
+
persist(form);
|
|
271
396
|
return form;
|
|
272
397
|
},
|
|
273
398
|
|
|
274
399
|
/** Cancel a pending form; a finished form reports its current status. */
|
|
275
400
|
cancel(form) {
|
|
276
401
|
expireIfDue(form);
|
|
277
|
-
if (form.status
|
|
402
|
+
if (form.status !== STATUS.pending) return form;
|
|
403
|
+
const at = now();
|
|
404
|
+
sql.cancelled.run(at, form.uuid);
|
|
405
|
+
form.status = STATUS.cancelled;
|
|
406
|
+
form.finishedAt = at;
|
|
407
|
+
form.busy = false;
|
|
408
|
+
wake(form.uuid);
|
|
409
|
+
return form;
|
|
410
|
+
},
|
|
411
|
+
|
|
412
|
+
/** Record that the note about this form was delivered. */
|
|
413
|
+
markNotified(form, at = now()) {
|
|
414
|
+
form.notifiedAt = at;
|
|
415
|
+
sql.notified.run(at, form.uuid);
|
|
278
416
|
return form;
|
|
279
417
|
},
|
|
280
418
|
|
|
@@ -286,32 +424,31 @@ export function createFormStore({ now = () => Date.now(), defaultTtlSeconds = DE
|
|
|
286
424
|
expireIfDue(form);
|
|
287
425
|
if (form.status !== STATUS.pending || !(ms > 0)) return form;
|
|
288
426
|
await new Promise((resolve) => {
|
|
289
|
-
const
|
|
427
|
+
const set = waiters.get(form.uuid) ?? new Set();
|
|
428
|
+
waiters.set(form.uuid, set);
|
|
429
|
+
const resume = () => {
|
|
290
430
|
clearTimeout(timer);
|
|
291
|
-
|
|
431
|
+
set.delete(resume);
|
|
432
|
+
if (set.size === 0) waiters.delete(form.uuid);
|
|
292
433
|
resolve();
|
|
293
434
|
};
|
|
294
|
-
const timer = setTimeout(
|
|
295
|
-
|
|
435
|
+
const timer = setTimeout(resume, ms);
|
|
436
|
+
set.add(resume);
|
|
296
437
|
});
|
|
297
|
-
return form;
|
|
438
|
+
return store.require(form.uuid);
|
|
298
439
|
},
|
|
299
440
|
|
|
300
441
|
/** Expire overdue forms and drop finished ones past their retention. */
|
|
301
|
-
sweep() {
|
|
442
|
+
sweep({ retainMs = RETAIN_MS } = {}) {
|
|
302
443
|
const at = now();
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
if (form.finishedAt !== undefined && form.finishedAt + RETAIN_MS > at) continue;
|
|
307
|
-
byToken.delete(token);
|
|
308
|
-
byUuid.delete(form.uuid);
|
|
309
|
-
}
|
|
444
|
+
sql.due.run(at, at);
|
|
445
|
+
sql.stale.run();
|
|
446
|
+
sql.purge.run(STATUS.pending, at - retainMs);
|
|
310
447
|
return store;
|
|
311
448
|
},
|
|
312
449
|
|
|
313
450
|
get size() {
|
|
314
|
-
return
|
|
451
|
+
return db.prepare('SELECT COUNT(*) AS n FROM form').get().n;
|
|
315
452
|
},
|
|
316
453
|
};
|
|
317
454
|
return store;
|