@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.
@@ -0,0 +1,249 @@
1
+ // The general write of actions (D-0202): one runner for every caller of every module's actions —
2
+ // the route `POST <path>/:module/:action`, the group API and the MCP tools of @dokebi/module/mcp.
3
+ // It checks the caller's permission and scope, the input against the declaration (unknown fields
4
+ // 400, wrong values 422), runs a dangerous action only with the token of its preview, and checks
5
+ // that the result is JSON.
6
+ import { DokebiError } from '@dokebi/core';
7
+ import { ACTION_LIMITS, checkInput, confirmToken, } from './action.js';
8
+ const STATUS = {
9
+ ACTION_NOT_FOUND: 404,
10
+ FORBIDDEN: 403,
11
+ INVALID_INPUT: 400,
12
+ VALIDATION_FAILED: 422,
13
+ ACTION_CONFLICT: 409,
14
+ CONFIRM_REQUIRED: 428,
15
+ CONFIRM_STALE: 409,
16
+ ACTION_FAILED: 500,
17
+ };
18
+ const FIX = {
19
+ ACTION_NOT_FOUND: 'Run an action that npx dokebi describe --json lists under app.modules[].actions, as <module>.<name>.',
20
+ FORBIDDEN: 'Sign in with an account that holds the action permission (its scope must not be empty), or leave the action out.',
21
+ INVALID_INPUT: 'Send { input: { <declared field>: value } } and, for a dangerous action, confirm: <the token of its preview>; nothing else. data.reason and data.name say what was refused.',
22
+ VALIDATION_FAILED: 'Correct the fields named in fields (a fixed message each; data.rules names the broken rule) and send the input again.',
23
+ ACTION_CONFLICT: 'Read the row again (its new version) and send the change again on top of it.',
24
+ CONFIRM_REQUIRED: 'Show data.preview to the user; when they agree, send the same input with confirm: data.confirm.',
25
+ CONFIRM_STALE: 'The row changed after the preview: show the new data.preview and send confirm: data.confirm when the user agrees.',
26
+ ACTION_FAILED: 'Correct the action as the message says: its scope function answers one of its scopes, its preview and result are JSON of at most the documented size.',
27
+ };
28
+ const HINT = {
29
+ ACTION_NOT_FOUND: 'This action does not exist.',
30
+ FORBIDDEN: 'You are not allowed to do this.',
31
+ VALIDATION_FAILED: 'Check the highlighted fields.',
32
+ ACTION_CONFLICT: 'Someone changed this in the meantime. Load it again.',
33
+ CONFIRM_REQUIRED: 'Confirm to continue.',
34
+ CONFIRM_STALE: 'It changed in the meantime. Check again and confirm.',
35
+ };
36
+ export function actionError(code, message, data, cause) {
37
+ return new DokebiError(code, message, {
38
+ plugin: 'dokebi-module',
39
+ status: STATUS[code],
40
+ fix: FIX[code],
41
+ ...(HINT[code] === undefined ? {} : { hint: HINT[code] }),
42
+ ...(data === undefined ? {} : { data }),
43
+ ...(cause === undefined ? {} : { cause }),
44
+ });
45
+ }
46
+ /**
47
+ * 422 with the refused fields, in the shape @dokebi/web answers (`fields`, `errors`) and
48
+ * template-inertia turns into a validation redirect. `data.rules` names the rule per field.
49
+ */
50
+ export class ActionValidationError extends DokebiError {
51
+ fields;
52
+ errors;
53
+ constructor(problems, action) {
54
+ const rules = {};
55
+ for (const problem of problems)
56
+ if (!Object.hasOwn(rules, problem.field))
57
+ rules[problem.field] = problem.rule;
58
+ super('VALIDATION_FAILED', `Invalid fields: ${[...new Set(problems.map((problem) => problem.field))].join(', ')}`, {
59
+ plugin: 'dokebi-module',
60
+ status: 422,
61
+ fix: FIX.VALIDATION_FAILED,
62
+ hint: HINT.VALIDATION_FAILED,
63
+ data: { action, rules },
64
+ });
65
+ this.fields = Object.freeze(problems.map(({ field, message }) => Object.freeze({ field, message })));
66
+ const errors = {};
67
+ for (const { field, message } of this.fields)
68
+ if (!Object.hasOwn(errors, field))
69
+ errors[field] = message;
70
+ this.errors = Object.freeze(errors);
71
+ }
72
+ }
73
+ /**
74
+ * What a run throws when the row changed since the caller read it (the `version` it sent is not the
75
+ * stored one): 409 ACTION_CONFLICT. `data` may carry the stored version (`{ version }`).
76
+ */
77
+ export function actionConflict(message = 'The row changed since it was read', data) {
78
+ return actionError('ACTION_CONFLICT', message, data);
79
+ }
80
+ /**
81
+ * What a run throws for a field the services refuse after the input check (a username that is
82
+ * taken): 422 VALIDATION_FAILED like the input check, `{ field: message }`.
83
+ */
84
+ export function actionInvalid(fields, action = '') {
85
+ return new ActionValidationError(Object.entries(fields).map(([field, message]) => ({ field, message, rule: 'service' })), action);
86
+ }
87
+ /** Who asks: the AI client of an OAuth grant (@dokebi/oauth), else the signed-in user. */
88
+ export function actorOf(request) {
89
+ const asked = (request ?? {});
90
+ const grant = asked.oauth?.grant;
91
+ if (grant && typeof grant === 'object') {
92
+ const client = typeof grant.clientName === 'string' && grant.clientName ? grant.clientName : grant.clientId;
93
+ return Object.freeze({
94
+ type: 'ai',
95
+ ...(typeof grant.userId === 'string' ? { id: grant.userId } : {}),
96
+ ...(typeof client === 'string' ? { client: client.slice(0, 128) } : {}),
97
+ });
98
+ }
99
+ const id = asked.auth?.id;
100
+ return Object.freeze({ type: 'user', ...(typeof id === 'string' ? { id } : {}) });
101
+ }
102
+ /** JSON of at most `bytes`, or undefined. */
103
+ function json(value, bytes) {
104
+ let text;
105
+ try {
106
+ text = JSON.stringify(value === undefined ? null : value);
107
+ }
108
+ catch (error) {
109
+ throw actionError('ACTION_FAILED', 'The value is not JSON', undefined, error);
110
+ }
111
+ if (text === undefined || Buffer.byteLength(text) > bytes)
112
+ return undefined;
113
+ return JSON.parse(text);
114
+ }
115
+ /** Runs one action: the steps every caller shares (route, group API, MCP tool). */
116
+ export async function runAction(entry, request, body, logger) {
117
+ const begin = performance.now();
118
+ const { id, declaration } = entry;
119
+ const actor = actorOf(request);
120
+ const done = (outcome, extra = {}) => {
121
+ if (logger.isEnabled('debug'))
122
+ logger.log('debug', 'Action answered', {
123
+ action: id,
124
+ outcome,
125
+ actor: actor.type,
126
+ ...(actor.id === undefined ? {} : { user: actor.id }),
127
+ ...(actor.client === undefined ? {} : { client: actor.client }),
128
+ ms: Math.round((performance.now() - begin) * 10) / 10,
129
+ ...extra,
130
+ });
131
+ };
132
+ try {
133
+ const asked = request;
134
+ const allowed = asked?.auth ? await asked.auth.can(declaration.permission) : false;
135
+ if (!allowed)
136
+ throw actionError('FORBIDDEN', `Running ${id} needs ${declaration.permission}`, {
137
+ action: id,
138
+ });
139
+ if (body === null || typeof body !== 'object' || Array.isArray(body))
140
+ throw actionError('INVALID_INPUT', 'The body must be { input, confirm? }', {
141
+ action: id,
142
+ reason: 'body',
143
+ });
144
+ const extra = Object.keys(body).find((key) => key !== 'input' && key !== 'confirm');
145
+ if (extra !== undefined)
146
+ throw actionError('INVALID_INPUT', `The body field ${extra.slice(0, 64)} is not known`, {
147
+ action: id,
148
+ reason: 'body',
149
+ name: extra.slice(0, 64),
150
+ });
151
+ const { input, confirm } = body;
152
+ if (confirm !== undefined &&
153
+ (!declaration.danger || typeof confirm !== 'string' || confirm.length > 64))
154
+ throw actionError('INVALID_INPUT', declaration.danger ? 'confirm must be the token of the preview' : `${id} takes no confirm`, { action: id, reason: 'confirm' });
155
+ const checked = checkInput(declaration.input ?? {}, input ?? {});
156
+ if (!checked.ok) {
157
+ if (checked.reason === 'fields')
158
+ throw new ActionValidationError(checked.problems, id);
159
+ throw actionError('INVALID_INPUT', checked.message, {
160
+ action: id,
161
+ reason: checked.reason,
162
+ ...(checked.name === undefined ? {} : { name: checked.name }),
163
+ });
164
+ }
165
+ const module = entry.context();
166
+ let scope = null;
167
+ if (declaration.scope) {
168
+ const answer = await declaration.scope({ request, module });
169
+ if (answer === null || answer === undefined)
170
+ throw actionError('FORBIDDEN', `The caller has no scope on ${id}`, { action: id });
171
+ if (typeof answer !== 'string' || !declaration.scopes?.includes(answer))
172
+ throw actionError('ACTION_FAILED', `The scope function of ${id} answered something other than one of its scopes (${declaration.scopes?.join(', ')})`, { action: id });
173
+ scope = answer;
174
+ }
175
+ const run = Object.freeze({
176
+ action: id,
177
+ input: checked.input,
178
+ scope,
179
+ actor,
180
+ request,
181
+ module,
182
+ });
183
+ if (declaration.preview) {
184
+ const preview = json(await declaration.preview(run), ACTION_LIMITS.previewBytes);
185
+ if (preview === undefined)
186
+ throw actionError('ACTION_FAILED', `The preview of ${id} is larger than ${ACTION_LIMITS.previewBytes} bytes of JSON`, { action: id });
187
+ const token = confirmToken(id, actor, checked.input, preview);
188
+ if (confirm === undefined)
189
+ throw actionError('CONFIRM_REQUIRED', `${id} needs a confirm after its preview`, {
190
+ action: id,
191
+ preview,
192
+ confirm: token,
193
+ });
194
+ if (confirm !== token)
195
+ throw actionError('CONFIRM_STALE', `What ${id} would change is not what was previewed`, {
196
+ action: id,
197
+ preview,
198
+ confirm: token,
199
+ });
200
+ }
201
+ const value = await declaration.run(run);
202
+ const result = json(value, ACTION_LIMITS.resultBytes);
203
+ if (result === undefined)
204
+ throw actionError('ACTION_FAILED', `The result of ${id} is larger than ${ACTION_LIMITS.resultBytes} bytes of JSON`, { action: id });
205
+ done('ok');
206
+ return Object.freeze({ action: id, result });
207
+ }
208
+ catch (error) {
209
+ const code = error?.code;
210
+ if (code === 'ACTION_FAILED')
211
+ logger.log('error', 'Action broke the rules', { code: 'ACTION_FAILED', action: id, error });
212
+ done('refused', { code: typeof code === 'string' ? code : 'ERROR' });
213
+ throw error;
214
+ }
215
+ }
216
+ const PATH = /^(?:\/[a-z0-9][a-z0-9._-]{0,63}){1,4}$/;
217
+ export function createActionApi(actions, logger) {
218
+ const ids = Object.freeze([...actions.keys()]);
219
+ const run = async (request, id, body) => {
220
+ const entry = typeof id === 'string' ? actions.get(id) : undefined;
221
+ if (!entry) {
222
+ const error = actionError('ACTION_NOT_FOUND', `There is no action ${String(id).slice(0, 140)}`, {
223
+ action: String(id).slice(0, 140),
224
+ });
225
+ logger.log('debug', 'Action answered', {
226
+ action: String(id).slice(0, 140),
227
+ outcome: 'refused',
228
+ code: error.code,
229
+ });
230
+ throw error;
231
+ }
232
+ return runAction(entry, request, body, logger);
233
+ };
234
+ return Object.freeze({
235
+ ids,
236
+ run,
237
+ routes(route, options = {}) {
238
+ const path = options.path ?? '/actions';
239
+ if (!PATH.test(path))
240
+ throw actionError('ACTION_FAILED', `The action route path ${path} must be /a/lower-case/path`);
241
+ const handler = (async (request) => {
242
+ const asked = request;
243
+ const params = asked.params ?? {};
244
+ return run(request, `${String(params.module)}.${String(params.action)}`, (asked.body ?? {}));
245
+ });
246
+ route.post(`${path}/:module/:action`, handler, { config: { id: 'module.action' } });
247
+ },
248
+ });
249
+ }
@@ -0,0 +1,152 @@
1
+ import { type DataFieldType } from './data-source.js';
2
+ /** A label: one text, or a text per locale. */
3
+ type Text = string | Readonly<Record<string, string>>;
4
+ /** Formats a text field may require. */
5
+ export declare const TEXT_FORMATS: readonly ['email'];
6
+ export type ActionTextFormat = (typeof TEXT_FORMATS)[number];
7
+ /** One input field of an action (the kinds of FIELD_TYPES, DEC-06). */
8
+ export interface ActionField {
9
+ readonly type: DataFieldType;
10
+ readonly label: Text;
11
+ /** Must be given and not empty (null, '' and [] count as missing). */
12
+ readonly required?: boolean;
13
+ /**
14
+ * `false`: may be left out (not changed), but never cleared — null, '' and [] are refused like a
15
+ * missing required value (a name that must stay). Default true for a field that is not required.
16
+ */
17
+ readonly nullable?: boolean;
18
+ /** text: characters (code points), default 0 to ACTION_LIMITS.textChars. */
19
+ readonly minLength?: number;
20
+ readonly maxLength?: number;
21
+ /** text: `email`. */
22
+ readonly format?: ActionTextFormat;
23
+ /** number and money: the smallest and largest value. */
24
+ readonly min?: number;
25
+ readonly max?: number;
26
+ /** number: whole numbers only. */
27
+ readonly integer?: boolean;
28
+ /** money: digits after the point (0 to 4, default 2). */
29
+ readonly scale?: number;
30
+ /** status, choice and category: the values it may take, with their labels (status and choice need them). */
31
+ readonly choices?: Readonly<Record<string, {
32
+ readonly label: Text;
33
+ }>>;
34
+ /** choice: a list of values (1 to ACTION_LIMITS.choiceValues, distinct). */
35
+ readonly multiple?: boolean;
36
+ /** richtext: bytes of the document's JSON (default ACTION_LIMITS.richtextBytes). */
37
+ readonly maxBytes?: number;
38
+ }
39
+ /** Who runs an action: a person, or an AI client acting for a person through an OAuth grant. */
40
+ export interface ActionActor {
41
+ readonly type: 'user' | 'ai';
42
+ /** The user id (for an AI client, the user it acts for); absent when nobody is signed in. */
43
+ readonly id?: string;
44
+ /** The AI client's name (`type: 'ai'`). */
45
+ readonly client?: string;
46
+ }
47
+ /** What `run` and `preview` receive: the checked input and who asks. */
48
+ export interface ActionRun {
49
+ /** `<module>.<name>`. */
50
+ readonly action: string;
51
+ /**
52
+ * The checked input: only the fields the caller gave (an absent field is not changed), each of
53
+ * its kind; null clears a field that is not required.
54
+ */
55
+ readonly input: Readonly<Record<string, unknown>>;
56
+ /** The caller's scope (from the action's `scope`), or null when it declares no scopes. */
57
+ readonly scope: string | null;
58
+ /** Who asks: for the audit row (`@dokebi/audit` `record` in the service's transaction). */
59
+ readonly actor: ActionActor;
60
+ readonly request: unknown;
61
+ /** The module context (`ModuleContext`). */
62
+ readonly module: unknown;
63
+ }
64
+ /** The declaration of one action in `defineModule({ actions })`. */
65
+ export interface ModuleAction {
66
+ readonly title: Text;
67
+ readonly description?: Text;
68
+ /** The input fields (0 to ACTION_LIMITS.fields). `confirm` is not a field name. */
69
+ readonly input?: Readonly<Record<string, ActionField>>;
70
+ /** The input field that names the row the action changes (an `id` field): a form reads the row by it. */
71
+ readonly key?: string;
72
+ /**
73
+ * The input field that carries the version of the row the caller saw (required, number or
74
+ * text). The run compares it with the stored one and throws `actionConflict()` when they differ.
75
+ */
76
+ readonly version?: string;
77
+ /** The permission key the caller must hold (`request.auth.can`): every action has one. */
78
+ readonly permission: string;
79
+ /** The scope names the run knows (`all`, `subtree`, `direct`, `own`). */
80
+ readonly scopes?: readonly string[];
81
+ /** The caller's scope, one of `scopes`, or null (403). Needed when `scopes` is declared. */
82
+ readonly scope?: (input: {
83
+ readonly request: unknown;
84
+ readonly module: unknown;
85
+ }) => unknown;
86
+ /** A dangerous action runs in two steps: `preview` first, then the same input with `confirm`. */
87
+ readonly danger?: true;
88
+ /** What would change (JSON, at most ACTION_LIMITS.previewBytes): needed when `danger` is set. */
89
+ readonly preview?: (run: ActionRun) => unknown;
90
+ /** Runs the action through the module's services and returns its result (JSON: ids, counts). */
91
+ readonly run: (run: ActionRun) => unknown;
92
+ }
93
+ /** Limits of one action (D-0202). */
94
+ export declare const ACTION_LIMITS: Readonly<{
95
+ fields: 64;
96
+ scopes: 8;
97
+ choices: 64;
98
+ choiceValues: 32;
99
+ textChars: 1000;
100
+ textMaxChars: 100000;
101
+ richtextBytes: 65536;
102
+ richtextMaxBytes: 1048576;
103
+ idChars: 128;
104
+ previewBytes: 16384;
105
+ resultBytes: 65536;
106
+ }>;
107
+ /** Thrown for a declaration that breaks a rule (contract.ts makes it INVALID_CONTRACT). */
108
+ export declare class ActionIssue extends Error {
109
+ }
110
+ /**
111
+ * Checks one action declaration (the caller checks `title` and `description` and gives the label
112
+ * and permission checks of the contract).
113
+ */
114
+ export declare function readAction(input: Record<string, unknown>, where: string, label: (value: unknown, at: string) => Text, permissionOf: (key: string, at: string) => void): Omit<ModuleAction, 'title' | 'description'>;
115
+ /** One refused field of an input (422): a fixed English message and the rule it broke. */
116
+ export interface ActionFieldProblem {
117
+ readonly field: string;
118
+ readonly message: string;
119
+ /** `required`, `type`, `minLength`, `maxLength`, `format`, `min`, `max`, `integer`, `scale`, `choice`, `size`. */
120
+ readonly rule: string;
121
+ }
122
+ /** The input check: a refusal before the fields (400) or the field problems (422). */
123
+ export type InputCheck = {
124
+ readonly ok: true;
125
+ readonly input: Readonly<Record<string, unknown>>;
126
+ } | {
127
+ readonly ok: false;
128
+ readonly reason: 'body' | 'field';
129
+ readonly name?: string;
130
+ readonly message: string;
131
+ } | {
132
+ readonly ok: false;
133
+ readonly reason: 'fields';
134
+ readonly problems: readonly ActionFieldProblem[];
135
+ };
136
+ /**
137
+ * Checks an input object against the action's fields: an unknown field is refused as a whole
138
+ * (400), each wrong value is a field problem (422). Required fields are checked even when absent.
139
+ */
140
+ export declare function checkInput(fields: Readonly<Record<string, ActionField>>, input: unknown): InputCheck;
141
+ /**
142
+ * The confirm token of a dangerous action: a hash of the action, the actor, the checked input and
143
+ * the preview. The confirm call runs the preview again: the same token means the caller confirms
144
+ * what it was shown; a changed row gives another preview and another token (CONFIRM_STALE).
145
+ */
146
+ export declare function confirmToken(action: string, actor: ActionActor, input: Readonly<Record<string, unknown>>, preview: unknown): string;
147
+ /**
148
+ * The JSON Schema of an action's input (draft 2020-12, the keywords @dokebi/mcp accepts): what
149
+ * describe shows and what an MCP tool publishes. `confirm` is added for a dangerous action.
150
+ */
151
+ export declare function inputSchema(action: Pick<ModuleAction, 'input' | 'danger'>): Record<string, unknown>;
152
+ export {};