@caelaralabs/agent-guard 0.0.0-stage → 1.0.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 +107 -2
- package/dist/cjs/index.d.ts +145 -0
- package/dist/cjs/index.js +192 -0
- package/dist/cjs/package.json +1 -0
- package/dist/esm/cli.d.ts +2 -0
- package/dist/esm/cli.js +22 -0
- package/dist/esm/index.d.ts +145 -0
- package/dist/esm/index.js +182 -0
- package/dist/esm/run.d.ts +39 -0
- package/dist/esm/run.js +227 -0
- package/package.json +60 -4
package/README.md
CHANGED
|
@@ -1,3 +1,108 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @caelaralabs/agent-guard
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Checks for the text going into and out of your agents: prompt-injection scanning, an input firewall with PII redaction, output validation against a JSON Schema, PII redaction, and domain trust reports. A typed SDK for ESM and CommonJS, plus a CLI.
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
npm install @caelaralabs/agent-guard
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
npx -y @caelaralabs/agent-guard --scan "Ignore all previous instructions"
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Node 20 or newer. No runtime dependencies.
|
|
16
|
+
|
|
17
|
+
**Where requests go:** requests are processed by Caelara Labs edge APIs at `*.caelaralabs.com` (`agent.caelaralabs.com` and `compliance.caelaralabs.com`), with a free 50-call trial key, `CAELARA_API_KEY`, or x402 USDC payment headers. There is no anonymous free tier: without a key or a payment every call answers HTTP 402.
|
|
18
|
+
|
|
19
|
+
## SDK
|
|
20
|
+
|
|
21
|
+
ESM:
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
import { scanPromptInjection, sanitizeInput, validateOutput, redactPII, checkDomainTrust, CaelaraError } from '@caelaralabs/agent-guard'
|
|
25
|
+
|
|
26
|
+
const scan = await scanPromptInjection(userText)
|
|
27
|
+
if (scan.verdict !== 'allow') throw new Error(`blocked input (risk ${scan.risk_score})`)
|
|
28
|
+
|
|
29
|
+
const input = await sanitizeInput(userText) // injection check + PII redaction
|
|
30
|
+
const safeText = input.sanitized_text // null when the verdict is "block"
|
|
31
|
+
|
|
32
|
+
const out = await validateOutput(modelOutput, {
|
|
33
|
+
schema: { type: 'object', required: ['answer'], properties: { answer: { type: 'string' } } },
|
|
34
|
+
source: retrievedContext, // optional grounding check
|
|
35
|
+
})
|
|
36
|
+
if (out.verdict === 'fail') console.log(out.schema?.errors)
|
|
37
|
+
|
|
38
|
+
const { redacted } = await redactPII('Mail me at jane@example.com')
|
|
39
|
+
const trust = await checkDomainTrust('example.com') // trust_score, verdict, flags
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
CommonJS:
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
const { scanPromptInjection, CaelaraError } = require('@caelaralabs/agent-guard')
|
|
46
|
+
|
|
47
|
+
scanPromptInjection(text)
|
|
48
|
+
.then((r) => console.log(r.verdict, r.risk_score))
|
|
49
|
+
.catch((e) => {
|
|
50
|
+
if (e instanceof CaelaraError && e.isBilling) console.error(e.guidance)
|
|
51
|
+
else throw e
|
|
52
|
+
})
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
| Function | Request | Result fields |
|
|
56
|
+
| --- | --- | --- |
|
|
57
|
+
| `sanitizeInput(text, { redactPII? })` | `POST agent.caelaralabs.com/v1/agent-input-firewall` `{ text, redact_pii }` | `verdict` (allow, review, block), `risk_score`, `injection_matches`, `pii_findings`, `sanitized_text`, `tokens_estimate` |
|
|
58
|
+
| `scanPromptInjection(text)` | `POST /v1/prompt-injection-scanner` `{ text }` | `verdict`, `risk_score`, `matches` |
|
|
59
|
+
| `validateOutput(output, { schema?, source? })` | `POST /v1/agent-output-validator` `{ output, schema, source }` | `verdict` (pass, fail), `json`, `schema`, `grounding`, `citations` |
|
|
60
|
+
| `redactPII(text)` | `POST /v1/pii-redactor` `{ text }` | `redacted`, `findings`, `total` |
|
|
61
|
+
| `checkDomainTrust(domain)` | `GET compliance.caelaralabs.com/v1/domain-trust-composite?domain=` | `domain`, `trust_score`, `verdict` (trusted, caution, risky), `email_auth`, `certificates`, `security_headers`, `flags`, `partial` |
|
|
62
|
+
|
|
63
|
+
Every function also takes the client options `{ apiKey?, payment?, fetch?, timeoutMs? }`. `apiKey` and `payment` default to the environment variables below, and `timeoutMs` defaults to 15000.
|
|
64
|
+
|
|
65
|
+
Failures throw a `CaelaraError` with `status`, `code` (`payment_required`, `rate_limited`, `bad_request`, `http_error`, `network_error`, `timeout`, `partial`, `invalid_response`) and `body`. For HTTP 402 and 429, `isBilling` is true, `guidance` lists the ways to get access, and on a 402 `terms` holds the x402 price, network and recipient.
|
|
66
|
+
|
|
67
|
+
## CLI
|
|
68
|
+
|
|
69
|
+
```
|
|
70
|
+
agent-guard --scan "<text>" # prompt-injection score
|
|
71
|
+
cat message.txt | agent-guard --scan - # same, from stdin
|
|
72
|
+
agent-guard --validate output.json --schema schema.json
|
|
73
|
+
agent-guard --redact "Call me on +1 415 555 0100"
|
|
74
|
+
agent-guard --domain example.com
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Add `--json` to print the API response. Text output goes to stdout; with `--redact` the summary of what was removed goes to stderr, so `agent-guard --redact - < in.txt > out.txt` writes only the redacted text.
|
|
78
|
+
|
|
79
|
+
| Exit code | Meaning |
|
|
80
|
+
| --- | --- |
|
|
81
|
+
| 0 | allow, pass or trusted (and `--redact` succeeded) |
|
|
82
|
+
| 1 | review or block, validation failed, caution or risky domain, or the check could not complete |
|
|
83
|
+
| 2 | Usage error |
|
|
84
|
+
| 3 | The API refused the request (HTTP 402 or 429): billing or rate limit |
|
|
85
|
+
|
|
86
|
+
A network failure or timeout exits 1, so a pipeline that gates on agent-guard fails closed.
|
|
87
|
+
|
|
88
|
+
## Environment
|
|
89
|
+
|
|
90
|
+
| Variable | Purpose |
|
|
91
|
+
| --- | --- |
|
|
92
|
+
| `CAELARA_API_KEY` | Your Caelara key, sent as `X-Caelara-Key`. Free 50-call trial key: https://caelaralabs.com/shield/#trial |
|
|
93
|
+
| `CAELARA_X402_PAYMENT` | Optional pre-signed x402 payment, sent as `X-PAYMENT`. This package never holds a wallet or signs payments. |
|
|
94
|
+
| `CAELARA_AGENT_API_BASE`, `CAELARA_COMPLIANCE_API_BASE` | Point requests at a local mock for testing. Only loopback addresses are accepted. |
|
|
95
|
+
|
|
96
|
+
## Access and pricing
|
|
97
|
+
|
|
98
|
+
On HTTP 402 or 429 you get the three ways to get access:
|
|
99
|
+
|
|
100
|
+
1. **Free trial key:** 50 calls from https://caelaralabs.com/shield/#trial, set as `CAELARA_API_KEY`.
|
|
101
|
+
2. **RapidAPI subscription:** [Agent Safety](https://rapidapi.com/caelara-labs-caelara-labs-default/api/caelara-labs-agent-safety) and [Compliance and Trust](https://rapidapi.com/caelara-labs-caelara-labs-default/api/caelara-labs-compliance-trust). RapidAPI calls go through RapidAPI's own hosts, not through this package.
|
|
102
|
+
3. **x402 per call:** USDC on Base. `scanPromptInjection` and `redactPII` cost 0.005 USDC per call; `sanitizeInput`, `validateOutput` and `checkDomainTrust` cost 0.025 USDC. Pass a pre-signed `X-PAYMENT` header in `CAELARA_X402_PAYMENT` or the `payment` option.
|
|
103
|
+
|
|
104
|
+
A trial key allows about one call per second; a 429 means wait and retry.
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
MIT, Caelara Labs <ops@caelaralabs.com>
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
export declare const VERSION = "1.0.0";
|
|
2
|
+
export declare const USER_AGENT = "CaelaraLabs-Engine/1.0";
|
|
3
|
+
export declare const DEFAULT_TIMEOUT_MS = 15000;
|
|
4
|
+
export declare const AGENT_API = "https://agent.caelaralabs.com";
|
|
5
|
+
export declare const COMPLIANCE_API = "https://compliance.caelaralabs.com";
|
|
6
|
+
export declare const TRIAL_URL = "https://caelaralabs.com/shield/#trial";
|
|
7
|
+
type Suite = 'agent' | 'compliance';
|
|
8
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
9
|
+
export interface ClientOptions {
|
|
10
|
+
/** Caelara key, sent as X-Caelara-Key. Defaults to process.env.CAELARA_API_KEY. */
|
|
11
|
+
apiKey?: string;
|
|
12
|
+
/** Pre-signed x402 payment, sent as X-PAYMENT. Defaults to process.env.CAELARA_X402_PAYMENT. */
|
|
13
|
+
payment?: string;
|
|
14
|
+
/** Custom fetch implementation (defaults to the global fetch). */
|
|
15
|
+
fetch?: FetchLike;
|
|
16
|
+
/** Per-request timeout in milliseconds (default 15000). */
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
}
|
|
19
|
+
export type CaelaraErrorCode = 'payment_required' | 'rate_limited' | 'bad_request' | 'http_error' | 'network_error' | 'timeout' | 'partial' | 'invalid_response';
|
|
20
|
+
export interface PaymentTerms {
|
|
21
|
+
priceUsdc?: string;
|
|
22
|
+
network?: string;
|
|
23
|
+
payTo?: string;
|
|
24
|
+
asset?: string;
|
|
25
|
+
resource?: string;
|
|
26
|
+
}
|
|
27
|
+
export declare class CaelaraError extends Error {
|
|
28
|
+
readonly status: number;
|
|
29
|
+
readonly code: CaelaraErrorCode;
|
|
30
|
+
readonly body: unknown;
|
|
31
|
+
/** Present for 402 and 429: how to get access (trial key, RapidAPI, x402). */
|
|
32
|
+
readonly guidance: string | null;
|
|
33
|
+
/** x402 terms from a 402 challenge, when the API sent them. */
|
|
34
|
+
readonly terms: PaymentTerms | null;
|
|
35
|
+
constructor(init: {
|
|
36
|
+
status: number;
|
|
37
|
+
code: CaelaraErrorCode;
|
|
38
|
+
message: string;
|
|
39
|
+
body?: unknown;
|
|
40
|
+
guidance?: string | null;
|
|
41
|
+
terms?: PaymentTerms | null;
|
|
42
|
+
});
|
|
43
|
+
/** True when the API refused for billing or rate-limit reasons (HTTP 402 or 429). */
|
|
44
|
+
get isBilling(): boolean;
|
|
45
|
+
}
|
|
46
|
+
export declare function billingGuidance(status: 402 | 429, suite?: Suite, terms?: PaymentTerms | null, serverMessage?: string | null): string;
|
|
47
|
+
export type InputVerdict = 'allow' | 'review' | 'block';
|
|
48
|
+
export interface InjectionMatch {
|
|
49
|
+
rule: string;
|
|
50
|
+
severity: number;
|
|
51
|
+
excerpt: string;
|
|
52
|
+
}
|
|
53
|
+
export interface PiiFinding {
|
|
54
|
+
type: string;
|
|
55
|
+
count: number;
|
|
56
|
+
}
|
|
57
|
+
/** POST /v1/agent-input-firewall */
|
|
58
|
+
export interface FirewallResult {
|
|
59
|
+
verdict: InputVerdict;
|
|
60
|
+
risk_score: number;
|
|
61
|
+
injection_matches: InjectionMatch[];
|
|
62
|
+
pii_findings: PiiFinding[];
|
|
63
|
+
/** null when the verdict is "block". */
|
|
64
|
+
sanitized_text: string | null;
|
|
65
|
+
tokens_estimate: number;
|
|
66
|
+
}
|
|
67
|
+
/** POST /v1/prompt-injection-scanner */
|
|
68
|
+
export interface InjectionScanResult {
|
|
69
|
+
risk_score: number;
|
|
70
|
+
verdict: InputVerdict;
|
|
71
|
+
matches: InjectionMatch[];
|
|
72
|
+
}
|
|
73
|
+
export interface GroundingSentence {
|
|
74
|
+
sentence: string;
|
|
75
|
+
support: number;
|
|
76
|
+
unsupported_numbers: string[];
|
|
77
|
+
unsupported_entities: string[];
|
|
78
|
+
flagged: boolean;
|
|
79
|
+
}
|
|
80
|
+
/** POST /v1/agent-output-validator */
|
|
81
|
+
export interface OutputValidation {
|
|
82
|
+
verdict: 'pass' | 'fail';
|
|
83
|
+
json: {
|
|
84
|
+
parseable: boolean;
|
|
85
|
+
fixes_applied: string[];
|
|
86
|
+
value: unknown;
|
|
87
|
+
};
|
|
88
|
+
schema: {
|
|
89
|
+
valid: boolean;
|
|
90
|
+
errors: string[];
|
|
91
|
+
coerced?: unknown;
|
|
92
|
+
coerced_valid?: boolean;
|
|
93
|
+
} | null;
|
|
94
|
+
grounding: {
|
|
95
|
+
sentences: GroundingSentence[];
|
|
96
|
+
flagged_count: number;
|
|
97
|
+
grounding_score: number;
|
|
98
|
+
} | null;
|
|
99
|
+
citations: {
|
|
100
|
+
urls: string[];
|
|
101
|
+
dois: string[];
|
|
102
|
+
arxiv: string[];
|
|
103
|
+
numeric_refs: string[];
|
|
104
|
+
author_year: string[];
|
|
105
|
+
markdown_links: Array<{
|
|
106
|
+
label: string;
|
|
107
|
+
url: string;
|
|
108
|
+
}>;
|
|
109
|
+
total: number;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** POST /v1/pii-redactor */
|
|
113
|
+
export interface RedactionResult {
|
|
114
|
+
redacted: string;
|
|
115
|
+
findings: PiiFinding[];
|
|
116
|
+
total: number;
|
|
117
|
+
}
|
|
118
|
+
/** GET https://compliance.caelaralabs.com/v1/domain-trust-composite */
|
|
119
|
+
export interface DomainTrustReport {
|
|
120
|
+
domain: string;
|
|
121
|
+
/** true when one of the underlying checks could not complete. */
|
|
122
|
+
partial: boolean;
|
|
123
|
+
trust_score: number;
|
|
124
|
+
verdict: 'trusted' | 'caution' | 'risky';
|
|
125
|
+
email_auth: Record<string, unknown>;
|
|
126
|
+
certificates: Record<string, unknown>;
|
|
127
|
+
security_headers: Record<string, unknown> | null;
|
|
128
|
+
flags: string[];
|
|
129
|
+
}
|
|
130
|
+
/** Input firewall: injection risk, PII redaction, sanitized text and an allow/review/block verdict. */
|
|
131
|
+
export declare function sanitizeInput(text: string, opts?: ClientOptions & {
|
|
132
|
+
redactPII?: boolean;
|
|
133
|
+
}): Promise<FirewallResult>;
|
|
134
|
+
/** Scores text for prompt-injection patterns. */
|
|
135
|
+
export declare function scanPromptInjection(text: string, opts?: ClientOptions): Promise<InjectionScanResult>;
|
|
136
|
+
/** Validates model output: repairs JSON, enforces an optional JSON Schema, checks grounding against an optional source. */
|
|
137
|
+
export declare function validateOutput(output: string, opts?: ClientOptions & {
|
|
138
|
+
schema?: Record<string, unknown>;
|
|
139
|
+
source?: string;
|
|
140
|
+
}): Promise<OutputValidation>;
|
|
141
|
+
/** Redacts emails, phone numbers, SSNs, card numbers, IP addresses, API keys and JWTs. */
|
|
142
|
+
export declare function redactPII(text: string, opts?: ClientOptions): Promise<RedactionResult>;
|
|
143
|
+
/** Domain trust report: SPF/DMARC grade, security headers, certificate history and an overall score. */
|
|
144
|
+
export declare function checkDomainTrust(domain: string, opts?: ClientOptions): Promise<DomainTrustReport>;
|
|
145
|
+
export {};
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Typed client for the Caelara Labs agent safety and compliance APIs.
|
|
3
|
+
// agent: https://agent.caelaralabs.com/v1/*
|
|
4
|
+
// compliance: https://compliance.caelaralabs.com/v1/*
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.CaelaraError = exports.TRIAL_URL = exports.COMPLIANCE_API = exports.AGENT_API = exports.DEFAULT_TIMEOUT_MS = exports.USER_AGENT = exports.VERSION = void 0;
|
|
7
|
+
exports.billingGuidance = billingGuidance;
|
|
8
|
+
exports.sanitizeInput = sanitizeInput;
|
|
9
|
+
exports.scanPromptInjection = scanPromptInjection;
|
|
10
|
+
exports.validateOutput = validateOutput;
|
|
11
|
+
exports.redactPII = redactPII;
|
|
12
|
+
exports.checkDomainTrust = checkDomainTrust;
|
|
13
|
+
exports.VERSION = '1.0.0';
|
|
14
|
+
exports.USER_AGENT = 'CaelaraLabs-Engine/1.0';
|
|
15
|
+
exports.DEFAULT_TIMEOUT_MS = 15_000;
|
|
16
|
+
exports.AGENT_API = 'https://agent.caelaralabs.com';
|
|
17
|
+
exports.COMPLIANCE_API = 'https://compliance.caelaralabs.com';
|
|
18
|
+
exports.TRIAL_URL = 'https://caelaralabs.com/shield/#trial';
|
|
19
|
+
const RAPIDAPI = {
|
|
20
|
+
agent: 'https://rapidapi.com/caelara-labs-caelara-labs-default/api/caelara-labs-agent-safety',
|
|
21
|
+
compliance: 'https://rapidapi.com/caelara-labs-caelara-labs-default/api/caelara-labs-compliance-trust',
|
|
22
|
+
};
|
|
23
|
+
class CaelaraError extends Error {
|
|
24
|
+
status;
|
|
25
|
+
code;
|
|
26
|
+
body;
|
|
27
|
+
/** Present for 402 and 429: how to get access (trial key, RapidAPI, x402). */
|
|
28
|
+
guidance;
|
|
29
|
+
/** x402 terms from a 402 challenge, when the API sent them. */
|
|
30
|
+
terms;
|
|
31
|
+
constructor(init) {
|
|
32
|
+
super(init.message);
|
|
33
|
+
this.name = 'CaelaraError';
|
|
34
|
+
this.status = init.status;
|
|
35
|
+
this.code = init.code;
|
|
36
|
+
this.body = init.body ?? null;
|
|
37
|
+
this.guidance = init.guidance ?? null;
|
|
38
|
+
this.terms = init.terms ?? null;
|
|
39
|
+
}
|
|
40
|
+
/** True when the API refused for billing or rate-limit reasons (HTTP 402 or 429). */
|
|
41
|
+
get isBilling() {
|
|
42
|
+
return this.status === 402 || this.status === 429;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
exports.CaelaraError = CaelaraError;
|
|
46
|
+
function billingGuidance(status, suite = 'agent', terms = null, serverMessage = null) {
|
|
47
|
+
const head = status === 429
|
|
48
|
+
? 'The Caelara Labs API refused this request (HTTP 429: rate limited).'
|
|
49
|
+
: 'The Caelara Labs API refused this request (HTTP 402: payment required).';
|
|
50
|
+
const price = terms?.priceUsdc ? ` at ${terms.priceUsdc} USDC per call` : '';
|
|
51
|
+
return [
|
|
52
|
+
head,
|
|
53
|
+
...(serverMessage ? [`Server said: ${serverMessage}`] : []),
|
|
54
|
+
'There is no anonymous free tier. Pick one of:',
|
|
55
|
+
` 1. Free trial key, 50 calls: ${exports.TRIAL_URL} then set CAELARA_API_KEY`,
|
|
56
|
+
` 2. RapidAPI subscription: ${RAPIDAPI[suite]} (calls go through RapidAPI)`,
|
|
57
|
+
` 3. x402 per-call payment in USDC on Base${price}: set CAELARA_X402_PAYMENT to a pre-signed X-PAYMENT header`,
|
|
58
|
+
...(status === 429 ? ['A trial key allows about one call per second; wait a moment and retry.'] : []),
|
|
59
|
+
].join('\n');
|
|
60
|
+
}
|
|
61
|
+
// ---------- transport ----------
|
|
62
|
+
function envOf() {
|
|
63
|
+
return typeof process !== 'undefined' && process.env ? process.env : {};
|
|
64
|
+
}
|
|
65
|
+
// Base URLs can only be overridden to a loopback address (local mocks and tests).
|
|
66
|
+
function baseFor(suite) {
|
|
67
|
+
const raw = envOf()[suite === 'agent' ? 'CAELARA_AGENT_API_BASE' : 'CAELARA_COMPLIANCE_API_BASE']?.trim();
|
|
68
|
+
const fallback = suite === 'agent' ? exports.AGENT_API : exports.COMPLIANCE_API;
|
|
69
|
+
if (!raw)
|
|
70
|
+
return fallback;
|
|
71
|
+
try {
|
|
72
|
+
const u = new URL(raw);
|
|
73
|
+
if (['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname))
|
|
74
|
+
return u.origin;
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
/* fall through */
|
|
78
|
+
}
|
|
79
|
+
throw new CaelaraError({ status: 0, code: 'bad_request', message: `${suite === 'agent' ? 'CAELARA_AGENT_API_BASE' : 'CAELARA_COMPLIANCE_API_BASE'} may only point at a loopback address` });
|
|
80
|
+
}
|
|
81
|
+
function termsFrom(body) {
|
|
82
|
+
const a = body?.accepts?.[0];
|
|
83
|
+
if (!a)
|
|
84
|
+
return null;
|
|
85
|
+
const atomic = typeof a.maxAmountRequired === 'string' ? Number(a.maxAmountRequired) : NaN;
|
|
86
|
+
const s = (v) => (typeof v === 'string' ? v : undefined);
|
|
87
|
+
return {
|
|
88
|
+
priceUsdc: Number.isFinite(atomic) ? String(atomic / 1_000_000) : undefined,
|
|
89
|
+
network: s(a.network),
|
|
90
|
+
payTo: s(a.payTo),
|
|
91
|
+
asset: s(a.asset),
|
|
92
|
+
resource: s(a.resource),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
async function request(suite, method, path, payload, query, opts = {}) {
|
|
96
|
+
const env = envOf();
|
|
97
|
+
const apiKey = (opts.apiKey ?? env.CAELARA_API_KEY)?.trim() || undefined;
|
|
98
|
+
const payment = (opts.payment ?? env.CAELARA_X402_PAYMENT)?.trim() || undefined;
|
|
99
|
+
const f = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
100
|
+
const timeoutMs = opts.timeoutMs ?? exports.DEFAULT_TIMEOUT_MS;
|
|
101
|
+
const u = new URL(path, baseFor(suite));
|
|
102
|
+
for (const [k, v] of Object.entries(query ?? {}))
|
|
103
|
+
u.searchParams.set(k, v);
|
|
104
|
+
const headers = { 'User-Agent': exports.USER_AGENT, Accept: 'application/json' };
|
|
105
|
+
if (payload)
|
|
106
|
+
headers['Content-Type'] = 'application/json';
|
|
107
|
+
if (apiKey)
|
|
108
|
+
headers['X-Caelara-Key'] = apiKey;
|
|
109
|
+
if (payment)
|
|
110
|
+
headers['X-PAYMENT'] = payment;
|
|
111
|
+
let res;
|
|
112
|
+
try {
|
|
113
|
+
res = await f(u.toString(), { method, headers, body: payload ? JSON.stringify(payload) : undefined, signal: AbortSignal.timeout(timeoutMs) });
|
|
114
|
+
}
|
|
115
|
+
catch (e) {
|
|
116
|
+
const timedOut = e instanceof Error && (e.name === 'TimeoutError' || e.name === 'AbortError');
|
|
117
|
+
throw new CaelaraError({
|
|
118
|
+
status: 0,
|
|
119
|
+
code: timedOut ? 'timeout' : 'network_error',
|
|
120
|
+
message: timedOut ? `request to ${u.host} timed out after ${timeoutMs} ms` : `could not reach ${u.host}: ${e instanceof Error ? e.message : String(e)}`,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
const text = await res.text();
|
|
124
|
+
let body = null;
|
|
125
|
+
try {
|
|
126
|
+
body = text ? JSON.parse(text) : null;
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
body = null;
|
|
130
|
+
}
|
|
131
|
+
const b = body;
|
|
132
|
+
if (res.status === 402 || res.status === 429) {
|
|
133
|
+
const serverMessage = typeof b?.message === 'string' ? b.message : typeof b?.error === 'string' ? b.error : null;
|
|
134
|
+
const terms = res.status === 402 ? termsFrom(body) : null;
|
|
135
|
+
const guidance = billingGuidance(res.status, suite, terms, serverMessage);
|
|
136
|
+
throw new CaelaraError({ status: res.status, code: res.status === 402 ? 'payment_required' : 'rate_limited', message: guidance.split('\n')[0], body, guidance, terms });
|
|
137
|
+
}
|
|
138
|
+
if (!res.ok) {
|
|
139
|
+
const msg = typeof b?.error === 'string' ? b.error : `HTTP ${res.status}`;
|
|
140
|
+
throw new CaelaraError({ status: res.status, code: res.status === 400 || res.status === 422 ? 'bad_request' : 'http_error', message: msg, body });
|
|
141
|
+
}
|
|
142
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
143
|
+
throw new CaelaraError({ status: res.status, code: 'invalid_response', message: 'response was not a JSON object', body });
|
|
144
|
+
}
|
|
145
|
+
return body;
|
|
146
|
+
}
|
|
147
|
+
// The edge APIs answer 200 with { partial: true } when a check could not complete.
|
|
148
|
+
function requireField(r, field) {
|
|
149
|
+
const o = r;
|
|
150
|
+
if (o[field] === undefined) {
|
|
151
|
+
throw new CaelaraError({ status: 200, code: 'partial', message: `the check could not complete (${typeof o.error === 'string' ? o.error : 'partial result'})`, body: r });
|
|
152
|
+
}
|
|
153
|
+
return r;
|
|
154
|
+
}
|
|
155
|
+
const assertText = (v, name) => {
|
|
156
|
+
if (typeof v !== 'string')
|
|
157
|
+
throw new TypeError(`${name} must be a string`);
|
|
158
|
+
};
|
|
159
|
+
// ---------- public API ----------
|
|
160
|
+
/** Input firewall: injection risk, PII redaction, sanitized text and an allow/review/block verdict. */
|
|
161
|
+
async function sanitizeInput(text, opts = {}) {
|
|
162
|
+
assertText(text, 'text');
|
|
163
|
+
const payload = { text };
|
|
164
|
+
if (opts.redactPII !== undefined)
|
|
165
|
+
payload.redact_pii = opts.redactPII;
|
|
166
|
+
return requireField(await request('agent', 'POST', '/v1/agent-input-firewall', payload, null, opts), 'verdict');
|
|
167
|
+
}
|
|
168
|
+
/** Scores text for prompt-injection patterns. */
|
|
169
|
+
async function scanPromptInjection(text, opts = {}) {
|
|
170
|
+
assertText(text, 'text');
|
|
171
|
+
return requireField(await request('agent', 'POST', '/v1/prompt-injection-scanner', { text }, null, opts), 'verdict');
|
|
172
|
+
}
|
|
173
|
+
/** Validates model output: repairs JSON, enforces an optional JSON Schema, checks grounding against an optional source. */
|
|
174
|
+
async function validateOutput(output, opts = {}) {
|
|
175
|
+
assertText(output, 'output');
|
|
176
|
+
const payload = { output };
|
|
177
|
+
if (opts.schema !== undefined)
|
|
178
|
+
payload.schema = opts.schema;
|
|
179
|
+
if (opts.source !== undefined)
|
|
180
|
+
payload.source = opts.source;
|
|
181
|
+
return requireField(await request('agent', 'POST', '/v1/agent-output-validator', payload, null, opts), 'verdict');
|
|
182
|
+
}
|
|
183
|
+
/** Redacts emails, phone numbers, SSNs, card numbers, IP addresses, API keys and JWTs. */
|
|
184
|
+
async function redactPII(text, opts = {}) {
|
|
185
|
+
assertText(text, 'text');
|
|
186
|
+
return requireField(await request('agent', 'POST', '/v1/pii-redactor', { text }, null, opts), 'redacted');
|
|
187
|
+
}
|
|
188
|
+
/** Domain trust report: SPF/DMARC grade, security headers, certificate history and an overall score. */
|
|
189
|
+
async function checkDomainTrust(domain, opts = {}) {
|
|
190
|
+
assertText(domain, 'domain');
|
|
191
|
+
return requireField(await request('compliance', 'GET', '/v1/domain-trust-composite', null, { domain }, opts), 'verdict');
|
|
192
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
package/dist/esm/cli.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// agent-guard: prompt-injection scan, output validation, PII redaction and domain trust from the shell.
|
|
3
|
+
// npx -y @caelaralabs/agent-guard --scan "text to check"
|
|
4
|
+
import { run } from './run.js';
|
|
5
|
+
const io = {
|
|
6
|
+
out: (s) => process.stdout.write(s.endsWith('\n') ? s : s + '\n'),
|
|
7
|
+
err: (s) => process.stderr.write(s.endsWith('\n') ? s : s + '\n'),
|
|
8
|
+
};
|
|
9
|
+
async function readStdin() {
|
|
10
|
+
const chunks = [];
|
|
11
|
+
for await (const c of process.stdin)
|
|
12
|
+
chunks.push(typeof c === 'string' ? Buffer.from(c) : c);
|
|
13
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
14
|
+
}
|
|
15
|
+
run(process.argv.slice(2), process.env, io, { readStdin })
|
|
16
|
+
.then((code) => {
|
|
17
|
+
process.exitCode = code;
|
|
18
|
+
})
|
|
19
|
+
.catch((e) => {
|
|
20
|
+
process.stderr.write(`agent-guard: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
21
|
+
process.exitCode = 1;
|
|
22
|
+
});
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
export declare const VERSION = "1.0.0";
|
|
2
|
+
export declare const USER_AGENT = "CaelaraLabs-Engine/1.0";
|
|
3
|
+
export declare const DEFAULT_TIMEOUT_MS = 15000;
|
|
4
|
+
export declare const AGENT_API = "https://agent.caelaralabs.com";
|
|
5
|
+
export declare const COMPLIANCE_API = "https://compliance.caelaralabs.com";
|
|
6
|
+
export declare const TRIAL_URL = "https://caelaralabs.com/shield/#trial";
|
|
7
|
+
type Suite = 'agent' | 'compliance';
|
|
8
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
9
|
+
export interface ClientOptions {
|
|
10
|
+
/** Caelara key, sent as X-Caelara-Key. Defaults to process.env.CAELARA_API_KEY. */
|
|
11
|
+
apiKey?: string;
|
|
12
|
+
/** Pre-signed x402 payment, sent as X-PAYMENT. Defaults to process.env.CAELARA_X402_PAYMENT. */
|
|
13
|
+
payment?: string;
|
|
14
|
+
/** Custom fetch implementation (defaults to the global fetch). */
|
|
15
|
+
fetch?: FetchLike;
|
|
16
|
+
/** Per-request timeout in milliseconds (default 15000). */
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
}
|
|
19
|
+
export type CaelaraErrorCode = 'payment_required' | 'rate_limited' | 'bad_request' | 'http_error' | 'network_error' | 'timeout' | 'partial' | 'invalid_response';
|
|
20
|
+
export interface PaymentTerms {
|
|
21
|
+
priceUsdc?: string;
|
|
22
|
+
network?: string;
|
|
23
|
+
payTo?: string;
|
|
24
|
+
asset?: string;
|
|
25
|
+
resource?: string;
|
|
26
|
+
}
|
|
27
|
+
export declare class CaelaraError extends Error {
|
|
28
|
+
readonly status: number;
|
|
29
|
+
readonly code: CaelaraErrorCode;
|
|
30
|
+
readonly body: unknown;
|
|
31
|
+
/** Present for 402 and 429: how to get access (trial key, RapidAPI, x402). */
|
|
32
|
+
readonly guidance: string | null;
|
|
33
|
+
/** x402 terms from a 402 challenge, when the API sent them. */
|
|
34
|
+
readonly terms: PaymentTerms | null;
|
|
35
|
+
constructor(init: {
|
|
36
|
+
status: number;
|
|
37
|
+
code: CaelaraErrorCode;
|
|
38
|
+
message: string;
|
|
39
|
+
body?: unknown;
|
|
40
|
+
guidance?: string | null;
|
|
41
|
+
terms?: PaymentTerms | null;
|
|
42
|
+
});
|
|
43
|
+
/** True when the API refused for billing or rate-limit reasons (HTTP 402 or 429). */
|
|
44
|
+
get isBilling(): boolean;
|
|
45
|
+
}
|
|
46
|
+
export declare function billingGuidance(status: 402 | 429, suite?: Suite, terms?: PaymentTerms | null, serverMessage?: string | null): string;
|
|
47
|
+
export type InputVerdict = 'allow' | 'review' | 'block';
|
|
48
|
+
export interface InjectionMatch {
|
|
49
|
+
rule: string;
|
|
50
|
+
severity: number;
|
|
51
|
+
excerpt: string;
|
|
52
|
+
}
|
|
53
|
+
export interface PiiFinding {
|
|
54
|
+
type: string;
|
|
55
|
+
count: number;
|
|
56
|
+
}
|
|
57
|
+
/** POST /v1/agent-input-firewall */
|
|
58
|
+
export interface FirewallResult {
|
|
59
|
+
verdict: InputVerdict;
|
|
60
|
+
risk_score: number;
|
|
61
|
+
injection_matches: InjectionMatch[];
|
|
62
|
+
pii_findings: PiiFinding[];
|
|
63
|
+
/** null when the verdict is "block". */
|
|
64
|
+
sanitized_text: string | null;
|
|
65
|
+
tokens_estimate: number;
|
|
66
|
+
}
|
|
67
|
+
/** POST /v1/prompt-injection-scanner */
|
|
68
|
+
export interface InjectionScanResult {
|
|
69
|
+
risk_score: number;
|
|
70
|
+
verdict: InputVerdict;
|
|
71
|
+
matches: InjectionMatch[];
|
|
72
|
+
}
|
|
73
|
+
export interface GroundingSentence {
|
|
74
|
+
sentence: string;
|
|
75
|
+
support: number;
|
|
76
|
+
unsupported_numbers: string[];
|
|
77
|
+
unsupported_entities: string[];
|
|
78
|
+
flagged: boolean;
|
|
79
|
+
}
|
|
80
|
+
/** POST /v1/agent-output-validator */
|
|
81
|
+
export interface OutputValidation {
|
|
82
|
+
verdict: 'pass' | 'fail';
|
|
83
|
+
json: {
|
|
84
|
+
parseable: boolean;
|
|
85
|
+
fixes_applied: string[];
|
|
86
|
+
value: unknown;
|
|
87
|
+
};
|
|
88
|
+
schema: {
|
|
89
|
+
valid: boolean;
|
|
90
|
+
errors: string[];
|
|
91
|
+
coerced?: unknown;
|
|
92
|
+
coerced_valid?: boolean;
|
|
93
|
+
} | null;
|
|
94
|
+
grounding: {
|
|
95
|
+
sentences: GroundingSentence[];
|
|
96
|
+
flagged_count: number;
|
|
97
|
+
grounding_score: number;
|
|
98
|
+
} | null;
|
|
99
|
+
citations: {
|
|
100
|
+
urls: string[];
|
|
101
|
+
dois: string[];
|
|
102
|
+
arxiv: string[];
|
|
103
|
+
numeric_refs: string[];
|
|
104
|
+
author_year: string[];
|
|
105
|
+
markdown_links: Array<{
|
|
106
|
+
label: string;
|
|
107
|
+
url: string;
|
|
108
|
+
}>;
|
|
109
|
+
total: number;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** POST /v1/pii-redactor */
|
|
113
|
+
export interface RedactionResult {
|
|
114
|
+
redacted: string;
|
|
115
|
+
findings: PiiFinding[];
|
|
116
|
+
total: number;
|
|
117
|
+
}
|
|
118
|
+
/** GET https://compliance.caelaralabs.com/v1/domain-trust-composite */
|
|
119
|
+
export interface DomainTrustReport {
|
|
120
|
+
domain: string;
|
|
121
|
+
/** true when one of the underlying checks could not complete. */
|
|
122
|
+
partial: boolean;
|
|
123
|
+
trust_score: number;
|
|
124
|
+
verdict: 'trusted' | 'caution' | 'risky';
|
|
125
|
+
email_auth: Record<string, unknown>;
|
|
126
|
+
certificates: Record<string, unknown>;
|
|
127
|
+
security_headers: Record<string, unknown> | null;
|
|
128
|
+
flags: string[];
|
|
129
|
+
}
|
|
130
|
+
/** Input firewall: injection risk, PII redaction, sanitized text and an allow/review/block verdict. */
|
|
131
|
+
export declare function sanitizeInput(text: string, opts?: ClientOptions & {
|
|
132
|
+
redactPII?: boolean;
|
|
133
|
+
}): Promise<FirewallResult>;
|
|
134
|
+
/** Scores text for prompt-injection patterns. */
|
|
135
|
+
export declare function scanPromptInjection(text: string, opts?: ClientOptions): Promise<InjectionScanResult>;
|
|
136
|
+
/** Validates model output: repairs JSON, enforces an optional JSON Schema, checks grounding against an optional source. */
|
|
137
|
+
export declare function validateOutput(output: string, opts?: ClientOptions & {
|
|
138
|
+
schema?: Record<string, unknown>;
|
|
139
|
+
source?: string;
|
|
140
|
+
}): Promise<OutputValidation>;
|
|
141
|
+
/** Redacts emails, phone numbers, SSNs, card numbers, IP addresses, API keys and JWTs. */
|
|
142
|
+
export declare function redactPII(text: string, opts?: ClientOptions): Promise<RedactionResult>;
|
|
143
|
+
/** Domain trust report: SPF/DMARC grade, security headers, certificate history and an overall score. */
|
|
144
|
+
export declare function checkDomainTrust(domain: string, opts?: ClientOptions): Promise<DomainTrustReport>;
|
|
145
|
+
export {};
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Typed client for the Caelara Labs agent safety and compliance APIs.
|
|
2
|
+
// agent: https://agent.caelaralabs.com/v1/*
|
|
3
|
+
// compliance: https://compliance.caelaralabs.com/v1/*
|
|
4
|
+
export const VERSION = '1.0.0';
|
|
5
|
+
export const USER_AGENT = 'CaelaraLabs-Engine/1.0';
|
|
6
|
+
export const DEFAULT_TIMEOUT_MS = 15_000;
|
|
7
|
+
export const AGENT_API = 'https://agent.caelaralabs.com';
|
|
8
|
+
export const COMPLIANCE_API = 'https://compliance.caelaralabs.com';
|
|
9
|
+
export const TRIAL_URL = 'https://caelaralabs.com/shield/#trial';
|
|
10
|
+
const RAPIDAPI = {
|
|
11
|
+
agent: 'https://rapidapi.com/caelara-labs-caelara-labs-default/api/caelara-labs-agent-safety',
|
|
12
|
+
compliance: 'https://rapidapi.com/caelara-labs-caelara-labs-default/api/caelara-labs-compliance-trust',
|
|
13
|
+
};
|
|
14
|
+
export class CaelaraError extends Error {
|
|
15
|
+
status;
|
|
16
|
+
code;
|
|
17
|
+
body;
|
|
18
|
+
/** Present for 402 and 429: how to get access (trial key, RapidAPI, x402). */
|
|
19
|
+
guidance;
|
|
20
|
+
/** x402 terms from a 402 challenge, when the API sent them. */
|
|
21
|
+
terms;
|
|
22
|
+
constructor(init) {
|
|
23
|
+
super(init.message);
|
|
24
|
+
this.name = 'CaelaraError';
|
|
25
|
+
this.status = init.status;
|
|
26
|
+
this.code = init.code;
|
|
27
|
+
this.body = init.body ?? null;
|
|
28
|
+
this.guidance = init.guidance ?? null;
|
|
29
|
+
this.terms = init.terms ?? null;
|
|
30
|
+
}
|
|
31
|
+
/** True when the API refused for billing or rate-limit reasons (HTTP 402 or 429). */
|
|
32
|
+
get isBilling() {
|
|
33
|
+
return this.status === 402 || this.status === 429;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function billingGuidance(status, suite = 'agent', terms = null, serverMessage = null) {
|
|
37
|
+
const head = status === 429
|
|
38
|
+
? 'The Caelara Labs API refused this request (HTTP 429: rate limited).'
|
|
39
|
+
: 'The Caelara Labs API refused this request (HTTP 402: payment required).';
|
|
40
|
+
const price = terms?.priceUsdc ? ` at ${terms.priceUsdc} USDC per call` : '';
|
|
41
|
+
return [
|
|
42
|
+
head,
|
|
43
|
+
...(serverMessage ? [`Server said: ${serverMessage}`] : []),
|
|
44
|
+
'There is no anonymous free tier. Pick one of:',
|
|
45
|
+
` 1. Free trial key, 50 calls: ${TRIAL_URL} then set CAELARA_API_KEY`,
|
|
46
|
+
` 2. RapidAPI subscription: ${RAPIDAPI[suite]} (calls go through RapidAPI)`,
|
|
47
|
+
` 3. x402 per-call payment in USDC on Base${price}: set CAELARA_X402_PAYMENT to a pre-signed X-PAYMENT header`,
|
|
48
|
+
...(status === 429 ? ['A trial key allows about one call per second; wait a moment and retry.'] : []),
|
|
49
|
+
].join('\n');
|
|
50
|
+
}
|
|
51
|
+
// ---------- transport ----------
|
|
52
|
+
function envOf() {
|
|
53
|
+
return typeof process !== 'undefined' && process.env ? process.env : {};
|
|
54
|
+
}
|
|
55
|
+
// Base URLs can only be overridden to a loopback address (local mocks and tests).
|
|
56
|
+
function baseFor(suite) {
|
|
57
|
+
const raw = envOf()[suite === 'agent' ? 'CAELARA_AGENT_API_BASE' : 'CAELARA_COMPLIANCE_API_BASE']?.trim();
|
|
58
|
+
const fallback = suite === 'agent' ? AGENT_API : COMPLIANCE_API;
|
|
59
|
+
if (!raw)
|
|
60
|
+
return fallback;
|
|
61
|
+
try {
|
|
62
|
+
const u = new URL(raw);
|
|
63
|
+
if (['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname))
|
|
64
|
+
return u.origin;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
/* fall through */
|
|
68
|
+
}
|
|
69
|
+
throw new CaelaraError({ status: 0, code: 'bad_request', message: `${suite === 'agent' ? 'CAELARA_AGENT_API_BASE' : 'CAELARA_COMPLIANCE_API_BASE'} may only point at a loopback address` });
|
|
70
|
+
}
|
|
71
|
+
function termsFrom(body) {
|
|
72
|
+
const a = body?.accepts?.[0];
|
|
73
|
+
if (!a)
|
|
74
|
+
return null;
|
|
75
|
+
const atomic = typeof a.maxAmountRequired === 'string' ? Number(a.maxAmountRequired) : NaN;
|
|
76
|
+
const s = (v) => (typeof v === 'string' ? v : undefined);
|
|
77
|
+
return {
|
|
78
|
+
priceUsdc: Number.isFinite(atomic) ? String(atomic / 1_000_000) : undefined,
|
|
79
|
+
network: s(a.network),
|
|
80
|
+
payTo: s(a.payTo),
|
|
81
|
+
asset: s(a.asset),
|
|
82
|
+
resource: s(a.resource),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
async function request(suite, method, path, payload, query, opts = {}) {
|
|
86
|
+
const env = envOf();
|
|
87
|
+
const apiKey = (opts.apiKey ?? env.CAELARA_API_KEY)?.trim() || undefined;
|
|
88
|
+
const payment = (opts.payment ?? env.CAELARA_X402_PAYMENT)?.trim() || undefined;
|
|
89
|
+
const f = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
90
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
91
|
+
const u = new URL(path, baseFor(suite));
|
|
92
|
+
for (const [k, v] of Object.entries(query ?? {}))
|
|
93
|
+
u.searchParams.set(k, v);
|
|
94
|
+
const headers = { 'User-Agent': USER_AGENT, Accept: 'application/json' };
|
|
95
|
+
if (payload)
|
|
96
|
+
headers['Content-Type'] = 'application/json';
|
|
97
|
+
if (apiKey)
|
|
98
|
+
headers['X-Caelara-Key'] = apiKey;
|
|
99
|
+
if (payment)
|
|
100
|
+
headers['X-PAYMENT'] = payment;
|
|
101
|
+
let res;
|
|
102
|
+
try {
|
|
103
|
+
res = await f(u.toString(), { method, headers, body: payload ? JSON.stringify(payload) : undefined, signal: AbortSignal.timeout(timeoutMs) });
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
const timedOut = e instanceof Error && (e.name === 'TimeoutError' || e.name === 'AbortError');
|
|
107
|
+
throw new CaelaraError({
|
|
108
|
+
status: 0,
|
|
109
|
+
code: timedOut ? 'timeout' : 'network_error',
|
|
110
|
+
message: timedOut ? `request to ${u.host} timed out after ${timeoutMs} ms` : `could not reach ${u.host}: ${e instanceof Error ? e.message : String(e)}`,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
const text = await res.text();
|
|
114
|
+
let body = null;
|
|
115
|
+
try {
|
|
116
|
+
body = text ? JSON.parse(text) : null;
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
body = null;
|
|
120
|
+
}
|
|
121
|
+
const b = body;
|
|
122
|
+
if (res.status === 402 || res.status === 429) {
|
|
123
|
+
const serverMessage = typeof b?.message === 'string' ? b.message : typeof b?.error === 'string' ? b.error : null;
|
|
124
|
+
const terms = res.status === 402 ? termsFrom(body) : null;
|
|
125
|
+
const guidance = billingGuidance(res.status, suite, terms, serverMessage);
|
|
126
|
+
throw new CaelaraError({ status: res.status, code: res.status === 402 ? 'payment_required' : 'rate_limited', message: guidance.split('\n')[0], body, guidance, terms });
|
|
127
|
+
}
|
|
128
|
+
if (!res.ok) {
|
|
129
|
+
const msg = typeof b?.error === 'string' ? b.error : `HTTP ${res.status}`;
|
|
130
|
+
throw new CaelaraError({ status: res.status, code: res.status === 400 || res.status === 422 ? 'bad_request' : 'http_error', message: msg, body });
|
|
131
|
+
}
|
|
132
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
133
|
+
throw new CaelaraError({ status: res.status, code: 'invalid_response', message: 'response was not a JSON object', body });
|
|
134
|
+
}
|
|
135
|
+
return body;
|
|
136
|
+
}
|
|
137
|
+
// The edge APIs answer 200 with { partial: true } when a check could not complete.
|
|
138
|
+
function requireField(r, field) {
|
|
139
|
+
const o = r;
|
|
140
|
+
if (o[field] === undefined) {
|
|
141
|
+
throw new CaelaraError({ status: 200, code: 'partial', message: `the check could not complete (${typeof o.error === 'string' ? o.error : 'partial result'})`, body: r });
|
|
142
|
+
}
|
|
143
|
+
return r;
|
|
144
|
+
}
|
|
145
|
+
const assertText = (v, name) => {
|
|
146
|
+
if (typeof v !== 'string')
|
|
147
|
+
throw new TypeError(`${name} must be a string`);
|
|
148
|
+
};
|
|
149
|
+
// ---------- public API ----------
|
|
150
|
+
/** Input firewall: injection risk, PII redaction, sanitized text and an allow/review/block verdict. */
|
|
151
|
+
export async function sanitizeInput(text, opts = {}) {
|
|
152
|
+
assertText(text, 'text');
|
|
153
|
+
const payload = { text };
|
|
154
|
+
if (opts.redactPII !== undefined)
|
|
155
|
+
payload.redact_pii = opts.redactPII;
|
|
156
|
+
return requireField(await request('agent', 'POST', '/v1/agent-input-firewall', payload, null, opts), 'verdict');
|
|
157
|
+
}
|
|
158
|
+
/** Scores text for prompt-injection patterns. */
|
|
159
|
+
export async function scanPromptInjection(text, opts = {}) {
|
|
160
|
+
assertText(text, 'text');
|
|
161
|
+
return requireField(await request('agent', 'POST', '/v1/prompt-injection-scanner', { text }, null, opts), 'verdict');
|
|
162
|
+
}
|
|
163
|
+
/** Validates model output: repairs JSON, enforces an optional JSON Schema, checks grounding against an optional source. */
|
|
164
|
+
export async function validateOutput(output, opts = {}) {
|
|
165
|
+
assertText(output, 'output');
|
|
166
|
+
const payload = { output };
|
|
167
|
+
if (opts.schema !== undefined)
|
|
168
|
+
payload.schema = opts.schema;
|
|
169
|
+
if (opts.source !== undefined)
|
|
170
|
+
payload.source = opts.source;
|
|
171
|
+
return requireField(await request('agent', 'POST', '/v1/agent-output-validator', payload, null, opts), 'verdict');
|
|
172
|
+
}
|
|
173
|
+
/** Redacts emails, phone numbers, SSNs, card numbers, IP addresses, API keys and JWTs. */
|
|
174
|
+
export async function redactPII(text, opts = {}) {
|
|
175
|
+
assertText(text, 'text');
|
|
176
|
+
return requireField(await request('agent', 'POST', '/v1/pii-redactor', { text }, null, opts), 'redacted');
|
|
177
|
+
}
|
|
178
|
+
/** Domain trust report: SPF/DMARC grade, security headers, certificate history and an overall score. */
|
|
179
|
+
export async function checkDomainTrust(domain, opts = {}) {
|
|
180
|
+
assertText(domain, 'domain');
|
|
181
|
+
return requireField(await request('compliance', 'GET', '/v1/domain-trust-composite', null, { domain }, opts), 'verdict');
|
|
182
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type FetchLike } from './index.js';
|
|
2
|
+
export declare const EXIT: {
|
|
3
|
+
readonly allow: 0;
|
|
4
|
+
readonly flagged: 1;
|
|
5
|
+
readonly usage: 2;
|
|
6
|
+
readonly billing: 3;
|
|
7
|
+
};
|
|
8
|
+
export declare const HELP = "agent-guard 1.0.0: check agent inputs and outputs from the command line\n\nUsage\n agent-guard --scan \"<text>\" Score text for prompt injection\n agent-guard --scan - Same, reading the text from stdin\n agent-guard --validate <file|-> [--schema <file>]\n Validate model output (JSON repair, schema)\n agent-guard --redact \"<text>\" Redact PII (use - to read stdin)\n agent-guard --domain <domain> Domain trust report\n\nOptions\n --json Print the API response as JSON\n --help Show this help\n --version Print the version\n\nExit codes\n 0 allow / pass / trusted (and --redact succeeded)\n 1 review or block, validation failed, caution or risky domain, or the check\n could not complete\n 2 usage error\n 3 the API refused the request (HTTP 402 or 429): billing or rate limit\n\nEnvironment\n CAELARA_API_KEY Caelara key, sent as X-Caelara-Key\n CAELARA_X402_PAYMENT Optional pre-signed x402 payment, sent as X-PAYMENT\n\nRequests are processed by Caelara Labs edge APIs at *.caelaralabs.com\n(agent.caelaralabs.com and compliance.caelaralabs.com), with a free 50-call\ntrial key (https://caelaralabs.com/shield/#trial), CAELARA_API_KEY, or x402\nUSDC payment headers. There is no anonymous free tier: without a key or\npayment the API answers HTTP 402.\n";
|
|
9
|
+
export interface Io {
|
|
10
|
+
out: (s: string) => void;
|
|
11
|
+
err: (s: string) => void;
|
|
12
|
+
}
|
|
13
|
+
export interface Deps {
|
|
14
|
+
fetch?: FetchLike;
|
|
15
|
+
readStdin: () => Promise<string>;
|
|
16
|
+
readFile?: (path: string) => string;
|
|
17
|
+
}
|
|
18
|
+
type Action = {
|
|
19
|
+
kind: 'scan' | 'redact';
|
|
20
|
+
text: string;
|
|
21
|
+
} | {
|
|
22
|
+
kind: 'validate';
|
|
23
|
+
file: string;
|
|
24
|
+
schema?: string;
|
|
25
|
+
} | {
|
|
26
|
+
kind: 'domain';
|
|
27
|
+
domain: string;
|
|
28
|
+
};
|
|
29
|
+
export declare class UsageError extends Error {
|
|
30
|
+
}
|
|
31
|
+
export interface Args {
|
|
32
|
+
action: Action | null;
|
|
33
|
+
json: boolean;
|
|
34
|
+
help: boolean;
|
|
35
|
+
version: boolean;
|
|
36
|
+
}
|
|
37
|
+
export declare function parseArgs(argv: string[]): Args;
|
|
38
|
+
export declare function run(argv: string[], env: NodeJS.ProcessEnv, io: Io, deps: Deps): Promise<number>;
|
|
39
|
+
export {};
|
package/dist/esm/run.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// agent-guard command implementation, separate from the entry point so it can be tested with a mocked fetch.
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { CaelaraError, VERSION, checkDomainTrust, redactPII, scanPromptInjection, validateOutput, } from './index.js';
|
|
4
|
+
export const EXIT = { allow: 0, flagged: 1, usage: 2, billing: 3 };
|
|
5
|
+
export const HELP = `agent-guard ${VERSION}: check agent inputs and outputs from the command line
|
|
6
|
+
|
|
7
|
+
Usage
|
|
8
|
+
agent-guard --scan "<text>" Score text for prompt injection
|
|
9
|
+
agent-guard --scan - Same, reading the text from stdin
|
|
10
|
+
agent-guard --validate <file|-> [--schema <file>]
|
|
11
|
+
Validate model output (JSON repair, schema)
|
|
12
|
+
agent-guard --redact "<text>" Redact PII (use - to read stdin)
|
|
13
|
+
agent-guard --domain <domain> Domain trust report
|
|
14
|
+
|
|
15
|
+
Options
|
|
16
|
+
--json Print the API response as JSON
|
|
17
|
+
--help Show this help
|
|
18
|
+
--version Print the version
|
|
19
|
+
|
|
20
|
+
Exit codes
|
|
21
|
+
0 allow / pass / trusted (and --redact succeeded)
|
|
22
|
+
1 review or block, validation failed, caution or risky domain, or the check
|
|
23
|
+
could not complete
|
|
24
|
+
2 usage error
|
|
25
|
+
3 the API refused the request (HTTP 402 or 429): billing or rate limit
|
|
26
|
+
|
|
27
|
+
Environment
|
|
28
|
+
CAELARA_API_KEY Caelara key, sent as X-Caelara-Key
|
|
29
|
+
CAELARA_X402_PAYMENT Optional pre-signed x402 payment, sent as X-PAYMENT
|
|
30
|
+
|
|
31
|
+
Requests are processed by Caelara Labs edge APIs at *.caelaralabs.com
|
|
32
|
+
(agent.caelaralabs.com and compliance.caelaralabs.com), with a free 50-call
|
|
33
|
+
trial key (https://caelaralabs.com/shield/#trial), CAELARA_API_KEY, or x402
|
|
34
|
+
USDC payment headers. There is no anonymous free tier: without a key or
|
|
35
|
+
payment the API answers HTTP 402.
|
|
36
|
+
`;
|
|
37
|
+
export class UsageError extends Error {
|
|
38
|
+
}
|
|
39
|
+
export function parseArgs(argv) {
|
|
40
|
+
const a = { action: null, json: false, help: false, version: false };
|
|
41
|
+
let schema;
|
|
42
|
+
const set = (act) => {
|
|
43
|
+
if (a.action)
|
|
44
|
+
throw new UsageError('use only one of --scan, --validate, --redact or --domain');
|
|
45
|
+
a.action = act;
|
|
46
|
+
};
|
|
47
|
+
for (let i = 0; i < argv.length; i++) {
|
|
48
|
+
const raw = argv[i];
|
|
49
|
+
const eq = raw.startsWith('--') ? raw.indexOf('=') : -1;
|
|
50
|
+
const flag = eq > 0 ? raw.slice(0, eq) : raw;
|
|
51
|
+
const inline = eq > 0 ? raw.slice(eq + 1) : undefined;
|
|
52
|
+
const value = () => {
|
|
53
|
+
if (inline !== undefined)
|
|
54
|
+
return inline;
|
|
55
|
+
const v = argv[i + 1];
|
|
56
|
+
// "-" (stdin) is a value; other dash-prefixed words are flags.
|
|
57
|
+
if (v === undefined || (v.startsWith('--') && v !== '-'))
|
|
58
|
+
throw new UsageError(`${flag} needs a value`);
|
|
59
|
+
i++;
|
|
60
|
+
return v;
|
|
61
|
+
};
|
|
62
|
+
switch (flag) {
|
|
63
|
+
case '--scan':
|
|
64
|
+
set({ kind: 'scan', text: value() });
|
|
65
|
+
break;
|
|
66
|
+
case '--redact':
|
|
67
|
+
set({ kind: 'redact', text: value() });
|
|
68
|
+
break;
|
|
69
|
+
case '--validate':
|
|
70
|
+
set({ kind: 'validate', file: value() });
|
|
71
|
+
break;
|
|
72
|
+
case '--schema':
|
|
73
|
+
schema = value();
|
|
74
|
+
break;
|
|
75
|
+
case '--domain':
|
|
76
|
+
set({ kind: 'domain', domain: value() });
|
|
77
|
+
break;
|
|
78
|
+
case '--json':
|
|
79
|
+
a.json = true;
|
|
80
|
+
break;
|
|
81
|
+
case '--help':
|
|
82
|
+
case '-h':
|
|
83
|
+
a.help = true;
|
|
84
|
+
break;
|
|
85
|
+
case '--version':
|
|
86
|
+
case '-v':
|
|
87
|
+
a.version = true;
|
|
88
|
+
break;
|
|
89
|
+
default: throw new UsageError(`unknown option: ${raw}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (schema !== undefined) {
|
|
93
|
+
if (a.action?.kind !== 'validate')
|
|
94
|
+
throw new UsageError('--schema only works with --validate');
|
|
95
|
+
a.action.schema = schema;
|
|
96
|
+
}
|
|
97
|
+
return a;
|
|
98
|
+
}
|
|
99
|
+
function normalizeDomain(input) {
|
|
100
|
+
const raw = input.trim();
|
|
101
|
+
let host = raw;
|
|
102
|
+
try {
|
|
103
|
+
host = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`).hostname;
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
throw new UsageError(`not a valid domain: ${input}`);
|
|
107
|
+
}
|
|
108
|
+
if (!host.includes('.'))
|
|
109
|
+
throw new UsageError(`not a valid domain: ${input}`);
|
|
110
|
+
return host;
|
|
111
|
+
}
|
|
112
|
+
export async function run(argv, env, io, deps) {
|
|
113
|
+
let args;
|
|
114
|
+
try {
|
|
115
|
+
args = parseArgs(argv);
|
|
116
|
+
}
|
|
117
|
+
catch (e) {
|
|
118
|
+
io.err(`${e instanceof Error ? e.message : String(e)}\nRun agent-guard --help for usage.`);
|
|
119
|
+
return EXIT.usage;
|
|
120
|
+
}
|
|
121
|
+
if (args.help) {
|
|
122
|
+
io.out(HELP);
|
|
123
|
+
return EXIT.allow;
|
|
124
|
+
}
|
|
125
|
+
if (args.version) {
|
|
126
|
+
io.out(VERSION);
|
|
127
|
+
return EXIT.allow;
|
|
128
|
+
}
|
|
129
|
+
const action = args.action;
|
|
130
|
+
if (!action) {
|
|
131
|
+
io.err('nothing to do: pass --scan, --validate, --redact or --domain\nRun agent-guard --help for usage.');
|
|
132
|
+
return EXIT.usage;
|
|
133
|
+
}
|
|
134
|
+
const readFile = deps.readFile ?? ((p) => readFileSync(p, 'utf8'));
|
|
135
|
+
const opts = { apiKey: env.CAELARA_API_KEY, payment: env.CAELARA_X402_PAYMENT, fetch: deps.fetch };
|
|
136
|
+
// Gather input first so usage problems exit 2 before any request is made.
|
|
137
|
+
let text = '';
|
|
138
|
+
let schema;
|
|
139
|
+
let domain = '';
|
|
140
|
+
try {
|
|
141
|
+
if (action.kind === 'scan' || action.kind === 'redact')
|
|
142
|
+
text = action.text === '-' ? await deps.readStdin() : action.text;
|
|
143
|
+
else if (action.kind === 'validate') {
|
|
144
|
+
text = action.file === '-' ? await deps.readStdin() : readFile(action.file);
|
|
145
|
+
if (action.schema) {
|
|
146
|
+
const parsed = JSON.parse(action.schema === '-' ? await deps.readStdin() : readFile(action.schema));
|
|
147
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
148
|
+
throw new UsageError('--schema must be a JSON object');
|
|
149
|
+
schema = parsed;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
else if (action.kind === 'domain')
|
|
153
|
+
domain = normalizeDomain(action.domain);
|
|
154
|
+
if (action.kind !== 'domain' && !text.trim())
|
|
155
|
+
throw new UsageError('input is empty');
|
|
156
|
+
}
|
|
157
|
+
catch (e) {
|
|
158
|
+
const msg = e instanceof SyntaxError ? `--schema is not valid JSON: ${e.message}` : e instanceof Error ? e.message : String(e);
|
|
159
|
+
io.err(`${msg}\nRun agent-guard --help for usage.`);
|
|
160
|
+
return EXIT.usage;
|
|
161
|
+
}
|
|
162
|
+
try {
|
|
163
|
+
switch (action.kind) {
|
|
164
|
+
case 'scan': {
|
|
165
|
+
const r = await scanPromptInjection(text, opts);
|
|
166
|
+
if (args.json)
|
|
167
|
+
io.out(JSON.stringify(r));
|
|
168
|
+
else {
|
|
169
|
+
io.out(`${r.verdict.toUpperCase()} (risk score ${r.risk_score}/100)`);
|
|
170
|
+
for (const m of r.matches)
|
|
171
|
+
io.out(` ${m.rule} (severity ${m.severity}): ${JSON.stringify(m.excerpt)}`);
|
|
172
|
+
}
|
|
173
|
+
return r.verdict === 'allow' ? EXIT.allow : EXIT.flagged;
|
|
174
|
+
}
|
|
175
|
+
case 'validate': {
|
|
176
|
+
const r = await validateOutput(text, { ...opts, schema });
|
|
177
|
+
if (args.json)
|
|
178
|
+
io.out(JSON.stringify(r));
|
|
179
|
+
else {
|
|
180
|
+
io.out(r.verdict === 'pass' ? 'PASS' : 'FAIL');
|
|
181
|
+
io.out(` JSON: ${r.json.parseable ? 'parseable' : 'not parseable'}${r.json.fixes_applied.length ? ` (fixed: ${r.json.fixes_applied.join(', ')})` : ''}`);
|
|
182
|
+
if (r.schema) {
|
|
183
|
+
io.out(` schema: ${r.schema.valid ? 'valid' : r.schema.coerced_valid ? 'valid after coercion' : 'invalid'}`);
|
|
184
|
+
for (const err of r.schema.errors)
|
|
185
|
+
io.out(` ${err}`);
|
|
186
|
+
}
|
|
187
|
+
if (r.citations.total)
|
|
188
|
+
io.out(` citations: ${r.citations.total}`);
|
|
189
|
+
}
|
|
190
|
+
return r.verdict === 'pass' ? EXIT.allow : EXIT.flagged;
|
|
191
|
+
}
|
|
192
|
+
case 'redact': {
|
|
193
|
+
const r = await redactPII(text, opts);
|
|
194
|
+
if (args.json)
|
|
195
|
+
io.out(JSON.stringify(r));
|
|
196
|
+
else {
|
|
197
|
+
io.out(r.redacted);
|
|
198
|
+
io.err(r.total ? `redacted ${r.total}: ${r.findings.map((f) => `${f.type} x${f.count}`).join(', ')}` : 'no PII found');
|
|
199
|
+
}
|
|
200
|
+
return EXIT.allow;
|
|
201
|
+
}
|
|
202
|
+
case 'domain': {
|
|
203
|
+
const r = await checkDomainTrust(domain, opts);
|
|
204
|
+
if (args.json)
|
|
205
|
+
io.out(JSON.stringify(r));
|
|
206
|
+
else {
|
|
207
|
+
io.out(`${r.verdict.toUpperCase()}: ${r.domain} trust score ${r.trust_score}/100${r.partial ? ' (some checks incomplete)' : ''}`);
|
|
208
|
+
for (const f of r.flags)
|
|
209
|
+
io.out(` ${f}`);
|
|
210
|
+
}
|
|
211
|
+
return r.verdict === 'trusted' ? EXIT.allow : EXIT.flagged;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
catch (e) {
|
|
216
|
+
if (e instanceof CaelaraError) {
|
|
217
|
+
if (args.json)
|
|
218
|
+
io.out(JSON.stringify({ error: e.code, status: e.status, message: e.message, ...(e.guidance ? { guidance: e.guidance } : {}) }));
|
|
219
|
+
io.err(e.guidance ?? `agent-guard: ${e.message}`);
|
|
220
|
+
if (e.isBilling)
|
|
221
|
+
return EXIT.billing;
|
|
222
|
+
// A guard that cannot reach its checker fails closed.
|
|
223
|
+
return e.code === 'bad_request' && e.status === 0 ? EXIT.usage : EXIT.flagged;
|
|
224
|
+
}
|
|
225
|
+
throw e;
|
|
226
|
+
}
|
|
227
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@caelaralabs/agent-guard",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Guard agent inputs and outputs: prompt-injection scanning, input firewall, output validation, PII redaction and domain trust checks. Typed SDK (ESM and CommonJS) and CLI.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"agent-guard": "dist/esm/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"main": "./dist/cjs/index.js",
|
|
10
|
+
"module": "./dist/esm/index.js",
|
|
11
|
+
"types": "./dist/esm/index.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"import": {
|
|
15
|
+
"types": "./dist/esm/index.d.ts",
|
|
16
|
+
"default": "./dist/esm/index.js"
|
|
17
|
+
},
|
|
18
|
+
"require": {
|
|
19
|
+
"types": "./dist/cjs/index.d.ts",
|
|
20
|
+
"default": "./dist/cjs/index.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist",
|
|
27
|
+
"README.md"
|
|
28
|
+
],
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node scripts/postbuild.mjs",
|
|
31
|
+
"test": "node --test test/"
|
|
32
|
+
},
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=20"
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@types/node": "^22.0.0",
|
|
41
|
+
"typescript": "^5"
|
|
42
|
+
},
|
|
43
|
+
"keywords": [
|
|
44
|
+
"prompt-injection",
|
|
45
|
+
"agents",
|
|
46
|
+
"guardrails",
|
|
47
|
+
"pii",
|
|
48
|
+
"redaction",
|
|
49
|
+
"output-validation",
|
|
50
|
+
"json-schema",
|
|
51
|
+
"domain-trust",
|
|
52
|
+
"x402"
|
|
53
|
+
],
|
|
54
|
+
"author": "Caelara Labs <ops@caelaralabs.com>",
|
|
55
|
+
"license": "MIT",
|
|
56
|
+
"homepage": "https://caelaralabs.com",
|
|
57
|
+
"repository": {
|
|
58
|
+
"type": "git",
|
|
59
|
+
"url": "git+https://github.com/kingefman1-cmyk/caelaralabs-hq.git",
|
|
60
|
+
"directory": "packages/cli-agent-guard"
|
|
61
|
+
}
|
|
62
|
+
}
|