@drsamonline/guardrails 0.0.0-stage → 0.12.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/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@drsamonline/guardrails",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.12.2",
4
+ "description": "Prompt checks: size, blocked patterns, token clamps.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "./src/index.js",
8
+ "exports": {
9
+ ".": "./src/index.js",
10
+ "./src/*": "./src/*"
11
+ },
12
+ "files": [
13
+ "src",
14
+ "web",
15
+ "bin",
16
+ "LICENSE"
17
+ ],
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git://github.com/drsamonline/sui.git",
21
+ "directory": "packages/guardrails"
22
+ },
23
+ "homepage": "https://github.com/drsamonline/sui#readme",
24
+ "publishConfig": {
25
+ "access": "public",
26
+ "registry": "https://registry.npmjs.org/"
27
+ }
28
+ }
package/src/index.js ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * @drsamonline/guardrails — the checks that run before a provider is called.
3
+ *
4
+ * Deliberately small and pure: prompt size, blocked patterns, output clamp.
5
+ * This is a starter set, not a governance product (see SECURITY.md).
6
+ */
7
+
8
+ import { SuiError } from '@drsamonline/core';
9
+
10
+ /**
11
+ * @param {{messages: Array<{role: string, content: string}>, guardrails: any}} input
12
+ * @returns {{ok: true, promptText: string, chars: number}}
13
+ */
14
+ export function checkPrompt(input) {
15
+ const guardrails = input.guardrails ?? {};
16
+ const promptText = input.messages.map((m) => m.content).join('\n');
17
+
18
+ const maxChars = Number(guardrails.maxInputChars ?? 0);
19
+ if (maxChars && promptText.length > maxChars) {
20
+ throw new SuiError(
21
+ `That prompt is ${promptText.length.toLocaleString('en-IN')} characters; this gateway allows ${maxChars.toLocaleString('en-IN')}.`,
22
+ { code: 'input_too_large', status: 413 },
23
+ );
24
+ }
25
+
26
+ for (const pattern of guardrails.blockPatterns ?? []) {
27
+ let re;
28
+ try {
29
+ re = new RegExp(pattern, 'i');
30
+ } catch {
31
+ continue; // a broken pattern is a config bug, not a request failure
32
+ }
33
+ if (re.test(promptText)) {
34
+ throw new SuiError('That prompt matched a blocked pattern in your guardrail policy.', {
35
+ code: 'blocked_by_guardrail',
36
+ status: 400,
37
+ detail: `pattern: ${pattern}`,
38
+ });
39
+ }
40
+ }
41
+
42
+ return { ok: true, promptText, chars: promptText.length };
43
+ }
44
+
45
+ /**
46
+ * B6.3 — dual-channel inspection.
47
+ *
48
+ * A prompt is not the only way instructions arrive. A tool *definition* is
49
+ * text the model will read, and a tool *result* is text an attacker may control
50
+ * completely. Inspecting only the prompt is inspecting the wrong channel.
51
+ *
52
+ * Modes: 'off' (default), 'warn' (report, allow), 'block' (refuse on a high finding).
53
+ */
54
+
55
+ /** Phrases that make no sense in a tool description unless someone is attacking. */
56
+ const INJECTION_MARKERS = [
57
+ 'ignore previous',
58
+ 'ignore all previous',
59
+ 'disregard your',
60
+ 'you must always',
61
+ 'do not tell the user',
62
+ 'system prompt',
63
+ 'new instructions',
64
+ 'reveal your',
65
+ 'print your instructions',
66
+ 'exfiltrate',
67
+ 'send the contents',
68
+ ];
69
+
70
+ const SUSPICIOUS_TOOL_CHARS = /[\u200b-\u200f\u202a-\u202e\ufeff]/; // zero-width and bidi controls
71
+
72
+ /**
73
+ * @param {{messages?: Array<any>, tools?: Array<any>, guardrails?: any}} input
74
+ * @returns {{findings: Array<{channel: string, where: string, signal: string, severity: 'high'|'low', detail: string}>, mode: string, blocked: boolean}}
75
+ */
76
+ export function inspectToolChannel(input) {
77
+ const mode = input.guardrails?.inspectToolChannel ?? 'off';
78
+ /** @type {Array<{channel: string, where: string, signal: string, severity: 'high'|'low', detail: string}>} */
79
+ const findings = [];
80
+
81
+ if (mode === 'off') return { findings, mode, blocked: false };
82
+
83
+ const maxToolResultChars = Number(input.guardrails?.maxToolResultChars ?? 20000);
84
+
85
+ // ---- channel 1: the tool definitions the model will read -----------------
86
+ for (const [index, tool] of (input.tools ?? []).entries()) {
87
+ const fn = tool?.function ?? tool ?? {};
88
+ const name = fn.name ?? `tools[${index}]`;
89
+ const description = String(fn.description ?? '');
90
+ const params = JSON.stringify(fn.parameters ?? {});
91
+ const haystack = `${description} ${params}`.toLowerCase();
92
+
93
+ for (const marker of INJECTION_MARKERS) {
94
+ if (haystack.includes(marker)) {
95
+ findings.push({
96
+ channel: 'tool_definition',
97
+ where: name,
98
+ signal: 'injection_marker',
99
+ severity: 'high',
100
+ detail: `the description of "${name}" contains "${marker}"`,
101
+ });
102
+ break;
103
+ }
104
+ }
105
+ if (SUSPICIOUS_TOOL_CHARS.test(`${description}${params}`)) {
106
+ findings.push({
107
+ channel: 'tool_definition',
108
+ where: name,
109
+ signal: 'hidden_characters',
110
+ severity: 'high',
111
+ detail: `"${name}" carries zero-width or bidi control characters`,
112
+ });
113
+ }
114
+ }
115
+
116
+ // ---- channel 2: tool results, which an attacker may control entirely -----
117
+ for (const [index, message] of (input.messages ?? []).entries()) {
118
+ const isToolResult = message?.role === 'tool' || message?.role === 'function';
119
+ if (!isToolResult) continue;
120
+
121
+ const content = typeof message.content === 'string' ? message.content : JSON.stringify(message.content ?? '');
122
+ const lower = content.toLowerCase();
123
+
124
+ for (const marker of INJECTION_MARKERS) {
125
+ if (lower.includes(marker)) {
126
+ findings.push({
127
+ channel: 'tool_result',
128
+ where: `messages[${index}]`,
129
+ signal: 'injection_marker',
130
+ severity: 'high',
131
+ detail: `a tool result contains "${marker}"`,
132
+ });
133
+ break;
134
+ }
135
+ }
136
+ if (content.length > maxToolResultChars) {
137
+ findings.push({
138
+ channel: 'tool_result',
139
+ where: `messages[${index}]`,
140
+ signal: 'oversized',
141
+ severity: 'low',
142
+ detail: `a tool result is ${content.length} characters (limit ${maxToolResultChars})`,
143
+ });
144
+ }
145
+ }
146
+
147
+ const high = findings.filter((f) => f.severity === 'high');
148
+ return { findings, mode, blocked: mode === 'block' && high.length > 0 };
149
+ }
150
+
151
+ /**
152
+ * The request's own max_tokens, clamped by policy. Whichever is smaller wins.
153
+ * @param {any} requested
154
+ * @param {any} guardrails
155
+ */
156
+ export function clampMaxTokens(requested, guardrails) {
157
+ const policy = Number(guardrails?.maxOutputTokens ?? 4096);
158
+ const asked = Number(requested ?? policy);
159
+ return Math.max(1, Math.min(asked, policy));
160
+ }
161
+ export { RunTracker, RunRegistry, callSignature } from './runs.js';
package/src/runs.js ADDED
@@ -0,0 +1,207 @@
1
+ /**
2
+ * @drsamonline/guardrails/runs — B5.5, bounded runs and approval gates.
3
+ *
4
+ * An agent that can call a model in a loop can spend money in a loop. A gateway
5
+ * is the right place to bound that, because it is the only component that sees
6
+ * every call: it can count steps, add up cost, watch the clock, and notice the
7
+ * same call being made for the tenth time.
8
+ *
9
+ * Four bounds, and one gate:
10
+ *
11
+ * maxUsd spend, from the same ledger the budget bar reads
12
+ * maxSteps calls, because a loop is often cheap per call
13
+ * maxMs wall clock, because some loops are cheap and endless
14
+ * loop the same tool with the same input, N times in a window
15
+ *
16
+ * The gate: a tool listed as needing approval returns `needsApproval` until
17
+ * somebody approves that exact call. Approvals are per run, per call, and
18
+ * single-use — an approval that carries over to the next call is not an approval,
19
+ * it is a blank cheque.
20
+ */
21
+
22
+ /** FNV-1a, for a stable hash of a call's input. */
23
+ function hash32(str) {
24
+ let h = 0x811c9dc5;
25
+ for (let i = 0; i < str.length; i++) {
26
+ h ^= str.charCodeAt(i);
27
+ h = Math.imul(h, 0x01000193);
28
+ }
29
+ return (h >>> 0).toString(16).padStart(8, '0');
30
+ }
31
+
32
+ /** A call is identified by what it does, not by when it did it. */
33
+ export function callSignature(tool, input) {
34
+ const normalised = JSON.stringify(input ?? {}, Object.keys(input ?? {}).sort());
35
+ return `${tool}:${hash32(normalised)}`;
36
+ }
37
+
38
+ export class RunTracker {
39
+ /**
40
+ * @param {{maxUsd?: number|null, maxSteps?: number|null, maxMs?: number|null, loopWindow?: number, maxRepeats?: number, requireApproval?: string[]}} [limits]
41
+ */
42
+ constructor(limits = {}) {
43
+ this.maxUsd = limits.maxUsd ?? null;
44
+ this.maxSteps = limits.maxSteps ?? null;
45
+ this.maxMs = limits.maxMs ?? null;
46
+ this.loopWindow = Number(limits.loopWindow ?? 20);
47
+ this.maxRepeats = Number(limits.maxRepeats ?? 3);
48
+ this.requireApproval = limits.requireApproval ?? [];
49
+
50
+ this.steps = 0;
51
+ this.spentUsd = 0;
52
+ this.startedAt = null;
53
+ this.finishedAt = null;
54
+ // The most recent clock reading any caller supplied. Elapsed time is measured
55
+ // against this rather than Date.now(), so an injected clock actually injects.
56
+ this.lastSeenAt = null;
57
+ /** @type {Array<{signature: string, at: number}>} */
58
+ this.recent = [];
59
+ /** @type {Set<string>} */
60
+ this.approved = new Set();
61
+ /** @type {Array<{signature: string, reason: string, at: number}>} */
62
+ this.denials = [];
63
+ }
64
+
65
+ /** @param {number} [now] */
66
+ start(now = Date.now()) {
67
+ this.startedAt = now;
68
+ return this;
69
+ }
70
+
71
+ /** @param {number} [now] */
72
+ finish(now = Date.now()) {
73
+ this.finishedAt = now;
74
+ this.lastSeenAt = now;
75
+ }
76
+
77
+ get elapsedMs() {
78
+ if (this.startedAt === null) return 0;
79
+ return (this.finishedAt ?? this.lastSeenAt ?? this.startedAt) - this.startedAt;
80
+ }
81
+
82
+ /**
83
+ * Decide whether the next call may proceed.
84
+ *
85
+ * @param {{tool: string, input?: any, costUsd?: number, now?: number}} call
86
+ * @returns {{decision: 'allow'|'deny'|'needsApproval', reason: string, signature: string, steps: number, spentUsd: number, elapsedMs: number}}
87
+ */
88
+ check(call) {
89
+ const now = call.now ?? Date.now();
90
+ this.lastSeenAt = now;
91
+ const signature = callSignature(call.tool, call.input);
92
+ const base = { signature, steps: this.steps, spentUsd: Math.round(this.spentUsd * 1e6) / 1e6, elapsedMs: this.elapsedMs };
93
+
94
+ const deny = (reason) => {
95
+ this.denials.push({ signature, reason, at: now });
96
+ if (this.denials.length > 50) this.denials.shift();
97
+ return { decision: 'deny', reason, ...base };
98
+ };
99
+
100
+ if (this.maxSteps !== null && this.steps >= this.maxSteps) {
101
+ return deny(`step limit reached (${this.steps}/${this.maxSteps}) — raise maxSteps or start a new run`);
102
+ }
103
+ if (this.maxUsd !== null && this.spentUsd >= this.maxUsd) {
104
+ return deny(`run budget exhausted ($${this.spentUsd.toFixed(4)} of $${this.maxUsd.toFixed(2)})`);
105
+ }
106
+ if (this.maxMs !== null && this.elapsedMs >= this.maxMs) {
107
+ return deny(`time limit reached (${Math.round(this.elapsedMs / 1000)}s of ${Math.round(this.maxMs / 1000)}s)`);
108
+ }
109
+
110
+ // The loop check: the same call, the same input, too many times recently.
111
+ this.recent = this.recent.filter((r) => now - r.at <= this.loopWindow * 1000 || r.at > now);
112
+ const repeats = this.recent.filter((r) => r.signature === signature).length;
113
+ if (repeats >= this.maxRepeats) {
114
+ return deny(`loop detected: ${call.tool} called ${repeats + 1} times with the same input in ${this.loopWindow}s — change the input or stop`);
115
+ }
116
+
117
+ if (this.requireApproval.includes(call.tool) && !this.approved.has(signature)) {
118
+ return { decision: 'needsApproval', reason: `${call.tool} needs approval for this exact call`, ...base };
119
+ }
120
+
121
+ return { decision: 'allow', reason: 'within bounds', ...base };
122
+ }
123
+
124
+ /**
125
+ * Record a call that was allowed. Returns false if the bounds were already
126
+ * exceeded, so a caller cannot record its way past the limit.
127
+ *
128
+ * @param {{tool: string, input?: any, costUsd?: number, now?: number}} call
129
+ */
130
+ record(call) {
131
+ const now = call.now ?? Date.now();
132
+ this.lastSeenAt = now;
133
+ const signature = callSignature(call.tool, call.input);
134
+ this.steps += 1;
135
+ this.spentUsd += Number(call.costUsd ?? 0);
136
+ this.recent.push({ signature, at: now });
137
+ if (this.recent.length > 200) this.recent.shift();
138
+ // an approval is spent by the call it approved
139
+ this.approved.delete(signature);
140
+ return true;
141
+ }
142
+
143
+ /** @param {{tool: string, input?: any}} call */
144
+ approve(call) {
145
+ const signature = callSignature(call.tool, call.input);
146
+ this.approved.add(signature);
147
+ return signature;
148
+ }
149
+
150
+ snapshot() {
151
+ return {
152
+ steps: this.steps,
153
+ spentUsd: Math.round(this.spentUsd * 1e6) / 1e6,
154
+ elapsedMs: this.elapsedMs,
155
+ limits: {
156
+ maxUsd: this.maxUsd,
157
+ maxSteps: this.maxSteps,
158
+ maxMs: this.maxMs,
159
+ loopWindow: this.loopWindow,
160
+ maxRepeats: this.maxRepeats,
161
+ requireApproval: this.requireApproval,
162
+ },
163
+ pendingApprovals: [...this.approved],
164
+ denials: [...this.denials].slice(-10),
165
+ finished: this.finishedAt !== null,
166
+ };
167
+ }
168
+ }
169
+
170
+ /** A registry of runs, keyed by the id a caller supplies. */
171
+ export class RunRegistry {
172
+ /** @param {{maxRuns?: number, now?: () => number}} [opts] */
173
+ constructor(opts = {}) {
174
+ this.maxRuns = Number(opts.maxRuns ?? 200);
175
+ this.now = opts.now ?? Date.now;
176
+ /** @type {Map<string, RunTracker>} */
177
+ this.runs = new Map();
178
+ }
179
+
180
+ /** @param {string} id @param {any} limits */
181
+ start(id, limits) {
182
+ const tracker = new RunTracker(limits).start(this.now());
183
+ this.runs.set(id, tracker);
184
+ // oldest finished run goes first when the registry is full
185
+ if (this.runs.size > this.maxRuns) {
186
+ const oldest = [...this.runs.entries()].find(([, t]) => t.finishedAt !== null) ?? [...this.runs.entries()][0];
187
+ if (oldest) this.runs.delete(oldest[0]);
188
+ }
189
+ return tracker;
190
+ }
191
+
192
+ /** @param {string} id */
193
+ get(id) {
194
+ return this.runs.get(id) ?? null;
195
+ }
196
+
197
+ /** @param {string} id */
198
+ finish(id) {
199
+ const tracker = this.get(id);
200
+ if (tracker) tracker.finish(this.now());
201
+ return tracker;
202
+ }
203
+
204
+ list() {
205
+ return [...this.runs.entries()].map(([id, tracker]) => ({ id, ...tracker.snapshot() }));
206
+ }
207
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.