@awebai/oats 0.49.0 → 0.50.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.
@@ -0,0 +1,234 @@
1
+ /** A capability manifest's trigger sources (`triggerSources`, #669; docs/capabilities.md "Trigger sources"):
2
+ * the use-time validator. A source is one of the capability's own commands that, at each poll, lists the
3
+ * events due now; the kernel keeps everything after that (lib/triggers.mjs).
4
+ *
5
+ * Containment (the trigger-as-gate decision): a malformed `triggerSources` never refuses the capability. This
6
+ * module is called only where a source is used — `trigger add`, a poll, `trigger test`, `trigger poll` and
7
+ * `capabilities show` — and never from manifestContractProblems, the manifest loader, discovery or the lock:
8
+ * a trigger naming a malformed source fails E_TRIGGER_SOURCE, and nothing else changes.
9
+ *
10
+ * Validity is per source: a problem inside one source disables only that source; a malformed top level (not an
11
+ * object, more than MAX_SOURCES) disables every source. docs/capability-manifest.schema.json carries the same
12
+ * closed shape; what JSON Schema cannot say (a pattern compiles, `command` names one of `commands`, a parameter
13
+ * default matches its pattern) is checked here only.
14
+ *
15
+ * Patterns compile once, with the `u` flag: the flag JSON Schema's `pattern` uses (Ajv compiles with it), so
16
+ * an author's pattern means the same in the published schema's tooling and here. Every pattern is anchored:
17
+ * it is wrapped as `^(?:…)$`, which leaves an already anchored pattern's meaning unchanged and anchors one
18
+ * like `^a|b$` whose alternatives are not. */
19
+
20
+ import { REFUSED_TEXT, safeText } from "./refused-text.mjs";
21
+
22
+ export const SOURCE_NAME_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
23
+ /** A parameter value, when the parameter declares no pattern. */
24
+ export const DEFAULT_PARAM_PATTERN = "^[A-Za-z0-9._/:@ ,*-]{0,200}$";
25
+ /** A field value, when the field declares no pattern. */
26
+ export const DEFAULT_FIELD_PATTERN = "^[A-Za-z0-9._/:@-]{1,200}$";
27
+ const MAX_SOURCES = 16, MAX_EVENTS = 16, MAX_PARAMETERS = 16, MAX_FIELDS = 16, MAX_URL_HOSTS = 16, TEXT_MAX = 200;
28
+ const EVENT_RE = /^[a-z][a-z0-9_]{0,39}$/;
29
+ const NAME_RE = /^[a-zA-Z][a-zA-Z0-9_]{0,39}$/;
30
+ /** An exact lowercase hostname: no scheme, port, wildcard or trailing dot. */
31
+ const HOST_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;
32
+ /** One line: no control character (C0, DEL, C1) and no line or paragraph separator. */
33
+ const ONE_LINE_RE = /^[^\p{Cc}\u2028\u2029]*$/u;
34
+ const SOURCE_KEYS = ["command", "description", "events", "parameters", "fields", "urlHosts"];
35
+ const PARAMETER_KEYS = ["required", "default", "description", "pattern"];
36
+ const FIELD_KEYS = ["pattern"];
37
+
38
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
39
+ const chars = (s) => [...s].length;
40
+ /** An RFC 6901 pointer from its reference tokens. */
41
+ const pointerOf = (...tokens) => tokens.map((t) => `/${String(t).replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
42
+ const oneLine = (v) => typeof v === "string" && chars(v) <= TEXT_MAX && ONE_LINE_RE.test(v);
43
+ /** `src` compiled and anchored, or null when it does not compile. */
44
+ function compile(src) {
45
+ try { return new RegExp(`^(?:${src})$`, "u"); } catch { return null; }
46
+ }
47
+
48
+ /** Validate one source. → the normalized source, or null after pushing its problems. */
49
+ function checkSource(manifest, name, decl, problems) {
50
+ const at = (...tokens) => pointerOf("triggerSources", name, ...tokens);
51
+ const bad = (pointer, message) => problems.push({ source: name, pointer, message: `trigger source ${JSON.stringify(name)}: ${message}` });
52
+ if (!SOURCE_NAME_RE.test(name)) bad(at(), "the name must be 1 to 40 lowercase letters, digits and dashes, starting with a letter or digit");
53
+ if (!isObject(decl)) { bad(at(), "must be an object { command, events, description?, parameters?, fields?, urlHosts? }"); return null; }
54
+ for (const k of Object.keys(decl)) if (!SOURCE_KEYS.includes(k)) bad(at(k), `unknown key ${JSON.stringify(k)} (allowed: ${SOURCE_KEYS.join(", ")})`);
55
+
56
+ const commands = isObject(manifest.commands) ? manifest.commands : {};
57
+ const spec = typeof decl.command === "string" && Object.hasOwn(commands, decl.command) ? commands[decl.command] : undefined;
58
+ if (typeof decl.command !== "string" || !decl.command) bad(at("command"), "command must name one of the manifest's commands");
59
+ else if (typeof spec !== "string" || !spec.trim()) bad(at("command"), `command ${JSON.stringify(decl.command)} is not one of the manifest's commands`);
60
+
61
+ if (decl.description !== undefined && !oneLine(decl.description)) bad(at("description"), `description must be one line of at most ${TEXT_MAX} characters`);
62
+
63
+ const events = decl.events;
64
+ if (!Array.isArray(events) || events.length < 1 || events.length > MAX_EVENTS) bad(at("events"), `events must list 1 to ${MAX_EVENTS} event names`);
65
+ else {
66
+ events.forEach((e, i) => { if (typeof e !== "string" || !EVENT_RE.test(e)) bad(at("events", i), "an event name is 1 to 40 lowercase letters, digits and underscores, starting with a letter"); });
67
+ events.forEach((e, i) => { if (events.indexOf(e) !== i) bad(at("events", i), `event ${JSON.stringify(e)} is listed twice`); });
68
+ }
69
+
70
+ /** A declared pattern (or `fallback`), compiled. */
71
+ const patternAt = (value, pointer, fallback) => {
72
+ if (value === undefined) return compile(fallback);
73
+ if (typeof value !== "string" || !value) { bad(pointer, "pattern must be a non-empty regular expression"); return null; }
74
+ const re = compile(value);
75
+ if (!re) bad(pointer, `pattern ${JSON.stringify(value)} is not a valid regular expression`);
76
+ return re;
77
+ };
78
+ /** A named map (parameters, fields): at most `max` entries, each an object of `keys`. */
79
+ const namedMap = (key, max, keys, each) => {
80
+ const map = decl[key];
81
+ if (map === undefined) return {};
82
+ if (!isObject(map)) { bad(at(key), `${key} must be an object of named entries`); return null; }
83
+ const names = Object.keys(map);
84
+ if (names.length > max) bad(at(key), `at most ${max} ${key}`);
85
+ const out = {};
86
+ for (const n of names) {
87
+ if (!NAME_RE.test(n)) bad(at(key, n), `${JSON.stringify(n)} is not a valid name (a letter, then letters, digits and underscores, at most 40)`);
88
+ const entry = map[n];
89
+ if (!isObject(entry)) { bad(at(key, n), `must be an object with only ${keys.join(", ")}`); continue; }
90
+ for (const k of Object.keys(entry)) if (!keys.includes(k)) bad(at(key, n, k), `unknown key ${JSON.stringify(k)} (allowed: ${keys.join(", ")})`);
91
+ out[n] = each(n, entry);
92
+ }
93
+ return out;
94
+ };
95
+ const parameters = namedMap("parameters", MAX_PARAMETERS, PARAMETER_KEYS, (n, p) => {
96
+ if (p.required !== undefined && typeof p.required !== "boolean") bad(at("parameters", n, "required"), "required must be true or false");
97
+ if (p.description !== undefined && !oneLine(p.description)) bad(at("parameters", n, "description"), `description must be one line of at most ${TEXT_MAX} characters`);
98
+ const pattern = patternAt(p.pattern, at("parameters", n, "pattern"), DEFAULT_PARAM_PATTERN);
99
+ if (p.default !== undefined) {
100
+ if (typeof p.default !== "string" || chars(p.default) > TEXT_MAX) bad(at("parameters", n, "default"), `default must be a string of at most ${TEXT_MAX} characters`);
101
+ else if (pattern && !pattern.test(p.default)) bad(at("parameters", n, "default"), `default ${JSON.stringify(p.default)} does not match the parameter's pattern`);
102
+ }
103
+ return { required: p.required === true, default: typeof p.default === "string" ? p.default : null, description: typeof p.description === "string" ? p.description : null, pattern };
104
+ });
105
+ const fields = namedMap("fields", MAX_FIELDS, FIELD_KEYS, (n, f) => ({ pattern: patternAt(f.pattern, at("fields", n, "pattern"), DEFAULT_FIELD_PATTERN) }));
106
+
107
+ const hosts = decl.urlHosts === undefined ? [] : decl.urlHosts;
108
+ if (!Array.isArray(hosts) || hosts.length > MAX_URL_HOSTS) bad(at("urlHosts"), `urlHosts must list at most ${MAX_URL_HOSTS} hostnames`);
109
+ else hosts.forEach((h, i) => {
110
+ if (typeof h !== "string" || h.length > 253 || !HOST_RE.test(h)) bad(at("urlHosts", i), "a URL host is an exact lowercase hostname (no scheme, port or wildcard)");
111
+ else if (hosts.indexOf(h) !== i) bad(at("urlHosts", i), `host ${JSON.stringify(h)} is listed twice`);
112
+ });
113
+
114
+ if (problems.length) return null;
115
+ const [script, ...args] = spec.trim().split(/\s+/);
116
+ return { name, command: decl.command, script, args, description: decl.description ?? null, events: [...events], parameters, fields, urlHosts: [...hosts] };
117
+ }
118
+
119
+ /** A manifest's trigger sources, validated where they are used. Never throws, whatever `manifest` is.
120
+ * → { sources: { <name>: { name, command, script, args, description, events, parameters: { <p>: { required,
121
+ * default, description, pattern } }, fields: { <f>: { pattern } }, urlHosts } }, problems: [{ source, pointer,
122
+ * message }] } — `sources` holds only the well-formed sources; `source` is null for a top-level problem. */
123
+ export function triggerSourcesOf(manifest) {
124
+ const out = { sources: {}, problems: [] };
125
+ const decl = isObject(manifest) ? manifest.triggerSources : undefined;
126
+ if (decl === undefined) return out;
127
+ if (!isObject(decl)) { out.problems.push({ source: null, pointer: "/triggerSources", message: "triggerSources must be an object of named trigger sources" }); return out; }
128
+ const names = Object.keys(decl);
129
+ if (names.length > MAX_SOURCES) { out.problems.push({ source: null, pointer: "/triggerSources", message: `triggerSources declares ${names.length} sources; at most ${MAX_SOURCES}` }); return out; }
130
+ for (const name of names) {
131
+ const problems = [];
132
+ const source = checkSource(manifest, name, decl[name], problems);
133
+ if (source) out.sources[name] = source;
134
+ else out.problems.push(...problems);
135
+ }
136
+ return out;
137
+ }
138
+
139
+ // ------------------------------------------------------------ the wire (docs/capabilities.md "Trigger sources")
140
+
141
+ /** At most this many events, and skipped items, in one answer (more is `too-many-events`). */
142
+ export const MAX_ANSWER_EVENTS = 500, MAX_ANSWER_SKIPPED = 100;
143
+ /** Caps on the source's own text (§7): a skipped item's `why`, a refusal's message and code. */
144
+ export const SOURCE_TEXT_MAX = Object.freeze({ why: 200, message: 500, code: 128, invalidEvent: 200 });
145
+ const KEY_RE = /^[\x21-\x7e]{1,512}$/;
146
+ const SUBJECT_RE = /^[A-Za-z0-9._/:@-]{1,200}$/;
147
+ const URL_MAX = 500;
148
+ /** A url as it is stored and rendered: printable ASCII, no space. The URL parser alone would let a
149
+ * tab, CR or LF through (it strips them) and percent-encode the rest, while the RAW string is what
150
+ * reaches the event file and a `{url}` template. */
151
+ const URL_TEXT_RE = /^[\x21-\x7e]+$/;
152
+ /** A field value's length in code points, whatever its author's pattern admits (`.*`): the bound the
153
+ * default pattern has, and that every other text a source provides has one of. */
154
+ const FIELD_VALUE_MAX = 200;
155
+ /** A field value the kernel takes: at most FIELD_VALUE_MAX code points, no character it refuses in
156
+ * text it did not write, and then the author's pattern, which therefore never sees a longer or a
157
+ * refused string. The length is settled on UTF-16 units first (200 code points are at most 400), so
158
+ * a megabyte value is never spread to be counted. */
159
+ const fieldValueOk = (value, pattern) => typeof value === "string" && value.length <= FIELD_VALUE_MAX * 2
160
+ && (value.length <= FIELD_VALUE_MAX || [...value].length <= FIELD_VALUE_MAX) && !REFUSED_TEXT.test(value) && pattern.test(value);
161
+ const EVENT_KEYS = ["key", "subject", "event", "url", "fields"];
162
+ const SUCCESS_KEYS = ["schemaVersion", "phase", "capability", "source", "ok", "result"];
163
+ const REFUSAL_KEYS = ["schemaVersion", "phase", "capability", "source", "ok", "error"];
164
+
165
+ /** A wire failure: E_TRIGGER_POLL with its `cause` (and the source's own refusal, made safe). */
166
+ export function pollFailure(cause, message, source) {
167
+ return Object.assign(new Error(message), { code: "E_TRIGGER_POLL", details: { cause, ...(source ? { source } : {}) } });
168
+ }
169
+
170
+ /** One event's rule broken, or null when it is valid for `source` (a validated source). */
171
+ function eventProblem(source, ev) {
172
+ if (!isObject(ev)) return "shape";
173
+ if (Object.keys(ev).some((k) => !EVENT_KEYS.includes(k))) return "unknown-key";
174
+ if (typeof ev.key !== "string" || !KEY_RE.test(ev.key)) return "key";
175
+ if (typeof ev.subject !== "string" || !SUBJECT_RE.test(ev.subject)) return "subject";
176
+ if (typeof ev.event !== "string" || !source.events.includes(ev.event)) return "event";
177
+ if (ev.url !== undefined) {
178
+ if (typeof ev.url !== "string" || ev.url.length > URL_MAX || !URL_TEXT_RE.test(ev.url)) return "url";
179
+ let u; try { u = new URL(ev.url); } catch { return "url"; }
180
+ if (u.protocol !== "https:" || u.username || u.password || !source.urlHosts.includes(u.hostname.toLowerCase())) return "url";
181
+ }
182
+ if (ev.fields !== undefined) {
183
+ if (!isObject(ev.fields)) return "fields";
184
+ const names = Object.keys(ev.fields);
185
+ // Whatever its author's pattern admits (`.*`), a field value is bounded and never carries a
186
+ // character the kernel refuses: it is rendered into the task as `{fields.<name>}`.
187
+ if (names.length > MAX_FIELDS || names.some((n) => !Object.hasOwn(source.fields, n) || !fieldValueOk(ev.fields[n], source.fields[n].pattern))) return "fields";
188
+ }
189
+ return null;
190
+ }
191
+
192
+ /** Judge a source's answer (the document `runModuleCommand` decoded) against the request it was
193
+ * sent and the source's declaration; `selected` is the trigger's `on.events`.
194
+ * → { events, invalidEvents: [{ text, rule }], skipped: [{ subject, why }], filtered }:
195
+ * `events` are the valid events the trigger selects, first of each key; an invalid event is
196
+ * dropped alone; an event the source declares but the trigger does not select is counted in
197
+ * `filtered`. Throws E_TRIGGER_POLL: `result` (the envelope or its result is malformed),
198
+ * `too-many-events`, or `refused` (with the source's own code and message, made safe). */
199
+ export function judgeAnswer(doc, request, source, selected) {
200
+ const safe = safeText;
201
+ const malformed = (why) => pollFailure("result", `${request.capability}:${request.source} answered a malformed poll result: ${why}`);
202
+ if (!isObject(doc)) throw malformed("not a JSON object");
203
+ const keys = doc.ok === true ? SUCCESS_KEYS : doc.ok === false ? REFUSAL_KEYS : null;
204
+ if (!keys) throw malformed("ok must be true or false");
205
+ const extra = Object.keys(doc).filter((k) => !keys.includes(k)), missing = keys.filter((k) => !Object.hasOwn(doc, k));
206
+ if (extra.length || missing.length) throw malformed(`the envelope's keys must be exactly ${keys.join(", ")}`);
207
+ for (const k of ["schemaVersion", "phase", "capability", "source"]) if (doc[k] !== request[k]) throw malformed(`${k} must echo the request's ${JSON.stringify(request[k])}`);
208
+ if (doc.ok === false) {
209
+ const e = doc.error;
210
+ if (!isObject(e) || typeof e.code !== "string" || !e.code || (e.message !== undefined && typeof e.message !== "string") || Object.keys(e).some((k) => k !== "code" && k !== "message")) throw malformed("error must be { code, message? }");
211
+ const said = { code: safe(e.code, SOURCE_TEXT_MAX.code), ...(e.message !== undefined ? { message: safe(e.message, SOURCE_TEXT_MAX.message) } : {}) };
212
+ throw pollFailure("refused", `${request.capability}:${request.source} refused the poll`, said);
213
+ }
214
+ const res = doc.result;
215
+ if (!isObject(res) || !Array.isArray(res.events) || Object.keys(res).some((k) => k !== "events" && k !== "skipped") || (res.skipped !== undefined && !Array.isArray(res.skipped))) throw malformed("result must be { events: [...], skipped?: [...] }");
216
+ const skippedIn = res.skipped ?? [];
217
+ if (res.events.length > MAX_ANSWER_EVENTS || skippedIn.length > MAX_ANSWER_SKIPPED) throw pollFailure("too-many-events", `${request.capability}:${request.source} answered ${res.events.length} events and ${skippedIn.length} skipped (at most ${MAX_ANSWER_EVENTS} and ${MAX_ANSWER_SKIPPED})`);
218
+ const skipped = skippedIn.map((s) => {
219
+ if (!isObject(s) || typeof s.subject !== "string" || typeof s.why !== "string" || Object.keys(s).some((k) => k !== "subject" && k !== "why")) throw malformed("a skipped item must be { subject, why }");
220
+ return { subject: safe(s.subject, SOURCE_TEXT_MAX.why), why: safe(s.why, SOURCE_TEXT_MAX.why) };
221
+ });
222
+ const events = [], invalidEvents = [], seen = new Set();
223
+ let filtered = 0;
224
+ const drop = (ev, rule) => invalidEvents.push({ text: safe(JSON.stringify(ev) ?? String(ev), SOURCE_TEXT_MAX.invalidEvent), rule });
225
+ for (const ev of res.events) {
226
+ const rule = eventProblem(source, ev);
227
+ if (rule) { drop(ev, rule); continue; }
228
+ if (seen.has(ev.key)) { drop(ev, "duplicate-key"); continue; }
229
+ seen.add(ev.key);
230
+ if (!selected.includes(ev.event)) { filtered++; continue; }
231
+ events.push({ key: ev.key, subject: ev.subject, event: ev.event, ...(ev.url !== undefined ? { url: ev.url } : {}), fields: { ...(ev.fields ?? {}) } });
232
+ }
233
+ return { events, invalidEvents, skipped, filtered };
234
+ }