@zanii/sentinel 0.1.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/LICENSE +159 -0
- package/README.md +71 -0
- package/dist/index.d.ts +164 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +296 -0
- package/dist/index.js.map +1 -0
- package/package.json +41 -0
- package/src/index.ts +419 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
95
|
+
Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work; and
|
|
103
|
+
|
|
104
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
105
|
+
distribution, then any Derivative Works that You distribute must
|
|
106
|
+
include a readable copy of the attribution notices contained
|
|
107
|
+
within such NOTICE file.
|
|
108
|
+
|
|
109
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
110
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
111
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
112
|
+
this License, without any additional terms or conditions.
|
|
113
|
+
|
|
114
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
115
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
116
|
+
except as required for reasonable and customary use in describing the
|
|
117
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
118
|
+
|
|
119
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed
|
|
120
|
+
to in writing, Licensor provides the Work (and each Contributor
|
|
121
|
+
provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
|
|
122
|
+
OR CONDITIONS OF ANY KIND, either express or implied, including,
|
|
123
|
+
without limitation, any warranties or conditions of TITLE,
|
|
124
|
+
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
|
|
125
|
+
|
|
126
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
127
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
128
|
+
unless required by applicable law (such as deliberate and grossly
|
|
129
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
130
|
+
liable to You for damages, including any direct, indirect, special,
|
|
131
|
+
incidental, or consequential damages of any character arising as a
|
|
132
|
+
result of this License or out of the use or inability to use the
|
|
133
|
+
Work.
|
|
134
|
+
|
|
135
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
136
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
137
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
138
|
+
or other liability obligations and/or rights consistent with this
|
|
139
|
+
License. However, in accepting such obligations, You may act only
|
|
140
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
141
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
142
|
+
defend, and hold each Contributor harmless for any liability
|
|
143
|
+
incurred by, or claims asserted against, such Contributor.
|
|
144
|
+
|
|
145
|
+
END OF TERMS AND CONDITIONS
|
|
146
|
+
|
|
147
|
+
Copyright 2026 Zanii
|
|
148
|
+
|
|
149
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
150
|
+
you may not use this file except in compliance with the License.
|
|
151
|
+
You may obtain a copy of the License at
|
|
152
|
+
|
|
153
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
154
|
+
|
|
155
|
+
Unless required by applicable law or agreed to in writing, software
|
|
156
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
157
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
158
|
+
See the License for the specific language governing permissions and
|
|
159
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# @zanii/sentinel
|
|
2
|
+
|
|
3
|
+
**Runtime behavioral monitoring for agents — an "antivirus for agents."** The behavioral
|
|
4
|
+
layer between `@zanii/monitor` (log integrity) and `@zanii/policy` (pre-action rules): it
|
|
5
|
+
consumes the receipt stream and scores **drift** — what an agent *actually does* vs what
|
|
6
|
+
it was *made to do* — then feeds back: escalate, prepare a freeze, page.
|
|
7
|
+
|
|
8
|
+
**The Zanii twist:** findings become `sentinel.alert` **receipts**, recorded by the
|
|
9
|
+
sentinel's own `did:key` (watcher ≠ watched). Detection itself is tamper-evident — and so
|
|
10
|
+
is silence (no alert history is a fact a buyer can check). No generic agent-EDR has that.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @zanii/sentinel @zanii/core
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { buildBaseline, createWatcher, escalationRule, buildAlertReceipt, baselineHash } from '@zanii/sentinel';
|
|
18
|
+
|
|
19
|
+
// 1. baseline: declared scopes (from delegation) + learned habits (from history)
|
|
20
|
+
const baseline = buildBaseline(agent.did, { receipts: history, delegation: [cert] });
|
|
21
|
+
|
|
22
|
+
// 2. watch the live stream; respond on drift (responses are injected — the sentinel holds no keys)
|
|
23
|
+
const w = createWatcher({
|
|
24
|
+
server: 'https://ledger.zanii.agency',
|
|
25
|
+
baselines: { [agent.did]: baseline },
|
|
26
|
+
cursor: loadCursor(), // resume — otherwise a restart re-alerts on old receipts
|
|
27
|
+
onFinding: async (f) => {
|
|
28
|
+
await sentinelAgent.record(buildAlertReceipt(f, { baselineHash: baselineHash(baseline) })); // alert = receipt
|
|
29
|
+
const rule = escalationRule(f); // null when the finding names no targets
|
|
30
|
+
if (f.severity === 'high' && rule) policy.upsert(rule); // → require_approval speed bump
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
setInterval(async () => { await w.tick(); saveCursor(w.cursor()); }, 60_000);
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The watcher keeps a **rolling window** (`windowMs`, default 2h) so windowed detectors work
|
|
37
|
+
*across polls* — a 3-step exfil arriving one step per 60s poll still fires. Findings are
|
|
38
|
+
de-duplicated, so an already-alerted receipt isn't re-alerted every tick.
|
|
39
|
+
|
|
40
|
+
**Feed limit:** `/v1/recent` is a *global* feed the server caps at 100. On a busy ledger,
|
|
41
|
+
receipts can be missed between polls (the cursor jumps). For production, drive `scan` from
|
|
42
|
+
`receipt.recorded` webhooks (`@zanii/webhooks`) rather than polling.
|
|
43
|
+
|
|
44
|
+
## Two modes (forced by the metadata-only ledger)
|
|
45
|
+
- **Ledger mode** — anyone (auditor, customer, you) watches *behavior shape* over the
|
|
46
|
+
public stream: novel targets, rate spikes, exfil sequences, intent gaps, off-hours,
|
|
47
|
+
scope-probing (from `receipt.rejected` webhooks). No operator cooperation needed.
|
|
48
|
+
- **Operator mode** — inside the operator's pipeline, inject `payloadOf` + `checkContent`
|
|
49
|
+
(e.g. `@zanii/walls` `checkOutput` over raw payloads, pre-hash) for content detection.
|
|
50
|
+
|
|
51
|
+
## Detectors (v1, heuristic ladder — classifier upgrade is the documented path)
|
|
52
|
+
`novel-target`, `scope-edge`, `rate-spike`, `intent-gap`, `sequence` (default: the exfil
|
|
53
|
+
shape read → archive → external-send), `off-hours`, and `wall-crossing` (operator mode).
|
|
54
|
+
Every finding names the receipts behind it — evidence, not vibes.
|
|
55
|
+
|
|
56
|
+
## Honest limits (read these)
|
|
57
|
+
- **Detection, not prevention** — a sentinel sees what's recorded; an agent acting
|
|
58
|
+
entirely off-rails is the credential-custody problem, not a sentinel gap.
|
|
59
|
+
- **False positives are structural** — agents legitimately change. Default response is the
|
|
60
|
+
`require_approval` speed bump (`escalationRule`), **never** auto-revocation; `freeze` is
|
|
61
|
+
always human-in-the-loop (revocation needs the owner's key, which the sentinel never holds).
|
|
62
|
+
`escalationRule` returns `null` when a finding names no specific targets (e.g. `scope-edge`) —
|
|
63
|
+
it will not silently generate a `*` rule that gates the agent's whole surface.
|
|
64
|
+
- **In-scope compromise is the hard case** — a poisoned agent doing plausible actions
|
|
65
|
+
inside its scopes evades metadata detection; sequences/rates narrow the window, never to zero.
|
|
66
|
+
|
|
67
|
+
## Changelog
|
|
68
|
+
- **0.1.0** — initial release: `buildBaseline`, `scan` (six detectors + operator content hook), `createWatcher` (rolling window + finding de-dup + resumable cursor), `escalationRule`, `buildAlertReceipt`/`verifyAlert`.
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/sentinel — runtime behavioral monitoring for agents ("antivirus for agents").
|
|
3
|
+
*
|
|
4
|
+
* The behavioral layer between `@zanii/monitor` (log integrity) and `@zanii/policy`
|
|
5
|
+
* (pre-action rules): consume the receipt stream, score **drift** — what an agent
|
|
6
|
+
* *actually does* vs what it was *made to do* (declared scopes + learned habits) — and
|
|
7
|
+
* feed back: escalate to `require_approval`, prepare a human-gated freeze, page.
|
|
8
|
+
*
|
|
9
|
+
* The Zanii twist: findings become `sentinel.alert` receipts recorded by the sentinel's
|
|
10
|
+
* OWN did:key (watcher ≠ watched), so detection itself is tamper-evident — and so is
|
|
11
|
+
* silence (no alert history is a visible fact a buyer can check).
|
|
12
|
+
*
|
|
13
|
+
* Two modes, forced by the metadata-only ledger stream (payloads are salted hashes):
|
|
14
|
+
* **ledger mode** — anyone watches behavior shape (targets, rates, sequences, intent
|
|
15
|
+
* gaps) with no operator cooperation; **operator mode** — inject `checkContent` (e.g.
|
|
16
|
+
* `@zanii/walls` `checkOutput` over raw payloads, pre-hash) for content detection.
|
|
17
|
+
*
|
|
18
|
+
* Honest limits: detection, not prevention (off-rails action is the credential-custody
|
|
19
|
+
* problem); false positives are structural — default to the `require_approval` speed
|
|
20
|
+
* bump, never auto-revoke; in-scope compromise is the hard case — sequences and rates
|
|
21
|
+
* narrow the window, never to zero.
|
|
22
|
+
*/
|
|
23
|
+
import { type DelegationCert, type Receipt } from '@zanii/core';
|
|
24
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
25
|
+
export interface Baseline {
|
|
26
|
+
v: 1;
|
|
27
|
+
agent_id: string;
|
|
28
|
+
/** Declared: effective scopes from the delegation chain — what the agent is FOR. */
|
|
29
|
+
scopes: string[];
|
|
30
|
+
/** Learned: target prefixes seen in history (first two segments, e.g. `crm.lookup`). */
|
|
31
|
+
target_prefixes: string[];
|
|
32
|
+
/**
|
|
33
|
+
* Learned: actions-per-hour mean/std in **integer milli-units** (×1000). Protocol
|
|
34
|
+
* objects are float-free — JCS and JSON can disagree on floats, and a baseline is
|
|
35
|
+
* hashed into every alert, so it must be byte-identical across languages.
|
|
36
|
+
*/
|
|
37
|
+
rate: {
|
|
38
|
+
mean_milli: number;
|
|
39
|
+
std_milli: number;
|
|
40
|
+
};
|
|
41
|
+
/** Learned: share of actions bracketed by `action_intent`, in milli-units (0..1000). */
|
|
42
|
+
intent_milli: number;
|
|
43
|
+
/** Learned: UTC-hour activity histogram (24 buckets). */
|
|
44
|
+
active_hours: number[];
|
|
45
|
+
sample_size: number;
|
|
46
|
+
}
|
|
47
|
+
export declare function targetPrefix(target: string): string;
|
|
48
|
+
/** Build the drift baseline for one agent from its delegation (declared) + history (learned). */
|
|
49
|
+
export declare function buildBaseline(agentId: string, opts?: {
|
|
50
|
+
receipts?: Receipt[];
|
|
51
|
+
delegation?: DelegationCert[];
|
|
52
|
+
}): Baseline;
|
|
53
|
+
/** Canonical hash of a baseline — pinned into every alert ("drift relative to WHAT"). */
|
|
54
|
+
export declare function baselineHash(b: Baseline): string;
|
|
55
|
+
export type Severity = 'low' | 'medium' | 'high';
|
|
56
|
+
export interface Finding {
|
|
57
|
+
rule: string;
|
|
58
|
+
severity: Severity;
|
|
59
|
+
agent_id: string;
|
|
60
|
+
/** The receipts behind this finding — evidence, not vibes. */
|
|
61
|
+
receipt_hashes: string[];
|
|
62
|
+
/** The targets involved (drives `escalationRule`). */
|
|
63
|
+
targets: string[];
|
|
64
|
+
observed: string;
|
|
65
|
+
expected: string;
|
|
66
|
+
ts: string;
|
|
67
|
+
}
|
|
68
|
+
export interface SequenceRule {
|
|
69
|
+
name: string;
|
|
70
|
+
/** Ordered regexes over targets; a match = the steps occur in order within `windowMs`. */
|
|
71
|
+
steps: RegExp[];
|
|
72
|
+
windowMs: number;
|
|
73
|
+
}
|
|
74
|
+
/** The exfil shape: read-ish → encode/archive-ish → external-send-ish. */
|
|
75
|
+
export declare const EXFIL_SEQUENCE: SequenceRule;
|
|
76
|
+
export interface ScanOptions {
|
|
77
|
+
/** Rejected-write events (from `receipt.rejected` webhooks) — scope-probing signal. */
|
|
78
|
+
rejections?: Array<{
|
|
79
|
+
agent_id?: string;
|
|
80
|
+
error?: string;
|
|
81
|
+
ts?: string;
|
|
82
|
+
}>;
|
|
83
|
+
/** Rate-spike threshold in robust z-scores (default 3). */
|
|
84
|
+
rateZ?: number;
|
|
85
|
+
/** Sequence rules (default: the exfil shape). */
|
|
86
|
+
sequences?: SequenceRule[];
|
|
87
|
+
/** Operator mode: return raw payload text for a receipt (pre-hash). */
|
|
88
|
+
payloadOf?: (r: Receipt & {
|
|
89
|
+
hash?: string;
|
|
90
|
+
}) => string | undefined;
|
|
91
|
+
/** Operator mode: content detector (e.g. walls' checkOutput). Return violations. */
|
|
92
|
+
checkContent?: (payloadText: string, r: Receipt) => string[];
|
|
93
|
+
/** Minimum baseline sample size before statistical rules fire (default 20). */
|
|
94
|
+
minSample?: number;
|
|
95
|
+
}
|
|
96
|
+
type Scanned = Receipt & {
|
|
97
|
+
hash?: string;
|
|
98
|
+
};
|
|
99
|
+
/** Scan a window of an agent's receipts against its baseline. Pure — no I/O. */
|
|
100
|
+
export declare function scan(receipts: Scanned[], baseline: Baseline, opts?: ScanOptions): Finding[];
|
|
101
|
+
export interface WatcherOptions {
|
|
102
|
+
server: string;
|
|
103
|
+
fetchImpl?: FetchLike;
|
|
104
|
+
/** Baseline per watched agent DID. */
|
|
105
|
+
baselines: Record<string, Baseline>;
|
|
106
|
+
onFinding: (finding: Finding) => void | Promise<void>;
|
|
107
|
+
scan?: ScanOptions;
|
|
108
|
+
/** Page size for /v1/recent (server caps at 100). */
|
|
109
|
+
limit?: number;
|
|
110
|
+
/** Resume from a persisted cursor — the highest ledger index already processed. */
|
|
111
|
+
cursor?: number;
|
|
112
|
+
/**
|
|
113
|
+
* Rolling window of receipts kept per agent, so **windowed detectors** (`sequence`,
|
|
114
|
+
* `rate-spike`, `intent-gap`) see across polls. Without this a 3-step exfil arriving
|
|
115
|
+
* over three 60s polls would never be detected — each poll would see one step.
|
|
116
|
+
* Default 2h (covers the 30-min exfil window + hourly rate buckets).
|
|
117
|
+
*/
|
|
118
|
+
windowMs?: number;
|
|
119
|
+
}
|
|
120
|
+
export interface Watcher {
|
|
121
|
+
/** One poll: fetch new receipts, scan the rolling window, dispatch *new* findings. */
|
|
122
|
+
tick(): Promise<Finding[]>;
|
|
123
|
+
/** Highest ledger index processed — **persist this** and pass back as `cursor`. */
|
|
124
|
+
cursor(): number;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Ledger-mode watcher over `GET /v1/recent`. Call `tick()` on your own schedule.
|
|
128
|
+
*
|
|
129
|
+
* Keeps a rolling per-agent window (see `windowMs`) so windowed detectors work across
|
|
130
|
+
* polls, and de-duplicates findings so a receipt already alerted on isn't re-alerted.
|
|
131
|
+
*
|
|
132
|
+
* **Limit:** `/v1/recent` is a *global* feed capped at 100 by the server. On a busy
|
|
133
|
+
* ledger, receipts can be missed between polls (the cursor jumps). For production, drive
|
|
134
|
+
* `scan` from `receipt.recorded` webhooks (`@zanii/webhooks`) instead of polling.
|
|
135
|
+
*/
|
|
136
|
+
export declare function createWatcher(opts: WatcherOptions): Watcher;
|
|
137
|
+
/**
|
|
138
|
+
* The default response: a `@zanii/policy` rule turning the flagged prefixes into a
|
|
139
|
+
* `require_approval` speed bump.
|
|
140
|
+
*
|
|
141
|
+
* Returns `null` when the finding names no specific targets (e.g. `scope-edge`, which is
|
|
142
|
+
* driven by rejections, not receipts) — we will **not** silently generate a `*` rule that
|
|
143
|
+
* gates the agent's entire surface. That call belongs to a human.
|
|
144
|
+
*/
|
|
145
|
+
export declare function escalationRule(f: Finding): {
|
|
146
|
+
id: string;
|
|
147
|
+
effect: 'require_approval';
|
|
148
|
+
targets: string[];
|
|
149
|
+
} | null;
|
|
150
|
+
/** Record with the sentinel's OWN did:key (watcher ≠ watched): `sentinel.alert`. */
|
|
151
|
+
export declare function buildAlertReceipt(f: Finding, opts: {
|
|
152
|
+
baselineHash: string;
|
|
153
|
+
}): {
|
|
154
|
+
target: string;
|
|
155
|
+
payload: Record<string, unknown>;
|
|
156
|
+
};
|
|
157
|
+
export interface AlertCheck {
|
|
158
|
+
ok: boolean;
|
|
159
|
+
reasons: string[];
|
|
160
|
+
}
|
|
161
|
+
/** Structurally validate a `sentinel.alert` payload. */
|
|
162
|
+
export declare function verifyAlert(payload: Record<string, unknown> | undefined): AlertCheck;
|
|
163
|
+
export {};
|
|
164
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRo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EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,GAAG,UAAU,CAUpF"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/sentinel — runtime behavioral monitoring for agents ("antivirus for agents").
|
|
3
|
+
*
|
|
4
|
+
* The behavioral layer between `@zanii/monitor` (log integrity) and `@zanii/policy`
|
|
5
|
+
* (pre-action rules): consume the receipt stream, score **drift** — what an agent
|
|
6
|
+
* *actually does* vs what it was *made to do* (declared scopes + learned habits) — and
|
|
7
|
+
* feed back: escalate to `require_approval`, prepare a human-gated freeze, page.
|
|
8
|
+
*
|
|
9
|
+
* The Zanii twist: findings become `sentinel.alert` receipts recorded by the sentinel's
|
|
10
|
+
* OWN did:key (watcher ≠ watched), so detection itself is tamper-evident — and so is
|
|
11
|
+
* silence (no alert history is a visible fact a buyer can check).
|
|
12
|
+
*
|
|
13
|
+
* Two modes, forced by the metadata-only ledger stream (payloads are salted hashes):
|
|
14
|
+
* **ledger mode** — anyone watches behavior shape (targets, rates, sequences, intent
|
|
15
|
+
* gaps) with no operator cooperation; **operator mode** — inject `checkContent` (e.g.
|
|
16
|
+
* `@zanii/walls` `checkOutput` over raw payloads, pre-hash) for content detection.
|
|
17
|
+
*
|
|
18
|
+
* Honest limits: detection, not prevention (off-rails action is the credential-custody
|
|
19
|
+
* problem); false positives are structural — default to the `require_approval` speed
|
|
20
|
+
* bump, never auto-revoke; in-scope compromise is the hard case — sequences and rates
|
|
21
|
+
* narrow the window, never to zero.
|
|
22
|
+
*/
|
|
23
|
+
import { jcsHash, scopesAllow, verifyChain } from '@zanii/core';
|
|
24
|
+
export function targetPrefix(target) {
|
|
25
|
+
return target.split('.').slice(0, 2).join('.');
|
|
26
|
+
}
|
|
27
|
+
function hourOf(ts) {
|
|
28
|
+
return new Date(ts).getUTCHours();
|
|
29
|
+
}
|
|
30
|
+
/** Build the drift baseline for one agent from its delegation (declared) + history (learned). */
|
|
31
|
+
export function buildBaseline(agentId, opts = {}) {
|
|
32
|
+
const history = (opts.receipts ?? []).filter((r) => r.agent_id === agentId);
|
|
33
|
+
const scopes = opts.delegation
|
|
34
|
+
? verifyChain(opts.delegation, { agentId }).effectiveScopes ?? []
|
|
35
|
+
: [];
|
|
36
|
+
const prefixes = new Set();
|
|
37
|
+
const hours = new Array(24).fill(0);
|
|
38
|
+
const perHourCounts = new Map();
|
|
39
|
+
let intents = 0;
|
|
40
|
+
let actions = 0;
|
|
41
|
+
for (const r of history) {
|
|
42
|
+
prefixes.add(targetPrefix(r.target));
|
|
43
|
+
hours[hourOf(r.ts)] = (hours[hourOf(r.ts)] ?? 0) + 1;
|
|
44
|
+
const bucket = r.ts.slice(0, 13); // YYYY-MM-DDTHH
|
|
45
|
+
perHourCounts.set(bucket, (perHourCounts.get(bucket) ?? 0) + 1);
|
|
46
|
+
if (r.action === 'action_intent')
|
|
47
|
+
intents += 1;
|
|
48
|
+
else
|
|
49
|
+
actions += 1;
|
|
50
|
+
}
|
|
51
|
+
const counts = [...perHourCounts.values()];
|
|
52
|
+
const mean = counts.length ? counts.reduce((a, b) => a + b, 0) / counts.length : 0;
|
|
53
|
+
const variance = counts.length ? counts.reduce((a, b) => a + (b - mean) ** 2, 0) / counts.length : 0;
|
|
54
|
+
return {
|
|
55
|
+
v: 1,
|
|
56
|
+
agent_id: agentId,
|
|
57
|
+
scopes,
|
|
58
|
+
target_prefixes: [...prefixes].sort(),
|
|
59
|
+
rate: { mean_milli: Math.round(mean * 1000), std_milli: Math.round(Math.sqrt(variance) * 1000) },
|
|
60
|
+
intent_milli: actions > 0 ? Math.round((intents / actions) * 1000) : 0,
|
|
61
|
+
active_hours: hours,
|
|
62
|
+
sample_size: history.length,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Canonical hash of a baseline — pinned into every alert ("drift relative to WHAT"). */
|
|
66
|
+
export function baselineHash(b) {
|
|
67
|
+
return jcsHash(b);
|
|
68
|
+
}
|
|
69
|
+
/** The exfil shape: read-ish → encode/archive-ish → external-send-ish. */
|
|
70
|
+
export const EXFIL_SEQUENCE = {
|
|
71
|
+
name: 'exfil-shape',
|
|
72
|
+
steps: [/\.(read|list|export|fetch|get|search)/i, /\.(encode|archive|zip|compress|bundle)/i, /(send|post|upload|publish|external)/i],
|
|
73
|
+
windowMs: 30 * 60_000,
|
|
74
|
+
};
|
|
75
|
+
function finding(rule, severity, agentId, evidence, observed, expected) {
|
|
76
|
+
return {
|
|
77
|
+
rule,
|
|
78
|
+
severity,
|
|
79
|
+
agent_id: agentId,
|
|
80
|
+
receipt_hashes: evidence.map((r) => r.hash ?? jcsHash(r)),
|
|
81
|
+
targets: [...new Set(evidence.map((r) => r.target))],
|
|
82
|
+
observed,
|
|
83
|
+
expected,
|
|
84
|
+
ts: evidence[evidence.length - 1]?.ts ?? new Date(0).toISOString(),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** Scan a window of an agent's receipts against its baseline. Pure — no I/O. */
|
|
88
|
+
export function scan(receipts, baseline, opts = {}) {
|
|
89
|
+
const findings = [];
|
|
90
|
+
const mine = receipts
|
|
91
|
+
.filter((r) => r.agent_id === baseline.agent_id)
|
|
92
|
+
.sort((a, b) => a.ts.localeCompare(b.ts));
|
|
93
|
+
const minSample = opts.minSample ?? 20;
|
|
94
|
+
const known = new Set(baseline.target_prefixes);
|
|
95
|
+
// 1. novel-target — prefix outside the learned set; high severity if also outside declared scopes
|
|
96
|
+
const novel = new Map();
|
|
97
|
+
for (const r of mine) {
|
|
98
|
+
const p = targetPrefix(r.target);
|
|
99
|
+
if (baseline.sample_size >= minSample && !known.has(p)) {
|
|
100
|
+
novel.set(p, [...(novel.get(p) ?? []), r]);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
for (const [prefix, evidence] of novel) {
|
|
104
|
+
const inScope = baseline.scopes.length === 0 || scopesAllow(baseline.scopes, evidence[0].target);
|
|
105
|
+
findings.push(finding('novel-target', inScope ? 'medium' : 'high', baseline.agent_id, evidence, `target prefix ${prefix} never seen in baseline`, `one of [${baseline.target_prefixes.join(', ')}]`));
|
|
106
|
+
}
|
|
107
|
+
// 2. scope-edge — rejected writes are the probing signal (from receipt.rejected webhooks)
|
|
108
|
+
const probes = (opts.rejections ?? []).filter((e) => !e.agent_id || e.agent_id === baseline.agent_id);
|
|
109
|
+
if (probes.length > 0) {
|
|
110
|
+
findings.push({
|
|
111
|
+
rule: 'scope-edge', severity: probes.length > 2 ? 'high' : 'medium', agent_id: baseline.agent_id,
|
|
112
|
+
receipt_hashes: [], targets: [],
|
|
113
|
+
observed: `${probes.length} rejected write(s): ${probes.map((p) => p.error).filter(Boolean).slice(0, 3).join('; ')}`,
|
|
114
|
+
expected: 'no rejected writes', ts: probes[probes.length - 1]?.ts ?? new Date(0).toISOString(),
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
// 3. rate-spike — actions per hour vs baseline (milli-units; +1000 keeps std=0 from firing on +1)
|
|
118
|
+
if (baseline.sample_size >= minSample) {
|
|
119
|
+
const buckets = new Map();
|
|
120
|
+
for (const r of mine)
|
|
121
|
+
buckets.set(r.ts.slice(0, 13), [...(buckets.get(r.ts.slice(0, 13)) ?? []), r]);
|
|
122
|
+
const z = opts.rateZ ?? 3;
|
|
123
|
+
for (const [hour, rs] of buckets) {
|
|
124
|
+
if (rs.length * 1000 > baseline.rate.mean_milli + z * (baseline.rate.std_milli + 1000)) {
|
|
125
|
+
findings.push(finding('rate-spike', 'high', baseline.agent_id, rs, `${rs.length} actions in hour ${hour}`, `~${(baseline.rate.mean_milli / 1000).toFixed(1)}/h (σ ${(baseline.rate.std_milli / 1000).toFixed(1)})`));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// 4. intent-gap — the agent normally brackets actions with intents, this window doesn't
|
|
130
|
+
if (baseline.intent_milli >= 800 && mine.length >= 5) {
|
|
131
|
+
const intents = mine.filter((r) => r.action === 'action_intent').length;
|
|
132
|
+
const actions = mine.length - intents;
|
|
133
|
+
const ratioMilli = actions > 0 ? Math.round((intents / actions) * 1000) : 1000;
|
|
134
|
+
if (ratioMilli < baseline.intent_milli / 2) {
|
|
135
|
+
findings.push(finding('intent-gap', 'high', baseline.agent_id, mine.filter((r) => r.action !== 'action_intent'), `intent ratio ${(ratioMilli / 1000).toFixed(2)} this window`, `~${(baseline.intent_milli / 1000).toFixed(2)} (agent normally declares intent)`));
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// 5. sequence — ordered target patterns within a window (default: the exfil shape)
|
|
139
|
+
for (const rule of opts.sequences ?? [EXFIL_SEQUENCE]) {
|
|
140
|
+
let step = 0;
|
|
141
|
+
let startMs = 0;
|
|
142
|
+
const evidence = [];
|
|
143
|
+
for (const r of mine) {
|
|
144
|
+
if (rule.steps[step].test(r.target)) {
|
|
145
|
+
if (step === 0)
|
|
146
|
+
startMs = Date.parse(r.ts);
|
|
147
|
+
if (Date.parse(r.ts) - startMs <= rule.windowMs) {
|
|
148
|
+
evidence.push(r);
|
|
149
|
+
step += 1;
|
|
150
|
+
if (step === rule.steps.length) {
|
|
151
|
+
findings.push(finding(`sequence:${rule.name}`, 'high', baseline.agent_id, [...evidence], evidence.map((e) => e.target).join(' → '), `no ${rule.name} sequence`));
|
|
152
|
+
step = 0;
|
|
153
|
+
evidence.length = 0;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
step = 0;
|
|
158
|
+
evidence.length = 0;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
// 6. off-hours — activity in hours the baseline says are silent
|
|
164
|
+
if (baseline.sample_size >= minSample) {
|
|
165
|
+
const silent = mine.filter((r) => (baseline.active_hours[hourOf(r.ts)] ?? 0) === 0);
|
|
166
|
+
if (silent.length > 0) {
|
|
167
|
+
findings.push(finding('off-hours', 'medium', baseline.agent_id, silent, `${silent.length} action(s) at UTC hour(s) [${[...new Set(silent.map((r) => hourOf(r.ts)))].join(',')}]`, 'activity only in learned active hours'));
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// 7. wall-crossing — operator mode only (raw payloads pre-hash)
|
|
171
|
+
if (opts.payloadOf && opts.checkContent) {
|
|
172
|
+
for (const r of mine) {
|
|
173
|
+
const text = opts.payloadOf(r);
|
|
174
|
+
if (text === undefined)
|
|
175
|
+
continue;
|
|
176
|
+
const violations = opts.checkContent(text, r);
|
|
177
|
+
if (violations.length > 0) {
|
|
178
|
+
findings.push(finding('wall-crossing', 'high', baseline.agent_id, [r], `content violations: ${violations.join(', ')}`, 'no boundary-crossing content'));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return findings;
|
|
183
|
+
}
|
|
184
|
+
/** Stable identity of a finding, so the same one isn't re-alerted on every poll. */
|
|
185
|
+
function fingerprint(f) {
|
|
186
|
+
return `${f.rule}|${[...f.receipt_hashes].sort().join(',')}|${f.ts}`;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Ledger-mode watcher over `GET /v1/recent`. Call `tick()` on your own schedule.
|
|
190
|
+
*
|
|
191
|
+
* Keeps a rolling per-agent window (see `windowMs`) so windowed detectors work across
|
|
192
|
+
* polls, and de-duplicates findings so a receipt already alerted on isn't re-alerted.
|
|
193
|
+
*
|
|
194
|
+
* **Limit:** `/v1/recent` is a *global* feed capped at 100 by the server. On a busy
|
|
195
|
+
* ledger, receipts can be missed between polls (the cursor jumps). For production, drive
|
|
196
|
+
* `scan` from `receipt.recorded` webhooks (`@zanii/webhooks`) instead of polling.
|
|
197
|
+
*/
|
|
198
|
+
export function createWatcher(opts) {
|
|
199
|
+
const fetchImpl = opts.fetchImpl ?? ((u, i) => fetch(u, i));
|
|
200
|
+
const server = opts.server.replace(/\/$/, '');
|
|
201
|
+
const windowMs = opts.windowMs ?? 2 * 60 * 60_000;
|
|
202
|
+
let cursor = opts.cursor ?? -1;
|
|
203
|
+
const buffers = {};
|
|
204
|
+
const seen = new Set();
|
|
205
|
+
return {
|
|
206
|
+
cursor: () => cursor,
|
|
207
|
+
async tick() {
|
|
208
|
+
const res = await fetchImpl(`${server}/v1/recent?limit=${opts.limit ?? 100}`);
|
|
209
|
+
if (!res.ok)
|
|
210
|
+
throw new Error(`recent fetch failed: HTTP ${res.status}`);
|
|
211
|
+
const body = (await res.json());
|
|
212
|
+
const fresh = body.receipts.filter((r) => r.index > cursor);
|
|
213
|
+
for (const r of fresh)
|
|
214
|
+
cursor = Math.max(cursor, r.index);
|
|
215
|
+
const all = [];
|
|
216
|
+
for (const [did, baseline] of Object.entries(opts.baselines)) {
|
|
217
|
+
const mine = fresh.filter((r) => r.receipt.agent_id === did).map((r) => ({ ...r.receipt, hash: r.hash }));
|
|
218
|
+
if (mine.length === 0)
|
|
219
|
+
continue;
|
|
220
|
+
// Rolling window: append, then trim to `windowMs` behind the newest receipt.
|
|
221
|
+
const buf = [...(buffers[did] ?? []), ...mine].sort((a, b) => a.ts.localeCompare(b.ts));
|
|
222
|
+
const newest = Date.parse(buf[buf.length - 1].ts);
|
|
223
|
+
buffers[did] = buf.filter((r) => newest - Date.parse(r.ts) <= windowMs);
|
|
224
|
+
for (const f of scan(buffers[did], baseline, opts.scan)) {
|
|
225
|
+
const fp = fingerprint(f);
|
|
226
|
+
if (seen.has(fp))
|
|
227
|
+
continue; // already alerted — don't re-fire every poll
|
|
228
|
+
seen.add(fp);
|
|
229
|
+
all.push(f);
|
|
230
|
+
await opts.onFinding(f);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (seen.size > 5000)
|
|
234
|
+
seen.clear(); // bounded; worst case a stale finding re-fires once
|
|
235
|
+
return all;
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* The default response: a `@zanii/policy` rule turning the flagged prefixes into a
|
|
241
|
+
* `require_approval` speed bump.
|
|
242
|
+
*
|
|
243
|
+
* Returns `null` when the finding names no specific targets (e.g. `scope-edge`, which is
|
|
244
|
+
* driven by rejections, not receipts) — we will **not** silently generate a `*` rule that
|
|
245
|
+
* gates the agent's entire surface. That call belongs to a human.
|
|
246
|
+
*/
|
|
247
|
+
export function escalationRule(f) {
|
|
248
|
+
const prefixes = [...new Set(f.targets.map((t) => `${targetPrefix(t)}.*`))];
|
|
249
|
+
if (prefixes.length === 0)
|
|
250
|
+
return null;
|
|
251
|
+
return {
|
|
252
|
+
id: `sentinel-${f.rule.replace(/[^a-z0-9-]/gi, '-')}-${f.agent_id.slice(-8)}`,
|
|
253
|
+
effect: 'require_approval',
|
|
254
|
+
targets: prefixes,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
// ---------------------------------------------------------------------------
|
|
258
|
+
// Alerts are receipts — detection itself is tamper-evident
|
|
259
|
+
// ---------------------------------------------------------------------------
|
|
260
|
+
/** Record with the sentinel's OWN did:key (watcher ≠ watched): `sentinel.alert`. */
|
|
261
|
+
export function buildAlertReceipt(f, opts) {
|
|
262
|
+
return {
|
|
263
|
+
target: 'sentinel.alert',
|
|
264
|
+
payload: {
|
|
265
|
+
_zr_kind: 'sentinel',
|
|
266
|
+
v: 1,
|
|
267
|
+
rule: f.rule,
|
|
268
|
+
severity: f.severity,
|
|
269
|
+
watched_agent: f.agent_id,
|
|
270
|
+
evidence: f.receipt_hashes,
|
|
271
|
+
observed: f.observed,
|
|
272
|
+
expected: f.expected,
|
|
273
|
+
baseline_hash: opts.baselineHash,
|
|
274
|
+
ts: f.ts,
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
/** Structurally validate a `sentinel.alert` payload. */
|
|
279
|
+
export function verifyAlert(payload) {
|
|
280
|
+
const reasons = [];
|
|
281
|
+
const p = payload ?? {};
|
|
282
|
+
if (p._zr_kind !== 'sentinel' || p.v !== 1)
|
|
283
|
+
reasons.push('not a sentinel alert (v1)');
|
|
284
|
+
if (!p.rule)
|
|
285
|
+
reasons.push('missing rule');
|
|
286
|
+
if (!['low', 'medium', 'high'].includes(p.severity))
|
|
287
|
+
reasons.push('missing/invalid severity');
|
|
288
|
+
if (!p.watched_agent)
|
|
289
|
+
reasons.push('missing watched_agent');
|
|
290
|
+
if (!Array.isArray(p.evidence))
|
|
291
|
+
reasons.push('missing evidence array');
|
|
292
|
+
if (typeof p.baseline_hash !== 'string' || !p.baseline_hash.startsWith('sha256:'))
|
|
293
|
+
reasons.push('missing/invalid baseline_hash');
|
|
294
|
+
return { ok: reasons.length === 0, reasons };
|
|
295
|
+
}
|
|
296
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAqC,MAAM,aAAa,CAAC;AA4BnG,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,OAAO,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,MAAM,CAAC,EAAU;IACxB,OAAO,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;AACpC,CAAC;AAED,iGAAiG;AACjG,MAAM,UAAU,aAAa,CAC3B,OAAe,EACf,OAAgE,EAAE;IAElE,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC;IAC5E,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU;QAC5B,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,eAA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QAAE,OAAO,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;IACvE,IAAI,OAAO,CAAC,CAAC,aAAa,KAAK,QAAQ,IAAI,CAAC,CAAC,CAAC,aAAa,CAAC,UAAU,CAAC,SAAS,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,+BAA+B,CAAC,CAAC;IACjI,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC;AAC/C,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zanii/sentinel",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Runtime behavioral monitoring for agents ('antivirus for agents'): score drift between what an agent actually does and what it was made to do, from the receipt stream — and the alerts themselves are tamper-evident receipts.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://ledger.zanii.agency",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"src",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=18"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^26.1.0",
|
|
30
|
+
"typescript": "^5.8.2",
|
|
31
|
+
"vitest": "^3.0.9"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@zanii/core": "0.4.0"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsc -p tsconfig.build.json",
|
|
38
|
+
"test": "vitest run",
|
|
39
|
+
"typecheck": "tsc --noEmit"
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/sentinel — runtime behavioral monitoring for agents ("antivirus for agents").
|
|
3
|
+
*
|
|
4
|
+
* The behavioral layer between `@zanii/monitor` (log integrity) and `@zanii/policy`
|
|
5
|
+
* (pre-action rules): consume the receipt stream, score **drift** — what an agent
|
|
6
|
+
* *actually does* vs what it was *made to do* (declared scopes + learned habits) — and
|
|
7
|
+
* feed back: escalate to `require_approval`, prepare a human-gated freeze, page.
|
|
8
|
+
*
|
|
9
|
+
* The Zanii twist: findings become `sentinel.alert` receipts recorded by the sentinel's
|
|
10
|
+
* OWN did:key (watcher ≠ watched), so detection itself is tamper-evident — and so is
|
|
11
|
+
* silence (no alert history is a visible fact a buyer can check).
|
|
12
|
+
*
|
|
13
|
+
* Two modes, forced by the metadata-only ledger stream (payloads are salted hashes):
|
|
14
|
+
* **ledger mode** — anyone watches behavior shape (targets, rates, sequences, intent
|
|
15
|
+
* gaps) with no operator cooperation; **operator mode** — inject `checkContent` (e.g.
|
|
16
|
+
* `@zanii/walls` `checkOutput` over raw payloads, pre-hash) for content detection.
|
|
17
|
+
*
|
|
18
|
+
* Honest limits: detection, not prevention (off-rails action is the credential-custody
|
|
19
|
+
* problem); false positives are structural — default to the `require_approval` speed
|
|
20
|
+
* bump, never auto-revoke; in-scope compromise is the hard case — sequences and rates
|
|
21
|
+
* narrow the window, never to zero.
|
|
22
|
+
*/
|
|
23
|
+
import { jcsHash, scopesAllow, verifyChain, type DelegationCert, type Receipt } from '@zanii/core';
|
|
24
|
+
|
|
25
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
26
|
+
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Baseline — declared (cryptographic) + learned (statistical)
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
export interface Baseline {
|
|
32
|
+
v: 1;
|
|
33
|
+
agent_id: string;
|
|
34
|
+
/** Declared: effective scopes from the delegation chain — what the agent is FOR. */
|
|
35
|
+
scopes: string[];
|
|
36
|
+
/** Learned: target prefixes seen in history (first two segments, e.g. `crm.lookup`). */
|
|
37
|
+
target_prefixes: string[];
|
|
38
|
+
/**
|
|
39
|
+
* Learned: actions-per-hour mean/std in **integer milli-units** (×1000). Protocol
|
|
40
|
+
* objects are float-free — JCS and JSON can disagree on floats, and a baseline is
|
|
41
|
+
* hashed into every alert, so it must be byte-identical across languages.
|
|
42
|
+
*/
|
|
43
|
+
rate: { mean_milli: number; std_milli: number };
|
|
44
|
+
/** Learned: share of actions bracketed by `action_intent`, in milli-units (0..1000). */
|
|
45
|
+
intent_milli: number;
|
|
46
|
+
/** Learned: UTC-hour activity histogram (24 buckets). */
|
|
47
|
+
active_hours: number[];
|
|
48
|
+
sample_size: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function targetPrefix(target: string): string {
|
|
52
|
+
return target.split('.').slice(0, 2).join('.');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function hourOf(ts: string): number {
|
|
56
|
+
return new Date(ts).getUTCHours();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Build the drift baseline for one agent from its delegation (declared) + history (learned). */
|
|
60
|
+
export function buildBaseline(
|
|
61
|
+
agentId: string,
|
|
62
|
+
opts: { receipts?: Receipt[]; delegation?: DelegationCert[] } = {},
|
|
63
|
+
): Baseline {
|
|
64
|
+
const history = (opts.receipts ?? []).filter((r) => r.agent_id === agentId);
|
|
65
|
+
const scopes = opts.delegation
|
|
66
|
+
? verifyChain(opts.delegation, { agentId }).effectiveScopes ?? []
|
|
67
|
+
: [];
|
|
68
|
+
const prefixes = new Set<string>();
|
|
69
|
+
const hours = new Array<number>(24).fill(0);
|
|
70
|
+
const perHourCounts = new Map<string, number>();
|
|
71
|
+
let intents = 0;
|
|
72
|
+
let actions = 0;
|
|
73
|
+
for (const r of history) {
|
|
74
|
+
prefixes.add(targetPrefix(r.target));
|
|
75
|
+
hours[hourOf(r.ts)] = (hours[hourOf(r.ts)] ?? 0) + 1;
|
|
76
|
+
const bucket = r.ts.slice(0, 13); // YYYY-MM-DDTHH
|
|
77
|
+
perHourCounts.set(bucket, (perHourCounts.get(bucket) ?? 0) + 1);
|
|
78
|
+
if (r.action === 'action_intent') intents += 1;
|
|
79
|
+
else actions += 1;
|
|
80
|
+
}
|
|
81
|
+
const counts = [...perHourCounts.values()];
|
|
82
|
+
const mean = counts.length ? counts.reduce((a, b) => a + b, 0) / counts.length : 0;
|
|
83
|
+
const variance = counts.length ? counts.reduce((a, b) => a + (b - mean) ** 2, 0) / counts.length : 0;
|
|
84
|
+
return {
|
|
85
|
+
v: 1,
|
|
86
|
+
agent_id: agentId,
|
|
87
|
+
scopes,
|
|
88
|
+
target_prefixes: [...prefixes].sort(),
|
|
89
|
+
rate: { mean_milli: Math.round(mean * 1000), std_milli: Math.round(Math.sqrt(variance) * 1000) },
|
|
90
|
+
intent_milli: actions > 0 ? Math.round((intents / actions) * 1000) : 0,
|
|
91
|
+
active_hours: hours,
|
|
92
|
+
sample_size: history.length,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Canonical hash of a baseline — pinned into every alert ("drift relative to WHAT"). */
|
|
97
|
+
export function baselineHash(b: Baseline): string {
|
|
98
|
+
return jcsHash(b as unknown as Record<string, unknown>);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ---------------------------------------------------------------------------
|
|
102
|
+
// Detectors — a heuristic ladder; every finding names its evidence receipts
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
export type Severity = 'low' | 'medium' | 'high';
|
|
106
|
+
|
|
107
|
+
export interface Finding {
|
|
108
|
+
rule: string;
|
|
109
|
+
severity: Severity;
|
|
110
|
+
agent_id: string;
|
|
111
|
+
/** The receipts behind this finding — evidence, not vibes. */
|
|
112
|
+
receipt_hashes: string[];
|
|
113
|
+
/** The targets involved (drives `escalationRule`). */
|
|
114
|
+
targets: string[];
|
|
115
|
+
observed: string;
|
|
116
|
+
expected: string;
|
|
117
|
+
ts: string;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface SequenceRule {
|
|
121
|
+
name: string;
|
|
122
|
+
/** Ordered regexes over targets; a match = the steps occur in order within `windowMs`. */
|
|
123
|
+
steps: RegExp[];
|
|
124
|
+
windowMs: number;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The exfil shape: read-ish → encode/archive-ish → external-send-ish. */
|
|
128
|
+
export const EXFIL_SEQUENCE: SequenceRule = {
|
|
129
|
+
name: 'exfil-shape',
|
|
130
|
+
steps: [/\.(read|list|export|fetch|get|search)/i, /\.(encode|archive|zip|compress|bundle)/i, /(send|post|upload|publish|external)/i],
|
|
131
|
+
windowMs: 30 * 60_000,
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
export interface ScanOptions {
|
|
135
|
+
/** Rejected-write events (from `receipt.rejected` webhooks) — scope-probing signal. */
|
|
136
|
+
rejections?: Array<{ agent_id?: string; error?: string; ts?: string }>;
|
|
137
|
+
/** Rate-spike threshold in robust z-scores (default 3). */
|
|
138
|
+
rateZ?: number;
|
|
139
|
+
/** Sequence rules (default: the exfil shape). */
|
|
140
|
+
sequences?: SequenceRule[];
|
|
141
|
+
/** Operator mode: return raw payload text for a receipt (pre-hash). */
|
|
142
|
+
payloadOf?: (r: Receipt & { hash?: string }) => string | undefined;
|
|
143
|
+
/** Operator mode: content detector (e.g. walls' checkOutput). Return violations. */
|
|
144
|
+
checkContent?: (payloadText: string, r: Receipt) => string[];
|
|
145
|
+
/** Minimum baseline sample size before statistical rules fire (default 20). */
|
|
146
|
+
minSample?: number;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
type Scanned = Receipt & { hash?: string };
|
|
150
|
+
|
|
151
|
+
function finding(rule: string, severity: Severity, agentId: string, evidence: Scanned[], observed: string, expected: string): Finding {
|
|
152
|
+
return {
|
|
153
|
+
rule,
|
|
154
|
+
severity,
|
|
155
|
+
agent_id: agentId,
|
|
156
|
+
receipt_hashes: evidence.map((r) => r.hash ?? jcsHash(r)),
|
|
157
|
+
targets: [...new Set(evidence.map((r) => r.target))],
|
|
158
|
+
observed,
|
|
159
|
+
expected,
|
|
160
|
+
ts: evidence[evidence.length - 1]?.ts ?? new Date(0).toISOString(),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Scan a window of an agent's receipts against its baseline. Pure — no I/O. */
|
|
165
|
+
export function scan(receipts: Scanned[], baseline: Baseline, opts: ScanOptions = {}): Finding[] {
|
|
166
|
+
const findings: Finding[] = [];
|
|
167
|
+
const mine = receipts
|
|
168
|
+
.filter((r) => r.agent_id === baseline.agent_id)
|
|
169
|
+
.sort((a, b) => a.ts.localeCompare(b.ts));
|
|
170
|
+
const minSample = opts.minSample ?? 20;
|
|
171
|
+
const known = new Set(baseline.target_prefixes);
|
|
172
|
+
|
|
173
|
+
// 1. novel-target — prefix outside the learned set; high severity if also outside declared scopes
|
|
174
|
+
const novel = new Map<string, Scanned[]>();
|
|
175
|
+
for (const r of mine) {
|
|
176
|
+
const p = targetPrefix(r.target);
|
|
177
|
+
if (baseline.sample_size >= minSample && !known.has(p)) {
|
|
178
|
+
novel.set(p, [...(novel.get(p) ?? []), r]);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
for (const [prefix, evidence] of novel) {
|
|
182
|
+
const inScope = baseline.scopes.length === 0 || scopesAllow(baseline.scopes, evidence[0]!.target);
|
|
183
|
+
findings.push(finding('novel-target', inScope ? 'medium' : 'high', baseline.agent_id, evidence,
|
|
184
|
+
`target prefix ${prefix} never seen in baseline`, `one of [${baseline.target_prefixes.join(', ')}]`));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// 2. scope-edge — rejected writes are the probing signal (from receipt.rejected webhooks)
|
|
188
|
+
const probes = (opts.rejections ?? []).filter((e) => !e.agent_id || e.agent_id === baseline.agent_id);
|
|
189
|
+
if (probes.length > 0) {
|
|
190
|
+
findings.push({
|
|
191
|
+
rule: 'scope-edge', severity: probes.length > 2 ? 'high' : 'medium', agent_id: baseline.agent_id,
|
|
192
|
+
receipt_hashes: [], targets: [],
|
|
193
|
+
observed: `${probes.length} rejected write(s): ${probes.map((p) => p.error).filter(Boolean).slice(0, 3).join('; ')}`,
|
|
194
|
+
expected: 'no rejected writes', ts: probes[probes.length - 1]?.ts ?? new Date(0).toISOString(),
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// 3. rate-spike — actions per hour vs baseline (milli-units; +1000 keeps std=0 from firing on +1)
|
|
199
|
+
if (baseline.sample_size >= minSample) {
|
|
200
|
+
const buckets = new Map<string, Scanned[]>();
|
|
201
|
+
for (const r of mine) buckets.set(r.ts.slice(0, 13), [...(buckets.get(r.ts.slice(0, 13)) ?? []), r]);
|
|
202
|
+
const z = opts.rateZ ?? 3;
|
|
203
|
+
for (const [hour, rs] of buckets) {
|
|
204
|
+
if (rs.length * 1000 > baseline.rate.mean_milli + z * (baseline.rate.std_milli + 1000)) {
|
|
205
|
+
findings.push(finding('rate-spike', 'high', baseline.agent_id, rs,
|
|
206
|
+
`${rs.length} actions in hour ${hour}`,
|
|
207
|
+
`~${(baseline.rate.mean_milli / 1000).toFixed(1)}/h (σ ${(baseline.rate.std_milli / 1000).toFixed(1)})`));
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// 4. intent-gap — the agent normally brackets actions with intents, this window doesn't
|
|
213
|
+
if (baseline.intent_milli >= 800 && mine.length >= 5) {
|
|
214
|
+
const intents = mine.filter((r) => r.action === 'action_intent').length;
|
|
215
|
+
const actions = mine.length - intents;
|
|
216
|
+
const ratioMilli = actions > 0 ? Math.round((intents / actions) * 1000) : 1000;
|
|
217
|
+
if (ratioMilli < baseline.intent_milli / 2) {
|
|
218
|
+
findings.push(finding('intent-gap', 'high', baseline.agent_id, mine.filter((r) => r.action !== 'action_intent'),
|
|
219
|
+
`intent ratio ${(ratioMilli / 1000).toFixed(2)} this window`,
|
|
220
|
+
`~${(baseline.intent_milli / 1000).toFixed(2)} (agent normally declares intent)`));
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// 5. sequence — ordered target patterns within a window (default: the exfil shape)
|
|
225
|
+
for (const rule of opts.sequences ?? [EXFIL_SEQUENCE]) {
|
|
226
|
+
let step = 0;
|
|
227
|
+
let startMs = 0;
|
|
228
|
+
const evidence: Scanned[] = [];
|
|
229
|
+
for (const r of mine) {
|
|
230
|
+
if (rule.steps[step]!.test(r.target)) {
|
|
231
|
+
if (step === 0) startMs = Date.parse(r.ts);
|
|
232
|
+
if (Date.parse(r.ts) - startMs <= rule.windowMs) {
|
|
233
|
+
evidence.push(r);
|
|
234
|
+
step += 1;
|
|
235
|
+
if (step === rule.steps.length) {
|
|
236
|
+
findings.push(finding(`sequence:${rule.name}`, 'high', baseline.agent_id, [...evidence],
|
|
237
|
+
evidence.map((e) => e.target).join(' → '), `no ${rule.name} sequence`));
|
|
238
|
+
step = 0;
|
|
239
|
+
evidence.length = 0;
|
|
240
|
+
}
|
|
241
|
+
} else {
|
|
242
|
+
step = 0;
|
|
243
|
+
evidence.length = 0;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// 6. off-hours — activity in hours the baseline says are silent
|
|
250
|
+
if (baseline.sample_size >= minSample) {
|
|
251
|
+
const silent = mine.filter((r) => (baseline.active_hours[hourOf(r.ts)] ?? 0) === 0);
|
|
252
|
+
if (silent.length > 0) {
|
|
253
|
+
findings.push(finding('off-hours', 'medium', baseline.agent_id, silent,
|
|
254
|
+
`${silent.length} action(s) at UTC hour(s) [${[...new Set(silent.map((r) => hourOf(r.ts)))].join(',')}]`,
|
|
255
|
+
'activity only in learned active hours'));
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// 7. wall-crossing — operator mode only (raw payloads pre-hash)
|
|
260
|
+
if (opts.payloadOf && opts.checkContent) {
|
|
261
|
+
for (const r of mine) {
|
|
262
|
+
const text = opts.payloadOf(r);
|
|
263
|
+
if (text === undefined) continue;
|
|
264
|
+
const violations = opts.checkContent(text, r);
|
|
265
|
+
if (violations.length > 0) {
|
|
266
|
+
findings.push(finding('wall-crossing', 'high', baseline.agent_id, [r],
|
|
267
|
+
`content violations: ${violations.join(', ')}`, 'no boundary-crossing content'));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return findings;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// ---------------------------------------------------------------------------
|
|
276
|
+
// The loop — feed + injected responses. The sentinel NEVER holds authority keys.
|
|
277
|
+
// ---------------------------------------------------------------------------
|
|
278
|
+
|
|
279
|
+
export interface WatcherOptions {
|
|
280
|
+
server: string;
|
|
281
|
+
fetchImpl?: FetchLike;
|
|
282
|
+
/** Baseline per watched agent DID. */
|
|
283
|
+
baselines: Record<string, Baseline>;
|
|
284
|
+
onFinding: (finding: Finding) => void | Promise<void>;
|
|
285
|
+
scan?: ScanOptions;
|
|
286
|
+
/** Page size for /v1/recent (server caps at 100). */
|
|
287
|
+
limit?: number;
|
|
288
|
+
/** Resume from a persisted cursor — the highest ledger index already processed. */
|
|
289
|
+
cursor?: number;
|
|
290
|
+
/**
|
|
291
|
+
* Rolling window of receipts kept per agent, so **windowed detectors** (`sequence`,
|
|
292
|
+
* `rate-spike`, `intent-gap`) see across polls. Without this a 3-step exfil arriving
|
|
293
|
+
* over three 60s polls would never be detected — each poll would see one step.
|
|
294
|
+
* Default 2h (covers the 30-min exfil window + hourly rate buckets).
|
|
295
|
+
*/
|
|
296
|
+
windowMs?: number;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export interface Watcher {
|
|
300
|
+
/** One poll: fetch new receipts, scan the rolling window, dispatch *new* findings. */
|
|
301
|
+
tick(): Promise<Finding[]>;
|
|
302
|
+
/** Highest ledger index processed — **persist this** and pass back as `cursor`. */
|
|
303
|
+
cursor(): number;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Stable identity of a finding, so the same one isn't re-alerted on every poll. */
|
|
307
|
+
function fingerprint(f: Finding): string {
|
|
308
|
+
return `${f.rule}|${[...f.receipt_hashes].sort().join(',')}|${f.ts}`;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Ledger-mode watcher over `GET /v1/recent`. Call `tick()` on your own schedule.
|
|
313
|
+
*
|
|
314
|
+
* Keeps a rolling per-agent window (see `windowMs`) so windowed detectors work across
|
|
315
|
+
* polls, and de-duplicates findings so a receipt already alerted on isn't re-alerted.
|
|
316
|
+
*
|
|
317
|
+
* **Limit:** `/v1/recent` is a *global* feed capped at 100 by the server. On a busy
|
|
318
|
+
* ledger, receipts can be missed between polls (the cursor jumps). For production, drive
|
|
319
|
+
* `scan` from `receipt.recorded` webhooks (`@zanii/webhooks`) instead of polling.
|
|
320
|
+
*/
|
|
321
|
+
export function createWatcher(opts: WatcherOptions): Watcher {
|
|
322
|
+
const fetchImpl = opts.fetchImpl ?? ((u: string, i?: RequestInit) => fetch(u, i));
|
|
323
|
+
const server = opts.server.replace(/\/$/, '');
|
|
324
|
+
const windowMs = opts.windowMs ?? 2 * 60 * 60_000;
|
|
325
|
+
let cursor = opts.cursor ?? -1;
|
|
326
|
+
const buffers: Record<string, Scanned[]> = {};
|
|
327
|
+
const seen = new Set<string>();
|
|
328
|
+
|
|
329
|
+
return {
|
|
330
|
+
cursor: () => cursor,
|
|
331
|
+
async tick(): Promise<Finding[]> {
|
|
332
|
+
const res = await fetchImpl(`${server}/v1/recent?limit=${opts.limit ?? 100}`);
|
|
333
|
+
if (!res.ok) throw new Error(`recent fetch failed: HTTP ${res.status}`);
|
|
334
|
+
const body = (await res.json()) as { receipts: Array<{ receipt: Receipt; hash: string; index: number }> };
|
|
335
|
+
const fresh = body.receipts.filter((r) => r.index > cursor);
|
|
336
|
+
for (const r of fresh) cursor = Math.max(cursor, r.index);
|
|
337
|
+
|
|
338
|
+
const all: Finding[] = [];
|
|
339
|
+
for (const [did, baseline] of Object.entries(opts.baselines)) {
|
|
340
|
+
const mine = fresh.filter((r) => r.receipt.agent_id === did).map((r) => ({ ...r.receipt, hash: r.hash }));
|
|
341
|
+
if (mine.length === 0) continue;
|
|
342
|
+
|
|
343
|
+
// Rolling window: append, then trim to `windowMs` behind the newest receipt.
|
|
344
|
+
const buf = [...(buffers[did] ?? []), ...mine].sort((a, b) => a.ts.localeCompare(b.ts));
|
|
345
|
+
const newest = Date.parse(buf[buf.length - 1]!.ts);
|
|
346
|
+
buffers[did] = buf.filter((r) => newest - Date.parse(r.ts) <= windowMs);
|
|
347
|
+
|
|
348
|
+
for (const f of scan(buffers[did]!, baseline, opts.scan)) {
|
|
349
|
+
const fp = fingerprint(f);
|
|
350
|
+
if (seen.has(fp)) continue; // already alerted — don't re-fire every poll
|
|
351
|
+
seen.add(fp);
|
|
352
|
+
all.push(f);
|
|
353
|
+
await opts.onFinding(f);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (seen.size > 5000) seen.clear(); // bounded; worst case a stale finding re-fires once
|
|
357
|
+
return all;
|
|
358
|
+
},
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* The default response: a `@zanii/policy` rule turning the flagged prefixes into a
|
|
364
|
+
* `require_approval` speed bump.
|
|
365
|
+
*
|
|
366
|
+
* Returns `null` when the finding names no specific targets (e.g. `scope-edge`, which is
|
|
367
|
+
* driven by rejections, not receipts) — we will **not** silently generate a `*` rule that
|
|
368
|
+
* gates the agent's entire surface. That call belongs to a human.
|
|
369
|
+
*/
|
|
370
|
+
export function escalationRule(f: Finding): { id: string; effect: 'require_approval'; targets: string[] } | null {
|
|
371
|
+
const prefixes = [...new Set(f.targets.map((t) => `${targetPrefix(t)}.*`))];
|
|
372
|
+
if (prefixes.length === 0) return null;
|
|
373
|
+
return {
|
|
374
|
+
id: `sentinel-${f.rule.replace(/[^a-z0-9-]/gi, '-')}-${f.agent_id.slice(-8)}`,
|
|
375
|
+
effect: 'require_approval',
|
|
376
|
+
targets: prefixes,
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// ---------------------------------------------------------------------------
|
|
381
|
+
// Alerts are receipts — detection itself is tamper-evident
|
|
382
|
+
// ---------------------------------------------------------------------------
|
|
383
|
+
|
|
384
|
+
/** Record with the sentinel's OWN did:key (watcher ≠ watched): `sentinel.alert`. */
|
|
385
|
+
export function buildAlertReceipt(f: Finding, opts: { baselineHash: string }): { target: string; payload: Record<string, unknown> } {
|
|
386
|
+
return {
|
|
387
|
+
target: 'sentinel.alert',
|
|
388
|
+
payload: {
|
|
389
|
+
_zr_kind: 'sentinel',
|
|
390
|
+
v: 1,
|
|
391
|
+
rule: f.rule,
|
|
392
|
+
severity: f.severity,
|
|
393
|
+
watched_agent: f.agent_id,
|
|
394
|
+
evidence: f.receipt_hashes,
|
|
395
|
+
observed: f.observed,
|
|
396
|
+
expected: f.expected,
|
|
397
|
+
baseline_hash: opts.baselineHash,
|
|
398
|
+
ts: f.ts,
|
|
399
|
+
},
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export interface AlertCheck {
|
|
404
|
+
ok: boolean;
|
|
405
|
+
reasons: string[];
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** Structurally validate a `sentinel.alert` payload. */
|
|
409
|
+
export function verifyAlert(payload: Record<string, unknown> | undefined): AlertCheck {
|
|
410
|
+
const reasons: string[] = [];
|
|
411
|
+
const p = payload ?? {};
|
|
412
|
+
if (p._zr_kind !== 'sentinel' || p.v !== 1) reasons.push('not a sentinel alert (v1)');
|
|
413
|
+
if (!p.rule) reasons.push('missing rule');
|
|
414
|
+
if (!['low', 'medium', 'high'].includes(p.severity as string)) reasons.push('missing/invalid severity');
|
|
415
|
+
if (!p.watched_agent) reasons.push('missing watched_agent');
|
|
416
|
+
if (!Array.isArray(p.evidence)) reasons.push('missing evidence array');
|
|
417
|
+
if (typeof p.baseline_hash !== 'string' || !p.baseline_hash.startsWith('sha256:')) reasons.push('missing/invalid baseline_hash');
|
|
418
|
+
return { ok: reasons.length === 0, reasons };
|
|
419
|
+
}
|