@dokebi/module 0.4.1 → 0.4.2

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/dist/action.js ADDED
@@ -0,0 +1,498 @@
1
+ // Actions (D-0202, F-08): the write side of data sources. A module declares an action — its input
2
+ // fields (the shared field kinds of D-0199), the permission key, the scopes, whether it is
3
+ // dangerous (a preview, then a confirm) — and the function that runs it through the module's
4
+ // services. One general write runs every action for every caller (a form, another program, an AI
5
+ // through MCP): only declared input, field errors as 422, a version conflict as 409.
6
+ import { createHash } from 'node:crypto';
7
+ import { types } from 'node:util';
8
+ import { FIELD_TYPES } from './data-source.js';
9
+ /** Formats a text field may require. */
10
+ export const TEXT_FORMATS = ['email'];
11
+ /** Limits of one action (D-0202). */
12
+ export const ACTION_LIMITS = Object.freeze({
13
+ fields: 64,
14
+ scopes: 8,
15
+ choices: 64,
16
+ choiceValues: 32,
17
+ textChars: 1000,
18
+ textMaxChars: 100_000,
19
+ richtextBytes: 65_536,
20
+ richtextMaxBytes: 1_048_576,
21
+ idChars: 128,
22
+ previewBytes: 16_384,
23
+ resultBytes: 65_536,
24
+ });
25
+ const NAME = /^[a-z][a-z0-9_]{0,63}$/;
26
+ const CHOICE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;
27
+ const PERMISSION = /^[a-z0-9][a-z0-9_-]*(?:\.[a-z0-9][a-z0-9_-]*)+$/;
28
+ /** Kinds whose values are ids of something (a row, a person, an uploaded file). */
29
+ const ID_KINDS = new Set(['id', 'person', 'image', 'file']);
30
+ const CHOSEN = new Set(['status', 'choice', 'category']);
31
+ /** Field names the general write keeps for itself. */
32
+ const RESERVED = new Set(['confirm']);
33
+ /** Thrown for a declaration that breaks a rule (contract.ts makes it INVALID_CONTRACT). */
34
+ export class ActionIssue extends Error {
35
+ }
36
+ const plain = (value) => value !== null &&
37
+ typeof value === 'object' &&
38
+ !Array.isArray(value) &&
39
+ !types.isProxy(value) &&
40
+ [Object.prototype, null].includes(Object.getPrototypeOf(value));
41
+ function only(input, keys, where) {
42
+ const extra = Object.keys(input).find((name) => !keys.includes(name));
43
+ if (extra)
44
+ throw new ActionIssue(`${where} has an unknown field: ${extra}`);
45
+ }
46
+ const whole = (value, low, high) => Number.isInteger(value) && value >= low && value <= high;
47
+ /** The fields each kind accepts besides type, label and required. */
48
+ const OPTIONS = {
49
+ id: [],
50
+ person: [],
51
+ image: [],
52
+ file: [],
53
+ text: ['minLength', 'maxLength', 'format'],
54
+ richtext: ['maxBytes'],
55
+ number: ['min', 'max', 'integer'],
56
+ money: ['min', 'max', 'scale'],
57
+ date: [],
58
+ datetime: [],
59
+ boolean: [],
60
+ status: ['choices'],
61
+ choice: ['choices', 'multiple'],
62
+ category: ['choices'],
63
+ };
64
+ /**
65
+ * Checks one action declaration (the caller checks `title` and `description` and gives the label
66
+ * and permission checks of the contract).
67
+ */
68
+ export function readAction(input, where, label, permissionOf) {
69
+ only(input, [
70
+ 'title',
71
+ 'description',
72
+ 'input',
73
+ 'key',
74
+ 'version',
75
+ 'permission',
76
+ 'scopes',
77
+ 'scope',
78
+ 'danger',
79
+ 'preview',
80
+ 'run',
81
+ ], where);
82
+ if (typeof input.run !== 'function')
83
+ throw new ActionIssue(`${where}.run must be a function`);
84
+ const fields = {};
85
+ if (input.input !== undefined) {
86
+ if (!plain(input.input))
87
+ throw new ActionIssue(`${where}.input must be an object`);
88
+ const list = Object.entries(input.input);
89
+ if (list.length > ACTION_LIMITS.fields)
90
+ throw new ActionIssue(`${where}.input has more than ${ACTION_LIMITS.fields} fields`);
91
+ for (const [name, item] of list) {
92
+ const at = `${where}.input.${name}`;
93
+ if (!NAME.test(name))
94
+ throw new ActionIssue(`${where}.input has an invalid name: ${name}`);
95
+ if (RESERVED.has(name))
96
+ throw new ActionIssue(`${at}: ${name} is kept by the general write (the confirm token)`);
97
+ if (!plain(item))
98
+ throw new ActionIssue(`${at} must be an object`);
99
+ fields[name] = readField(item, at, label);
100
+ }
101
+ }
102
+ for (const key of ['key', 'version']) {
103
+ const name = input[key];
104
+ if (name === undefined)
105
+ continue;
106
+ if (typeof name !== 'string' || !Object.hasOwn(fields, name))
107
+ throw new ActionIssue(`${where}.${key} must name an input field`);
108
+ }
109
+ if (input.key !== undefined && fields[input.key]?.type !== 'id')
110
+ throw new ActionIssue(`${where}.key must name an input field of type id`);
111
+ if (input.version !== undefined) {
112
+ const field = fields[input.version];
113
+ if (!field?.required || (field.type !== 'number' && field.type !== 'text'))
114
+ throw new ActionIssue(`${where}.version must name a required number or text input field`);
115
+ }
116
+ if (typeof input.permission !== 'string' || !PERMISSION.test(input.permission))
117
+ throw new ActionIssue(`${where}.permission must be a permission key: every action needs one (writes are never public)`);
118
+ permissionOf(input.permission, `${where}.permission`);
119
+ let scopes;
120
+ if (input.scopes !== undefined) {
121
+ const value = input.scopes;
122
+ if (!Array.isArray(value) ||
123
+ types.isProxy(value) ||
124
+ value.length === 0 ||
125
+ value.length > ACTION_LIMITS.scopes ||
126
+ value.some((item) => typeof item !== 'string' || !NAME.test(item)) ||
127
+ new Set(value).size !== value.length)
128
+ throw new ActionIssue(`${where}.scopes must be 1 to ${ACTION_LIMITS.scopes} distinct names`);
129
+ scopes = Object.freeze([...value]);
130
+ }
131
+ if ((scopes === undefined) !== (input.scope === undefined))
132
+ throw new ActionIssue(`${where}: scopes and scope go together (the names and the function)`);
133
+ if (input.scope !== undefined && typeof input.scope !== 'function')
134
+ throw new ActionIssue(`${where}.scope must be a function`);
135
+ if (input.danger !== undefined && input.danger !== true)
136
+ throw new ActionIssue(`${where}.danger is true or left out`);
137
+ if ((input.danger === true) !== (input.preview !== undefined))
138
+ throw new ActionIssue(`${where}: danger and preview go together (a dangerous action shows what it would change first)`);
139
+ if (input.preview !== undefined && typeof input.preview !== 'function')
140
+ throw new ActionIssue(`${where}.preview must be a function`);
141
+ return {
142
+ input: Object.freeze(fields),
143
+ ...(input.key === undefined ? {} : { key: input.key }),
144
+ ...(input.version === undefined ? {} : { version: input.version }),
145
+ permission: input.permission,
146
+ ...(scopes === undefined ? {} : { scopes }),
147
+ ...(input.scope === undefined
148
+ ? {}
149
+ : { scope: input.scope }),
150
+ ...(input.danger === true ? { danger: true } : {}),
151
+ ...(input.preview === undefined
152
+ ? {}
153
+ : { preview: input.preview }),
154
+ run: input.run,
155
+ };
156
+ }
157
+ function readField(item, at, label) {
158
+ if (!FIELD_TYPES.includes(item.type))
159
+ throw new ActionIssue(`${at}.type must be one of ${FIELD_TYPES.join(', ')}`);
160
+ const type = item.type;
161
+ only(item, ['type', 'label', 'required', 'nullable', ...OPTIONS[type]], at);
162
+ for (const flag of ['required', 'nullable'])
163
+ if (item[flag] !== undefined && typeof item[flag] !== 'boolean')
164
+ throw new ActionIssue(`${at}.${flag} must be true or false`);
165
+ if (item.required && item.nullable !== undefined)
166
+ throw new ActionIssue(`${at}.nullable is for a field that is not required`);
167
+ const field = { type, label: label(item.label, `${at}.label`) };
168
+ if (item.required)
169
+ field.required = true;
170
+ if (item.nullable === false)
171
+ field.nullable = false;
172
+ if (type === 'text') {
173
+ const min = item.minLength ?? 0;
174
+ const max = item.maxLength ?? ACTION_LIMITS.textChars;
175
+ if (!whole(min, 0, ACTION_LIMITS.textMaxChars) || !whole(max, 1, ACTION_LIMITS.textMaxChars))
176
+ throw new ActionIssue(`${at}: minLength and maxLength are whole numbers up to ${ACTION_LIMITS.textMaxChars}`);
177
+ if (min > max)
178
+ throw new ActionIssue(`${at}.minLength is larger than maxLength`);
179
+ if (item.minLength !== undefined)
180
+ field.minLength = min;
181
+ field.maxLength = max;
182
+ if (item.format !== undefined) {
183
+ if (!TEXT_FORMATS.includes(item.format))
184
+ throw new ActionIssue(`${at}.format must be one of ${TEXT_FORMATS.join(', ')}`);
185
+ field.format = item.format;
186
+ }
187
+ }
188
+ if (type === 'richtext') {
189
+ const max = item.maxBytes ?? ACTION_LIMITS.richtextBytes;
190
+ if (!whole(max, 2, ACTION_LIMITS.richtextMaxBytes))
191
+ throw new ActionIssue(`${at}.maxBytes must be 2 to ${ACTION_LIMITS.richtextMaxBytes}`);
192
+ field.maxBytes = max;
193
+ }
194
+ if (type === 'number' || type === 'money') {
195
+ for (const bound of ['min', 'max'])
196
+ if (item[bound] !== undefined &&
197
+ (typeof item[bound] !== 'number' || !Number.isFinite(item[bound])))
198
+ throw new ActionIssue(`${at}.${bound} must be a number`);
199
+ if (item.min !== undefined &&
200
+ item.max !== undefined &&
201
+ item.min > item.max)
202
+ throw new ActionIssue(`${at}.min is larger than max`);
203
+ if (item.min !== undefined)
204
+ field.min = item.min;
205
+ if (item.max !== undefined)
206
+ field.max = item.max;
207
+ }
208
+ if (type === 'number' && item.integer !== undefined) {
209
+ if (typeof item.integer !== 'boolean')
210
+ throw new ActionIssue(`${at}.integer must be true or false`);
211
+ if (item.integer)
212
+ field.integer = true;
213
+ }
214
+ if (type === 'money') {
215
+ const scale = item.scale ?? 2;
216
+ if (!whole(scale, 0, 4))
217
+ throw new ActionIssue(`${at}.scale must be 0 to 4`);
218
+ field.scale = scale;
219
+ }
220
+ if (CHOSEN.has(type)) {
221
+ if (item.choices === undefined) {
222
+ if (type !== 'category')
223
+ throw new ActionIssue(`${at}.choices is required for a ${type} field`);
224
+ }
225
+ else {
226
+ if (!plain(item.choices))
227
+ throw new ActionIssue(`${at}.choices must be an object`);
228
+ const list = Object.entries(item.choices);
229
+ if (list.length === 0 || list.length > ACTION_LIMITS.choices)
230
+ throw new ActionIssue(`${at}.choices must have 1 to ${ACTION_LIMITS.choices} entries`);
231
+ const choices = {};
232
+ for (const [value, choice] of list) {
233
+ if (!CHOICE.test(value))
234
+ throw new ActionIssue(`${at}.choices has an invalid value: ${value}`);
235
+ if (!plain(choice))
236
+ throw new ActionIssue(`${at}.choices.${value} must be { label }`);
237
+ only(choice, ['label'], `${at}.choices.${value}`);
238
+ choices[value] = Object.freeze({
239
+ label: label(choice.label, `${at}.choices.${value}.label`),
240
+ });
241
+ }
242
+ field.choices = Object.freeze(choices);
243
+ }
244
+ }
245
+ if (type === 'choice' && item.multiple !== undefined) {
246
+ if (typeof item.multiple !== 'boolean')
247
+ throw new ActionIssue(`${at}.multiple must be true or false`);
248
+ if (item.multiple)
249
+ field.multiple = true;
250
+ }
251
+ return Object.freeze(field);
252
+ }
253
+ const EMAIL = /^[^\s@]{1,64}@[^\s@.]+(?:\.[^\s@.]+)+$/;
254
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
255
+ const DATETIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(?:Z|[+-](\d{2}):(\d{2}))$/;
256
+ const CONTROL = /\p{Cc}/u;
257
+ const realDate = (year, month, day) => {
258
+ const date = new Date(Date.UTC(year, month - 1, day));
259
+ return (date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day);
260
+ };
261
+ const empty = (value) => value === null ||
262
+ value === undefined ||
263
+ value === '' ||
264
+ (Array.isArray(value) && value.length === 0);
265
+ /** Checks one given value against its field: undefined when it is fine, else the problem. */
266
+ function fieldProblem(name, field, value, present) {
267
+ const problem = (rule, message) => ({ field: name, rule, message });
268
+ if (empty(value)) {
269
+ if (field.required)
270
+ return problem('required', 'is required');
271
+ return present && field.nullable === false ? problem('required', 'cannot be empty') : undefined;
272
+ }
273
+ switch (field.type) {
274
+ case 'id':
275
+ case 'person':
276
+ case 'image':
277
+ case 'file':
278
+ if ((typeof value === 'string' &&
279
+ value.length <= ACTION_LIMITS.idChars &&
280
+ value.trim() === value &&
281
+ !CONTROL.test(value)) ||
282
+ (Number.isSafeInteger(value) && value > 0))
283
+ return undefined;
284
+ return problem('type', 'must be an id');
285
+ case 'text': {
286
+ if (typeof value !== 'string')
287
+ return problem('type', 'must be text');
288
+ const length = [...value].length;
289
+ if (field.minLength !== undefined && length < field.minLength)
290
+ return problem('minLength', `must be at least ${field.minLength} characters`);
291
+ if (length > (field.maxLength ?? ACTION_LIMITS.textChars))
292
+ return problem('maxLength', `must be at most ${field.maxLength} characters`);
293
+ if (field.format === 'email' && (value.length > 254 || !EMAIL.test(value)))
294
+ return problem('format', 'must be an email address');
295
+ return undefined;
296
+ }
297
+ case 'richtext': {
298
+ if (!plain(value))
299
+ return problem('type', 'must be a rich text document (a JSON object)');
300
+ let bytes;
301
+ try {
302
+ bytes = Buffer.byteLength(JSON.stringify(value));
303
+ }
304
+ catch {
305
+ return problem('type', 'must be a rich text document (a JSON object)');
306
+ }
307
+ if (bytes > (field.maxBytes ?? ACTION_LIMITS.richtextBytes))
308
+ return problem('size', `must be at most ${field.maxBytes} bytes`);
309
+ return undefined;
310
+ }
311
+ case 'number':
312
+ if (typeof value !== 'number' || !Number.isFinite(value))
313
+ return problem('type', 'must be a number');
314
+ if (field.integer && !Number.isInteger(value))
315
+ return problem('integer', 'must be a whole number');
316
+ return bounds(field, value, problem);
317
+ case 'money': {
318
+ const scale = field.scale ?? 2;
319
+ const pattern = new RegExp(`^-?\\d{1,15}(?:\\.\\d{1,${scale}})?$`);
320
+ if (typeof value !== 'string' || !pattern.test(value))
321
+ return problem('type', scale === 0
322
+ ? 'must be an amount in whole units, such as 1200'
323
+ : `must be an amount with at most ${scale} digits after the point, such as 12.50`);
324
+ return bounds(field, Number(value), problem);
325
+ }
326
+ case 'date': {
327
+ const match = typeof value === 'string' ? DATE.exec(value) : null;
328
+ if (!match || !realDate(Number(match[1]), Number(match[2]), Number(match[3])))
329
+ return problem('type', 'must be a date such as 2026-11-12');
330
+ return undefined;
331
+ }
332
+ case 'datetime': {
333
+ const match = typeof value === 'string' ? DATETIME.exec(value) : null;
334
+ if (!match ||
335
+ !realDate(Number(match[1]), Number(match[2]), Number(match[3])) ||
336
+ Number(match[4]) > 23 ||
337
+ Number(match[5]) > 59 ||
338
+ Number(match[6] ?? 0) > 59 ||
339
+ Number(match[7] ?? 0) > 23 ||
340
+ Number(match[8] ?? 0) > 59)
341
+ return problem('type', 'must be a date and time with its offset, such as 2026-11-12T09:30:00Z');
342
+ return undefined;
343
+ }
344
+ case 'boolean':
345
+ return typeof value === 'boolean' ? undefined : problem('type', 'must be true or false');
346
+ case 'status':
347
+ case 'choice':
348
+ case 'category': {
349
+ const one = (item) => typeof item === 'string' &&
350
+ (field.choices ? Object.hasOwn(field.choices, item) : CHOICE.test(item));
351
+ const offered = field.choices ? Object.keys(field.choices).join(', ') : '';
352
+ const message = field.choices ? `must be one of: ${offered}` : 'must be a category value';
353
+ if (field.multiple) {
354
+ if (!Array.isArray(value) ||
355
+ value.length > ACTION_LIMITS.choiceValues ||
356
+ new Set(value).size !== value.length)
357
+ return problem('type', `must be a list of 1 to ${ACTION_LIMITS.choiceValues} distinct values`);
358
+ return value.every(one) ? undefined : problem('choice', message);
359
+ }
360
+ return one(value) ? undefined : problem('choice', message);
361
+ }
362
+ }
363
+ }
364
+ function bounds(field, value, problem) {
365
+ if (field.min !== undefined && value < field.min)
366
+ return problem('min', `must be at least ${field.min}`);
367
+ if (field.max !== undefined && value > field.max)
368
+ return problem('max', `must be at most ${field.max}`);
369
+ return undefined;
370
+ }
371
+ /**
372
+ * Checks an input object against the action's fields: an unknown field is refused as a whole
373
+ * (400), each wrong value is a field problem (422). Required fields are checked even when absent.
374
+ */
375
+ export function checkInput(fields, input) {
376
+ if (!plain(input))
377
+ return { ok: false, reason: 'body', message: 'input must be an object of field values' };
378
+ const unknown = Object.keys(input).find((name) => !Object.hasOwn(fields, name));
379
+ if (unknown !== undefined)
380
+ return {
381
+ ok: false,
382
+ reason: 'field',
383
+ name: unknown.slice(0, 64),
384
+ message: `The input field ${unknown.slice(0, 64)} is not declared by the action`,
385
+ };
386
+ const problems = [];
387
+ const given = {};
388
+ for (const [name, field] of Object.entries(fields)) {
389
+ const present = Object.hasOwn(input, name);
390
+ const value = present ? input[name] : undefined;
391
+ const problem = fieldProblem(name, field, value, present);
392
+ if (problem)
393
+ problems.push(problem);
394
+ else if (present)
395
+ given[name] = empty(value) ? null : value;
396
+ }
397
+ if (problems.length)
398
+ return { ok: false, reason: 'fields', problems };
399
+ return { ok: true, input: Object.freeze(given) };
400
+ }
401
+ /** JSON text with object keys sorted, for the confirm token. */
402
+ function canonical(value) {
403
+ if (Array.isArray(value))
404
+ return `[${value.map(canonical).join(',')}]`;
405
+ if (value !== null && typeof value === 'object')
406
+ return `{${Object.keys(value)
407
+ .sort()
408
+ .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)
409
+ .join(',')}}`;
410
+ return JSON.stringify(value) ?? 'null';
411
+ }
412
+ /**
413
+ * The confirm token of a dangerous action: a hash of the action, the actor, the checked input and
414
+ * the preview. The confirm call runs the preview again: the same token means the caller confirms
415
+ * what it was shown; a changed row gives another preview and another token (CONFIRM_STALE).
416
+ */
417
+ export function confirmToken(action, actor, input, preview) {
418
+ return createHash('sha256')
419
+ .update(canonical([1, action, actor.type, actor.id ?? null, actor.client ?? null, input, preview]))
420
+ .digest('base64url')
421
+ .slice(0, 32);
422
+ }
423
+ const label = (text) => typeof text === 'string' ? text : (text.en ?? Object.values(text)[0] ?? '');
424
+ /**
425
+ * The JSON Schema of an action's input (draft 2020-12, the keywords @dokebi/mcp accepts): what
426
+ * describe shows and what an MCP tool publishes. `confirm` is added for a dangerous action.
427
+ */
428
+ export function inputSchema(action) {
429
+ const properties = {};
430
+ const required = [];
431
+ for (const [name, field] of Object.entries(action.input ?? {})) {
432
+ const description = `${label(field.label)} (${field.type})`;
433
+ const nullable = (schema) => field.required || field.nullable === false
434
+ ? schema
435
+ : { anyOf: [schema, { type: 'null' }], description };
436
+ let schema;
437
+ if (ID_KINDS.has(field.type))
438
+ schema = {
439
+ anyOf: [
440
+ { type: 'string', minLength: 1, maxLength: ACTION_LIMITS.idChars },
441
+ { type: 'integer', minimum: 1 },
442
+ ],
443
+ };
444
+ else if (field.type === 'text')
445
+ schema = {
446
+ type: 'string',
447
+ ...(field.minLength === undefined ? {} : { minLength: field.minLength }),
448
+ maxLength: field.maxLength ?? ACTION_LIMITS.textChars,
449
+ ...(field.format === undefined ? {} : { format: field.format }),
450
+ };
451
+ else if (field.type === 'richtext')
452
+ schema = { type: 'object' };
453
+ else if (field.type === 'number')
454
+ schema = {
455
+ type: field.integer ? 'integer' : 'number',
456
+ ...(field.min === undefined ? {} : { minimum: field.min }),
457
+ ...(field.max === undefined ? {} : { maximum: field.max }),
458
+ };
459
+ else if (field.type === 'money')
460
+ schema = {
461
+ type: 'string',
462
+ pattern: `^-?[0-9]{1,15}(\\.[0-9]{1,${field.scale ?? 2}})?$`,
463
+ };
464
+ else if (field.type === 'date')
465
+ schema = { type: 'string', format: 'date' };
466
+ else if (field.type === 'datetime')
467
+ schema = { type: 'string', format: 'date-time' };
468
+ else if (field.type === 'boolean')
469
+ schema = { type: 'boolean' };
470
+ else {
471
+ const one = field.choices ? { enum: Object.keys(field.choices) } : { type: 'string' };
472
+ schema = field.multiple
473
+ ? {
474
+ type: 'array',
475
+ items: one,
476
+ minItems: 1,
477
+ maxItems: ACTION_LIMITS.choiceValues,
478
+ uniqueItems: true,
479
+ }
480
+ : one;
481
+ }
482
+ properties[name] = { ...nullable(schema), description };
483
+ if (field.required)
484
+ required.push(name);
485
+ }
486
+ if (action.danger)
487
+ properties.confirm = {
488
+ type: 'string',
489
+ maxLength: 64,
490
+ description: 'The confirm token of the preview: leave it out first, show the preview to the user, then call again with the same input and this token',
491
+ };
492
+ return {
493
+ type: 'object',
494
+ properties,
495
+ ...(required.length ? { required } : {}),
496
+ additionalProperties: false,
497
+ };
498
+ }