@aithorized/core 0.3.0 → 0.5.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 +95 -16
- package/dist/audit.d.ts +40 -0
- package/dist/audit.js +47 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/lifecycle/batch.d.ts +18 -0
- package/dist/lifecycle/batch.js +20 -0
- package/dist/lifecycle/preview.d.ts +41 -0
- package/dist/lifecycle/preview.js +60 -0
- package/dist/policy/browser.d.ts +4 -0
- package/dist/policy/browser.js +2 -0
- package/dist/policy/evaluate.js +34 -5
- package/dist/policy/explain.d.ts +50 -0
- package/dist/policy/explain.js +124 -0
- package/dist/policy/match.js +5 -0
- package/dist/policy/packs.d.ts +23 -0
- package/dist/policy/packs.js +230 -0
- package/dist/policy/types.d.ts +22 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -1,30 +1,109 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://aithorized.dev">
|
|
3
|
+
<img src="https://aithorized.dev/mark.svg" alt="aithorized" width="56" />
|
|
4
|
+
</a>
|
|
5
|
+
</p>
|
|
2
6
|
|
|
3
|
-
|
|
7
|
+
<h1 align="center">@aithorized/core</h1>
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
Deterministic crypto core and fail-closed policy engine for <a href="https://aithorized.dev">aithorized</a>.
|
|
11
|
+
</p>
|
|
12
|
+
|
|
13
|
+
<p align="center">
|
|
14
|
+
<a href="https://www.npmjs.com/package/@aithorized/core"><img src="https://img.shields.io/npm/v/@aithorized/core?color=10B981" alt="npm version" /></a>
|
|
15
|
+
<a href="https://github.com/JMBargueno/aithorized-oss/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-10B981" alt="MIT License" /></a>
|
|
16
|
+
<a href="https://docs.aithorized.dev"><img src="https://img.shields.io/badge/docs-docs.aithorized.dev-0EA5E9" alt="Documentation" /></a>
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
`@aithorized/core` is the deterministic heart of **aithorized**: what the SDK, MCP proxy, CLI, and hooks use to decide whether a tool call may run and to cryptographically verify signed human decisions. No network calls and no internal state. Requires **Node.js >= 20**.
|
|
22
|
+
|
|
23
|
+
> Most integrations should install [`@aithorized/sdk`](https://www.npmjs.com/package/@aithorized/sdk) instead. Use `@aithorized/core` when you want to evaluate policies offline, verify decision bundles directly, or port the protocol to another language using the test vectors.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
4
26
|
|
|
5
27
|
```bash
|
|
6
28
|
npm install @aithorized/core
|
|
7
29
|
```
|
|
8
30
|
|
|
9
|
-
|
|
31
|
+
## Subpath exports
|
|
32
|
+
|
|
33
|
+
| Import | Purpose | Browser-safe |
|
|
34
|
+
|---|---|---|
|
|
35
|
+
| `@aithorized/core` | Full crypto core, policy engine, decision-bundle verification, lifecycle & preview helpers | Node >= 20 |
|
|
36
|
+
| `@aithorized/core/policy` | Policy evaluation, matching, command analysis, and policy packs | Yes |
|
|
37
|
+
| `@aithorized/core/kill-switch` | Local pause notice helpers | Node >= 20 |
|
|
38
|
+
| `@aithorized/core/vectors` | Loaders for the `test-vectors/` fixtures | Node >= 20 |
|
|
10
39
|
|
|
11
40
|
## What is in it
|
|
12
41
|
|
|
13
|
-
- **Canonical JSON
|
|
14
|
-
- **
|
|
15
|
-
- **Policy**:
|
|
16
|
-
- **
|
|
17
|
-
- **
|
|
42
|
+
- **Canonical JSON & hashing**: RFC 8785 (`jcs`) and SHA-256 payload hashing (`payloadHash`, `feedbackHash`, `checkPayloadHash`) that every signature commits to.
|
|
43
|
+
- **Domain-separated signatures**: ECDSA P-256 (`signEcdsaP256`, `verifyEcdsaP256`, `normalizeEcdsaLowS`) for device decisions and Ed25519 (`signEd25519`, `verifyEd25519`) for policy bundles, with explicit domain tags (`DECISION_DOMAIN`, `ACTION_DOMAIN`, `HTTP_DOMAIN`, `WS_DOMAIN`, `ENROLL_DOMAIN`).
|
|
44
|
+
- **Policy engine**: `loadPolicyYaml`, `parsePolicyJson`, `evaluatePolicy`, `explainEvaluation`, `simulatePolicy`, `mergePolicies` (a merge can only make a policy stricter), and built-in `POLICY_PACKS` (`getPolicyPack`, `applyPolicyPack`).
|
|
45
|
+
- **Command analysis**: `analyzeCommand`, `splitShellSegments`, `tokenizeSegment` for inspecting shell commands before matching rules.
|
|
46
|
+
- **Verification**: `verifyDecisionBundle` and `verifyBundle` validate signed decisions and policy bundles against pinned keys and the exact canonical payload about to run.
|
|
47
|
+
- **Lifecycle & preview helpers**: `createLocalDeadline`, `awaitResolutionBeforeDeadline`, `redactForPreview`, `createUnifiedDiffPreview`, `runPreviewProviders`.
|
|
48
|
+
|
|
49
|
+
## Quick examples
|
|
50
|
+
|
|
51
|
+
### Evaluate a policy locally
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { evaluatePolicy, loadPolicyYaml } from '@aithorized/core/policy';
|
|
55
|
+
|
|
56
|
+
const doc = loadPolicyYaml(`
|
|
57
|
+
version: 1
|
|
58
|
+
defaults:
|
|
59
|
+
unmatched: require_approval
|
|
60
|
+
rules:
|
|
61
|
+
- id: allow-reads
|
|
62
|
+
match:
|
|
63
|
+
tool: "^(read_file|list_dir)$"
|
|
64
|
+
effect: allow
|
|
65
|
+
- id: guard-prod-refunds
|
|
66
|
+
match:
|
|
67
|
+
tool: "stripe.refund"
|
|
68
|
+
environment: prod
|
|
69
|
+
effect: require_approval
|
|
70
|
+
risk: high
|
|
71
|
+
`);
|
|
18
72
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
73
|
+
const result = evaluatePolicy(doc, {
|
|
74
|
+
tool: 'stripe.refund',
|
|
75
|
+
args: { charge: 'ch_1', amount: 45000 },
|
|
76
|
+
environment: 'prod'
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
console.log(result.effect); // 'require_approval'
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Verify a signed decision bundle
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { payloadHash, verifyDecisionBundle } from '@aithorized/core';
|
|
86
|
+
|
|
87
|
+
const hash = payloadHash('stripe.refund', { charge: 'ch_1', amount: 45000 });
|
|
88
|
+
const verification = verifyDecisionBundle(decisionBundle, {
|
|
89
|
+
expectedPayloadHash: hash,
|
|
90
|
+
pinnedDirectoryKeys: directoryKeys
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
if (!verification.ok) {
|
|
94
|
+
throw new Error(`Verification failed: ${verification.code}`);
|
|
95
|
+
}
|
|
96
|
+
```
|
|
25
97
|
|
|
26
98
|
## Test vectors
|
|
27
99
|
|
|
28
|
-
`test-vectors/` ships
|
|
100
|
+
`test-vectors/` ships inside the npm package: canonical JSON, payload hashes, signing inputs, policy evaluation, and bundle verification as JSON fixtures. An implementation in another language is conformant when it reproduces every vector byte for byte.
|
|
101
|
+
|
|
102
|
+
## Links
|
|
103
|
+
|
|
104
|
+
- Documentation: <https://docs.aithorized.dev>
|
|
105
|
+
- Source: <https://github.com/JMBargueno/aithorized-oss/tree/main/packages/core>
|
|
106
|
+
|
|
107
|
+
## License
|
|
29
108
|
|
|
30
|
-
MIT
|
|
109
|
+
MIT
|
package/dist/audit.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@aithorized/core/audit`: re-check an audit hash chain anywhere WebCrypto exists (a browser, Node 20+, Deno), with
|
|
3
|
+
* nothing from `node:crypto`. The rules are the backend's (docs/02 section 5):
|
|
4
|
+
*
|
|
5
|
+
* hash = "sha256:" + base64url(SHA-256(JCS({ prevHash, event })))
|
|
6
|
+
* event = { seq, ts, tenantId, type, actor?, subject?, detail? }
|
|
7
|
+
*
|
|
8
|
+
* and the first event of a tenant chains after `sha256:` + base64url(SHA-256("aithorized-audit-genesis")).
|
|
9
|
+
*/
|
|
10
|
+
export interface ChainedAuditEvent {
|
|
11
|
+
seq: number;
|
|
12
|
+
ts: string;
|
|
13
|
+
tenantId: string;
|
|
14
|
+
type: string;
|
|
15
|
+
actor?: string;
|
|
16
|
+
subject?: string;
|
|
17
|
+
detail?: Record<string, unknown>;
|
|
18
|
+
prevHash: string;
|
|
19
|
+
hash: string;
|
|
20
|
+
}
|
|
21
|
+
export interface AuditChainResult {
|
|
22
|
+
valid: boolean;
|
|
23
|
+
/** Events re-hashed before the result (all of them when valid). */
|
|
24
|
+
checked: number;
|
|
25
|
+
/** The first event whose link or hash does not match. */
|
|
26
|
+
firstBadSeq?: number;
|
|
27
|
+
/** The hash the next event must chain after: the last good event's (or the starting point). */
|
|
28
|
+
headHash: string;
|
|
29
|
+
}
|
|
30
|
+
/** The event body exactly as it was hashed at append time. */
|
|
31
|
+
export declare function auditEventBody(event: Omit<ChainedAuditEvent, 'prevHash' | 'hash'>): Record<string, unknown>;
|
|
32
|
+
/** The prevHash of a tenant's first event. */
|
|
33
|
+
export declare function auditGenesisHash(): Promise<string>;
|
|
34
|
+
/** The hash an event must carry, given the hash it chains after. */
|
|
35
|
+
export declare function auditEventHash(prevHash: string, event: Omit<ChainedAuditEvent, 'prevHash' | 'hash'>): Promise<string>;
|
|
36
|
+
/**
|
|
37
|
+
* Re-hash consecutive events of one tenant, oldest first. Starts from the genesis unless `after` gives the hash of
|
|
38
|
+
* the event just before the first one (to check a long chain page by page).
|
|
39
|
+
*/
|
|
40
|
+
export declare function verifyAuditChainAsync(events: readonly ChainedAuditEvent[], after?: string): Promise<AuditChainResult>;
|
package/dist/audit.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { jcs } from './crypto/jcs.js';
|
|
2
|
+
const GENESIS_INPUT = 'aithorized-audit-genesis';
|
|
3
|
+
/** The event body exactly as it was hashed at append time. */
|
|
4
|
+
export function auditEventBody(event) {
|
|
5
|
+
const body = { seq: event.seq, ts: event.ts, tenantId: event.tenantId, type: event.type };
|
|
6
|
+
if (event.actor !== undefined)
|
|
7
|
+
body.actor = event.actor;
|
|
8
|
+
if (event.subject !== undefined)
|
|
9
|
+
body.subject = event.subject;
|
|
10
|
+
if (event.detail !== undefined)
|
|
11
|
+
body.detail = event.detail;
|
|
12
|
+
return body;
|
|
13
|
+
}
|
|
14
|
+
/** The prevHash of a tenant's first event. */
|
|
15
|
+
export async function auditGenesisHash() {
|
|
16
|
+
return 'sha256:' + (await sha256Base64url(GENESIS_INPUT));
|
|
17
|
+
}
|
|
18
|
+
/** The hash an event must carry, given the hash it chains after. */
|
|
19
|
+
export async function auditEventHash(prevHash, event) {
|
|
20
|
+
return 'sha256:' + (await sha256Base64url(jcs({ prevHash, event: auditEventBody(event) })));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Re-hash consecutive events of one tenant, oldest first. Starts from the genesis unless `after` gives the hash of
|
|
24
|
+
* the event just before the first one (to check a long chain page by page).
|
|
25
|
+
*/
|
|
26
|
+
export async function verifyAuditChainAsync(events, after) {
|
|
27
|
+
let prev = after ?? (await auditGenesisHash());
|
|
28
|
+
let checked = 0;
|
|
29
|
+
for (const event of events) {
|
|
30
|
+
if (event.prevHash !== prev || (await auditEventHash(event.prevHash, event)) !== event.hash) {
|
|
31
|
+
return { valid: false, checked, firstBadSeq: event.seq, headHash: prev };
|
|
32
|
+
}
|
|
33
|
+
prev = event.hash;
|
|
34
|
+
checked += 1;
|
|
35
|
+
}
|
|
36
|
+
return { valid: true, checked, headHash: prev };
|
|
37
|
+
}
|
|
38
|
+
async function sha256Base64url(text) {
|
|
39
|
+
const subtle = globalThis.crypto?.subtle;
|
|
40
|
+
if (!subtle)
|
|
41
|
+
throw new Error('WebCrypto (crypto.subtle) is not available');
|
|
42
|
+
const digest = new Uint8Array(await subtle.digest('SHA-256', new TextEncoder().encode(text)));
|
|
43
|
+
let binary = '';
|
|
44
|
+
for (const byte of digest)
|
|
45
|
+
binary += String.fromCharCode(byte);
|
|
46
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
47
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -11,6 +11,10 @@ export { jwkThumbprint, publicJwkToKeyObject, privateJwkToKeyObject, ed25519Publ
|
|
|
11
11
|
export type { EcP256Jwk, Ed25519Jwk, JwkThumbprintJwk } from './crypto/jwk.js';
|
|
12
12
|
export { DECISION_DOMAIN, ACTION_DOMAIN, HTTP_DOMAIN, WS_DOMAIN, ENROLL_DOMAIN, decisionSigningInput, actionSigningInput, enrollSigningInput, wsSigningInput, refreshSigningInput, httpSigningInput, parseEcdsaDer, encodeEcdsaDer, normalizeEcdsaLowS, signEcdsaP256, verifyEcdsaP256, signEd25519, verifyEd25519 } from './crypto/sign.js';
|
|
13
13
|
export { RISK_ORDER, MIN_TTL_SECONDS, MAX_TTL_SECONDS, clampTtl, evaluatePolicy } from './policy/evaluate.js';
|
|
14
|
+
export { explainEvaluation, simulatePolicy } from './policy/explain.js';
|
|
15
|
+
export type { RuleEvaluationTrace, ExplainResult, SimulationSample, SimulationTransitionSample, SimulationTransition, SimulationSummary } from './policy/explain.js';
|
|
16
|
+
export { POLICY_PACKS, getPolicyPack, applyPolicyPack } from './policy/packs.js';
|
|
17
|
+
export type { PolicyPackId, PolicyPack } from './policy/packs.js';
|
|
14
18
|
export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './policy/match.js';
|
|
15
19
|
export { analyzeCommand, splitShellSegments, tokenizeSegment } from './policy/command-analyzer.js';
|
|
16
20
|
export type { CommandAnalysis, CommandIntent, CommandPatternSuggestion, DetectedFile, DetectedPath, DetectedTool } from './policy/command-analyzer.js';
|
|
@@ -27,5 +31,9 @@ export { verifyDecisionBundle, keyClassCanDecide, KEY_CLASSES, DIRECTORY_DOMAIN,
|
|
|
27
31
|
export type { RequestStatus, KeyClass, DeviceDirectoryKey, DeviceKeyDirectory, DecisionObject, DecisionSignature, DecisionBundle, EditableField, VerifyDecisionOptions, VerificationResult } from './lifecycle/verify.js';
|
|
28
32
|
export { redactForPreview, REDACTED_VALUE, DEFAULT_KEY_GLOBS } from './lifecycle/redact.js';
|
|
29
33
|
export type { RedactionConfig, PreviewField, RedactionResult } from './lifecycle/redact.js';
|
|
34
|
+
export { createUnifiedDiffPreview, runPreviewProviders } from './lifecycle/preview.js';
|
|
35
|
+
export type { VerifiedPreview, PreviewProvider } from './lifecycle/preview.js';
|
|
36
|
+
export { computeBatchHash, verifyBatchInclusion } from './lifecycle/batch.js';
|
|
37
|
+
export type { BatchDecision } from './lifecycle/batch.js';
|
|
30
38
|
export { CoreError, JcsError, CryptoError, PolicyError, VerificationError } from './errors.js';
|
|
31
39
|
export type { VerificationCode } from './errors.js';
|
package/dist/index.js
CHANGED
|
@@ -10,6 +10,8 @@ export { sha256, base64urlEncode, base64urlDecode, payloadHash, feedbackHash, co
|
|
|
10
10
|
export { jwkThumbprint, publicJwkToKeyObject, privateJwkToKeyObject, ed25519PublicKeyToKeyObject, ed25519PrivateKeyToKeyObject, keyObjectToJwk } from './crypto/jwk.js';
|
|
11
11
|
export { DECISION_DOMAIN, ACTION_DOMAIN, HTTP_DOMAIN, WS_DOMAIN, ENROLL_DOMAIN, decisionSigningInput, actionSigningInput, enrollSigningInput, wsSigningInput, refreshSigningInput, httpSigningInput, parseEcdsaDer, encodeEcdsaDer, normalizeEcdsaLowS, signEcdsaP256, verifyEcdsaP256, signEd25519, verifyEd25519 } from './crypto/sign.js';
|
|
12
12
|
export { RISK_ORDER, MIN_TTL_SECONDS, MAX_TTL_SECONDS, clampTtl, evaluatePolicy } from './policy/evaluate.js';
|
|
13
|
+
export { explainEvaluation, simulatePolicy } from './policy/explain.js';
|
|
14
|
+
export { POLICY_PACKS, getPolicyPack, applyPolicyPack } from './policy/packs.js';
|
|
13
15
|
export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './policy/match.js';
|
|
14
16
|
export { analyzeCommand, splitShellSegments, tokenizeSegment } from './policy/command-analyzer.js';
|
|
15
17
|
export { mergePolicies, strictnessOf } from './policy/merge.js';
|
|
@@ -19,4 +21,6 @@ export { loadPolicyYaml, parsePolicyJson, validateRules } from './policy/load.js
|
|
|
19
21
|
export { CLOCK_SKEW_ALLOWANCE_MS, MAX_CREATE_ATTEMPTS, createLocalDeadline, shouldRetryCreate, awaitResolutionBeforeDeadline } from './lifecycle/deadline.js';
|
|
20
22
|
export { verifyDecisionBundle, keyClassCanDecide, KEY_CLASSES, DIRECTORY_DOMAIN, directorySigningInput, verifyDirectory } from './lifecycle/verify.js';
|
|
21
23
|
export { redactForPreview, REDACTED_VALUE, DEFAULT_KEY_GLOBS } from './lifecycle/redact.js';
|
|
24
|
+
export { createUnifiedDiffPreview, runPreviewProviders } from './lifecycle/preview.js';
|
|
25
|
+
export { computeBatchHash, verifyBatchInclusion } from './lifecycle/batch.js';
|
|
22
26
|
export { CoreError, JcsError, CryptoError, PolicyError, VerificationError } from './errors.js';
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface BatchDecision {
|
|
2
|
+
requestIds: string[];
|
|
3
|
+
payloadHashes: string[];
|
|
4
|
+
batchHash: string;
|
|
5
|
+
decision: 'APPROVE' | 'REJECT';
|
|
6
|
+
signature: string;
|
|
7
|
+
keyId: string;
|
|
8
|
+
signerUserId?: string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Deterministic hash over a sorted list of payloadHashes for batch approvals.
|
|
12
|
+
*/
|
|
13
|
+
export declare function computeBatchHash(payloadHashes: readonly string[]): string;
|
|
14
|
+
/**
|
|
15
|
+
* Verify that a specific requestId + payloadHash belongs to a batch decision
|
|
16
|
+
* and that the batchHash matches the canonical sorted payloadHashes.
|
|
17
|
+
*/
|
|
18
|
+
export declare function verifyBatchInclusion(batch: Pick<BatchDecision, 'requestIds' | 'payloadHashes' | 'batchHash'>, requestId: string, requestPayloadHash: string): boolean;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { jcs } from '../crypto/jcs.js';
|
|
2
|
+
import { base64urlEncode, sha256 } from '../crypto/hash.js';
|
|
3
|
+
/**
|
|
4
|
+
* Deterministic hash over a sorted list of payloadHashes for batch approvals.
|
|
5
|
+
*/
|
|
6
|
+
export function computeBatchHash(payloadHashes) {
|
|
7
|
+
const canonical = jcs([...payloadHashes].sort());
|
|
8
|
+
return base64urlEncode(sha256(Buffer.from(canonical, 'utf8')));
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Verify that a specific requestId + payloadHash belongs to a batch decision
|
|
12
|
+
* and that the batchHash matches the canonical sorted payloadHashes.
|
|
13
|
+
*/
|
|
14
|
+
export function verifyBatchInclusion(batch, requestId, requestPayloadHash) {
|
|
15
|
+
if (!batch.requestIds.includes(requestId))
|
|
16
|
+
return false;
|
|
17
|
+
if (!batch.payloadHashes.includes(requestPayloadHash))
|
|
18
|
+
return false;
|
|
19
|
+
return computeBatchHash(batch.payloadHashes) === batch.batchHash;
|
|
20
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-side Verified Preview types & pluggable PreviewProvider runner.
|
|
3
|
+
* Previews are always computed deterministically outside the LLM.
|
|
4
|
+
*/
|
|
5
|
+
export type VerifiedPreview = {
|
|
6
|
+
kind: 'diff';
|
|
7
|
+
title: string;
|
|
8
|
+
filePath?: string;
|
|
9
|
+
diff: string;
|
|
10
|
+
additions: number;
|
|
11
|
+
deletions: number;
|
|
12
|
+
} | {
|
|
13
|
+
kind: 'sql_impact';
|
|
14
|
+
title: string;
|
|
15
|
+
dialect: 'postgres' | 'mysql' | 'sqlite' | 'unknown';
|
|
16
|
+
estimatedRows?: number;
|
|
17
|
+
tables?: string[];
|
|
18
|
+
statementType: string;
|
|
19
|
+
readOnlyChecked: boolean;
|
|
20
|
+
} | {
|
|
21
|
+
kind: 'resource_delta';
|
|
22
|
+
title: string;
|
|
23
|
+
create: number;
|
|
24
|
+
update: number;
|
|
25
|
+
destroy: number;
|
|
26
|
+
resources: string[];
|
|
27
|
+
} | {
|
|
28
|
+
kind: 'summary';
|
|
29
|
+
title: string;
|
|
30
|
+
items: Array<{
|
|
31
|
+
label: string;
|
|
32
|
+
value: string;
|
|
33
|
+
}>;
|
|
34
|
+
};
|
|
35
|
+
export interface PreviewProvider {
|
|
36
|
+
name: string;
|
|
37
|
+
supports: (tool: string, args: Record<string, unknown>) => boolean;
|
|
38
|
+
generate: (tool: string, args: Record<string, unknown>) => Promise<VerifiedPreview | undefined>;
|
|
39
|
+
}
|
|
40
|
+
export declare function createUnifiedDiffPreview(filePath: string, before: string, after: string): VerifiedPreview;
|
|
41
|
+
export declare function runPreviewProviders(providers: readonly PreviewProvider[], tool: string, args: Record<string, unknown>, timeoutMs?: number): Promise<VerifiedPreview | undefined>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-side Verified Preview types & pluggable PreviewProvider runner.
|
|
3
|
+
* Previews are always computed deterministically outside the LLM.
|
|
4
|
+
*/
|
|
5
|
+
export function createUnifiedDiffPreview(filePath, before, after) {
|
|
6
|
+
const beforeLines = before.split('\n');
|
|
7
|
+
const afterLines = after.split('\n');
|
|
8
|
+
const lines = [`--- a/${filePath}`, `+++ b/${filePath}`];
|
|
9
|
+
let additions = 0;
|
|
10
|
+
let deletions = 0;
|
|
11
|
+
const maxLen = Math.max(beforeLines.length, afterLines.length);
|
|
12
|
+
for (let i = 0; i < maxLen; i++) {
|
|
13
|
+
const b = beforeLines[i];
|
|
14
|
+
const a = afterLines[i];
|
|
15
|
+
if (b === a) {
|
|
16
|
+
if (b !== undefined)
|
|
17
|
+
lines.push(` ${b}`);
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
if (b !== undefined) {
|
|
21
|
+
lines.push(`-${b}`);
|
|
22
|
+
deletions += 1;
|
|
23
|
+
}
|
|
24
|
+
if (a !== undefined) {
|
|
25
|
+
lines.push(`+${a}`);
|
|
26
|
+
additions += 1;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
kind: 'diff',
|
|
32
|
+
title: `Diff: ${filePath}`,
|
|
33
|
+
filePath,
|
|
34
|
+
diff: lines.join('\n'),
|
|
35
|
+
additions,
|
|
36
|
+
deletions
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export async function runPreviewProviders(providers, tool, args, timeoutMs = 1500) {
|
|
40
|
+
for (const provider of providers) {
|
|
41
|
+
if (!provider.supports(tool, args))
|
|
42
|
+
continue;
|
|
43
|
+
try {
|
|
44
|
+
const result = await Promise.race([
|
|
45
|
+
provider.generate(tool, args),
|
|
46
|
+
new Promise((resolve) => setTimeout(() => resolve(undefined), timeoutMs))
|
|
47
|
+
]);
|
|
48
|
+
if (result)
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return {
|
|
53
|
+
kind: 'summary',
|
|
54
|
+
title: 'Preview unavailable',
|
|
55
|
+
items: [{ label: 'Provider', value: `${provider.name} failed (fail-closed)` }]
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
package/dist/policy/browser.d.ts
CHANGED
|
@@ -4,6 +4,10 @@
|
|
|
4
4
|
*/
|
|
5
5
|
export { loadPolicyYaml, parsePolicyJson, validateRules } from './load.js';
|
|
6
6
|
export { evaluatePolicy, clampTtl, MIN_TTL_SECONDS, MAX_TTL_SECONDS, RISK_ORDER } from './evaluate.js';
|
|
7
|
+
export { explainEvaluation, simulatePolicy } from './explain.js';
|
|
8
|
+
export type { RuleEvaluationTrace, ExplainResult, SimulationSample, SimulationTransitionSample, SimulationTransition, SimulationSummary } from './explain.js';
|
|
9
|
+
export { POLICY_PACKS, getPolicyPack, applyPolicyPack } from './packs.js';
|
|
10
|
+
export type { PolicyPackId, PolicyPack } from './packs.js';
|
|
7
11
|
export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './match.js';
|
|
8
12
|
export { analyzeCommand, splitShellSegments, tokenizeSegment } from './command-analyzer.js';
|
|
9
13
|
export { activePause, MAX_PAUSE_MS, PAUSE_MODES } from './pause.js';
|
package/dist/policy/browser.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
*/
|
|
5
5
|
export { loadPolicyYaml, parsePolicyJson, validateRules } from './load.js';
|
|
6
6
|
export { evaluatePolicy, clampTtl, MIN_TTL_SECONDS, MAX_TTL_SECONDS, RISK_ORDER } from './evaluate.js';
|
|
7
|
+
export { explainEvaluation, simulatePolicy } from './explain.js';
|
|
8
|
+
export { POLICY_PACKS, getPolicyPack, applyPolicyPack } from './packs.js';
|
|
7
9
|
export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './match.js';
|
|
8
10
|
export { analyzeCommand, splitShellSegments, tokenizeSegment } from './command-analyzer.js';
|
|
9
11
|
export { activePause, MAX_PAUSE_MS, PAUSE_MODES } from './pause.js';
|
package/dist/policy/evaluate.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isOpaqueCommandInput, ruleMatches } from './match.js';
|
|
1
|
+
import { isOpaqueCommandInput, resolveArgPath, ruleMatches } from './match.js';
|
|
2
2
|
import { PolicyError } from '../errors.js';
|
|
3
3
|
/**
|
|
4
4
|
* Deterministic policy evaluation (docs/02 section 3.4).
|
|
@@ -45,6 +45,15 @@ function ruleMatchesAutoRule(autoRule, input) {
|
|
|
45
45
|
if (!input.agentId || !autoRule.agentIds.includes(input.agentId))
|
|
46
46
|
return false;
|
|
47
47
|
}
|
|
48
|
+
if (autoRule.budget) {
|
|
49
|
+
const resolved = resolveArgPath(input.args ?? {}, autoRule.budget.field);
|
|
50
|
+
if (!resolved.found || typeof resolved.value !== 'number' || !Number.isFinite(resolved.value) || resolved.value < 0) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
const nextTotal = (autoRule.budget.consumed ?? 0) + resolved.value;
|
|
54
|
+
if (nextTotal > autoRule.budget.maxTotal)
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
48
57
|
// Auto-rules can never cover CRITICAL risk (enforced at the call site).
|
|
49
58
|
return true;
|
|
50
59
|
}
|
|
@@ -81,7 +90,13 @@ export function evaluatePolicy(policy, input, flags = {}) {
|
|
|
81
90
|
// DENY always beats everything below it.
|
|
82
91
|
const denyRule = firstMatchingRule(rules, (r) => r.effect === 'DENY' && ruleMatches(r.match, input));
|
|
83
92
|
if (denyRule) {
|
|
84
|
-
return {
|
|
93
|
+
return {
|
|
94
|
+
effect: 'DENY',
|
|
95
|
+
reason: 'DENY_RULE',
|
|
96
|
+
ruleId: denyRule.id,
|
|
97
|
+
degraded,
|
|
98
|
+
...(denyRule.addTaints ? { addedTaints: denyRule.addTaints } : {})
|
|
99
|
+
};
|
|
85
100
|
}
|
|
86
101
|
const approvalRule = firstMatchingRule(rules, (r) => r.effect === 'REQUIRE_APPROVAL' && ruleMatches(r.match, input));
|
|
87
102
|
if (approvalRule) {
|
|
@@ -110,16 +125,30 @@ export function evaluatePolicy(policy, input, flags = {}) {
|
|
|
110
125
|
riskLevel: risk,
|
|
111
126
|
approversRequired: approvers,
|
|
112
127
|
ttlSeconds: ttl,
|
|
113
|
-
degraded
|
|
128
|
+
degraded,
|
|
129
|
+
...(approvalRule.addTaints ? { addedTaints: approvalRule.addTaints } : {}),
|
|
130
|
+
...(approvalRule.routingGroup ? { routingGroup: approvalRule.routingGroup } : {})
|
|
114
131
|
};
|
|
115
132
|
}
|
|
116
133
|
const observeRule = firstMatchingRule(rules, (r) => r.effect === 'OBSERVE' && ruleMatches(r.match, input));
|
|
117
134
|
if (observeRule) {
|
|
118
|
-
return {
|
|
135
|
+
return {
|
|
136
|
+
effect: 'OBSERVE',
|
|
137
|
+
reason: 'OBSERVE_RULE',
|
|
138
|
+
ruleId: observeRule.id,
|
|
139
|
+
degraded,
|
|
140
|
+
...(observeRule.addTaints ? { addedTaints: observeRule.addTaints } : {})
|
|
141
|
+
};
|
|
119
142
|
}
|
|
120
143
|
const allowRule = firstMatchingRule(rules, (r) => r.effect === 'ALLOW' && ruleMatches(r.match, input, { strictAllow: true }));
|
|
121
144
|
if (allowRule) {
|
|
122
|
-
return {
|
|
145
|
+
return {
|
|
146
|
+
effect: 'ALLOW',
|
|
147
|
+
reason: 'ALLOW_RULE',
|
|
148
|
+
ruleId: allowRule.id,
|
|
149
|
+
degraded,
|
|
150
|
+
...(allowRule.addTaints ? { addedTaints: allowRule.addTaints } : {})
|
|
151
|
+
};
|
|
123
152
|
}
|
|
124
153
|
const unmatched = policy.defaults.unmatched;
|
|
125
154
|
if (unmatched === 'ALLOW') {
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type CommandAnalysis } from './command-analyzer.js';
|
|
2
|
+
import type { EffectivePolicy, Effect, EvalFlags, EvalInput, EvalResult } from './types.js';
|
|
3
|
+
export interface RuleEvaluationTrace {
|
|
4
|
+
ruleId: string;
|
|
5
|
+
name?: string;
|
|
6
|
+
effect: Effect;
|
|
7
|
+
matched: boolean;
|
|
8
|
+
reason: string;
|
|
9
|
+
}
|
|
10
|
+
export interface ExplainResult {
|
|
11
|
+
result: EvalResult;
|
|
12
|
+
commandAnalysis?: CommandAnalysis;
|
|
13
|
+
traces: RuleEvaluationTrace[];
|
|
14
|
+
autoRuleMatched?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface SimulationSample {
|
|
17
|
+
id?: string;
|
|
18
|
+
input: EvalInput;
|
|
19
|
+
flags?: EvalFlags;
|
|
20
|
+
}
|
|
21
|
+
export interface SimulationTransitionSample {
|
|
22
|
+
id?: string;
|
|
23
|
+
tool: string;
|
|
24
|
+
fromRuleId?: string;
|
|
25
|
+
toRuleId?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface SimulationTransition {
|
|
28
|
+
from: Effect;
|
|
29
|
+
to: Effect;
|
|
30
|
+
count: number;
|
|
31
|
+
samples: SimulationTransitionSample[];
|
|
32
|
+
}
|
|
33
|
+
export interface SimulationSummary {
|
|
34
|
+
total: number;
|
|
35
|
+
unchanged: number;
|
|
36
|
+
changed: number;
|
|
37
|
+
transitions: SimulationTransition[];
|
|
38
|
+
byNewEffect: Record<Effect, number>;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Pure policy explanation helper for Policy Playground and CLI `policy test`.
|
|
42
|
+
* Evaluates the policy deterministically and returns a per-rule trace plus
|
|
43
|
+
* structured command analysis when a shell command is present.
|
|
44
|
+
*/
|
|
45
|
+
export declare function explainEvaluation(policy: EffectivePolicy, input: EvalInput, flags?: EvalFlags): ExplainResult;
|
|
46
|
+
/**
|
|
47
|
+
* Compare two policies over a batch of historical or synthetic samples
|
|
48
|
+
* ("What-If Replay"). Pure and side-effect free.
|
|
49
|
+
*/
|
|
50
|
+
export declare function simulatePolicy(currentPolicy: EffectivePolicy, candidatePolicy: EffectivePolicy, samples: SimulationSample[], maxSamplesPerTransition?: number): SimulationSummary;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { analyzeCommand } from './command-analyzer.js';
|
|
2
|
+
import { evaluatePolicy } from './evaluate.js';
|
|
3
|
+
import { isOpaqueCommandInput, ruleMatches, toolMatches } from './match.js';
|
|
4
|
+
function extractCommandText(args) {
|
|
5
|
+
if (!args)
|
|
6
|
+
return undefined;
|
|
7
|
+
for (const key of ['command', 'cmd', 'script']) {
|
|
8
|
+
const val = args[key];
|
|
9
|
+
if (typeof val === 'string' && val.trim().length > 0)
|
|
10
|
+
return val;
|
|
11
|
+
}
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
function diagnoseNoMatch(match, input, strictAllow) {
|
|
15
|
+
if (!toolMatches(match.tool, input.tool)) {
|
|
16
|
+
return `tool "${input.tool}" does not match glob "${match.tool}"`;
|
|
17
|
+
}
|
|
18
|
+
if (match.agentIds && match.agentIds.length > 0) {
|
|
19
|
+
if (!input.agentId || !match.agentIds.some((g) => toolMatches(g, input.agentId))) {
|
|
20
|
+
return `agentId "${input.agentId ?? '(none)'}" not in [${match.agentIds.join(', ')}]`;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (match.environments && match.environments.length > 0) {
|
|
24
|
+
if (!input.environment || !match.environments.includes(input.environment)) {
|
|
25
|
+
return `environment "${input.environment ?? '(none)'}" not in [${match.environments.join(', ')}]`;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (strictAllow && isOpaqueCommandInput(input.args)) {
|
|
29
|
+
return 'opaque command input cannot be auto-allowed by strict ALLOW rule';
|
|
30
|
+
}
|
|
31
|
+
if (match.command) {
|
|
32
|
+
return 'command structure (tools/subcommands/intents/paths/flags) did not match';
|
|
33
|
+
}
|
|
34
|
+
if (match.args) {
|
|
35
|
+
return 'argument predicates did not match';
|
|
36
|
+
}
|
|
37
|
+
return 'rule conditions did not match';
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Pure policy explanation helper for Policy Playground and CLI `policy test`.
|
|
41
|
+
* Evaluates the policy deterministically and returns a per-rule trace plus
|
|
42
|
+
* structured command analysis when a shell command is present.
|
|
43
|
+
*/
|
|
44
|
+
export function explainEvaluation(policy, input, flags = {}) {
|
|
45
|
+
const result = evaluatePolicy(policy, input, flags);
|
|
46
|
+
const cmdText = extractCommandText(input.args);
|
|
47
|
+
const commandAnalysis = cmdText ? analyzeCommand(cmdText) : undefined;
|
|
48
|
+
const traces = [];
|
|
49
|
+
const order = ['DENY', 'REQUIRE_APPROVAL', 'OBSERVE', 'ALLOW'];
|
|
50
|
+
for (const phaseEffect of order) {
|
|
51
|
+
for (const rule of policy.rules) {
|
|
52
|
+
if (rule.effect !== phaseEffect)
|
|
53
|
+
continue;
|
|
54
|
+
const strictAllow = phaseEffect === 'ALLOW';
|
|
55
|
+
const matched = ruleMatches(rule.match, input, strictAllow ? { strictAllow: true } : undefined);
|
|
56
|
+
traces.push({
|
|
57
|
+
ruleId: rule.id,
|
|
58
|
+
...(rule.name ? { name: rule.name } : {}),
|
|
59
|
+
effect: rule.effect,
|
|
60
|
+
matched,
|
|
61
|
+
reason: matched
|
|
62
|
+
? result.ruleId === rule.id
|
|
63
|
+
? `matched and selected (${result.reason})`
|
|
64
|
+
: 'matched, shadowed by higher-precedence rule'
|
|
65
|
+
: diagnoseNoMatch(rule.match, input, strictAllow)
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
result,
|
|
71
|
+
...(commandAnalysis ? { commandAnalysis } : {}),
|
|
72
|
+
traces,
|
|
73
|
+
...(result.autoRuleId ? { autoRuleMatched: result.autoRuleId } : {})
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Compare two policies over a batch of historical or synthetic samples
|
|
78
|
+
* ("What-If Replay"). Pure and side-effect free.
|
|
79
|
+
*/
|
|
80
|
+
export function simulatePolicy(currentPolicy, candidatePolicy, samples, maxSamplesPerTransition = 5) {
|
|
81
|
+
const byNewEffect = {
|
|
82
|
+
ALLOW: 0,
|
|
83
|
+
OBSERVE: 0,
|
|
84
|
+
REQUIRE_APPROVAL: 0,
|
|
85
|
+
DENY: 0
|
|
86
|
+
};
|
|
87
|
+
const transitionMap = new Map();
|
|
88
|
+
let unchanged = 0;
|
|
89
|
+
let changed = 0;
|
|
90
|
+
for (const sample of samples) {
|
|
91
|
+
const prev = evaluatePolicy(currentPolicy, sample.input, sample.flags);
|
|
92
|
+
const next = evaluatePolicy(candidatePolicy, sample.input, sample.flags);
|
|
93
|
+
byNewEffect[next.effect] += 1;
|
|
94
|
+
if (prev.effect === next.effect) {
|
|
95
|
+
unchanged += 1;
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
changed += 1;
|
|
99
|
+
}
|
|
100
|
+
const key = `${prev.effect}->${next.effect}`;
|
|
101
|
+
let entry = transitionMap.get(key);
|
|
102
|
+
if (!entry) {
|
|
103
|
+
entry = { from: prev.effect, to: next.effect, count: 0, samples: [] };
|
|
104
|
+
transitionMap.set(key, entry);
|
|
105
|
+
}
|
|
106
|
+
entry.count += 1;
|
|
107
|
+
if (entry.samples.length < maxSamplesPerTransition) {
|
|
108
|
+
entry.samples.push({
|
|
109
|
+
...(sample.id ? { id: sample.id } : {}),
|
|
110
|
+
tool: sample.input.tool,
|
|
111
|
+
...(prev.ruleId ? { fromRuleId: prev.ruleId } : {}),
|
|
112
|
+
...(next.ruleId ? { toRuleId: next.ruleId } : {})
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const transitions = Array.from(transitionMap.values()).sort((a, b) => b.count - a.count);
|
|
117
|
+
return {
|
|
118
|
+
total: samples.length,
|
|
119
|
+
unchanged,
|
|
120
|
+
changed,
|
|
121
|
+
transitions,
|
|
122
|
+
byNewEffect
|
|
123
|
+
};
|
|
124
|
+
}
|
package/dist/policy/match.js
CHANGED
|
@@ -303,6 +303,11 @@ export function ruleMatches(match, input, options = {}) {
|
|
|
303
303
|
if (!commandMatches(match.command, args, options))
|
|
304
304
|
return false;
|
|
305
305
|
}
|
|
306
|
+
if (match.sessionTaints && match.sessionTaints.length > 0) {
|
|
307
|
+
const active = input.activeTaints ?? [];
|
|
308
|
+
if (!match.sessionTaints.some((t) => active.includes(t)))
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
306
311
|
return true;
|
|
307
312
|
}
|
|
308
313
|
/** True when `args` contains a shell command that `analyzeCommand()` flags as opaque/evasive. */
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { PolicyDocument, PolicyRule } from './types.js';
|
|
2
|
+
export type PolicyPackId = 'coding-agent' | 'devops' | 'fintech' | 'database';
|
|
3
|
+
export interface PolicyPack {
|
|
4
|
+
id: PolicyPackId;
|
|
5
|
+
name: string;
|
|
6
|
+
description: string;
|
|
7
|
+
tags: string[];
|
|
8
|
+
rules: PolicyRule[];
|
|
9
|
+
}
|
|
10
|
+
export declare const POLICY_PACKS: readonly PolicyPack[];
|
|
11
|
+
export declare function getPolicyPack(id: string): PolicyPack | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* Merge a curated PolicyPack into an existing PolicyDocument without
|
|
14
|
+
* duplicating rule IDs. In `observe` mode, enforcement rules are
|
|
15
|
+
* downgraded to `OBSERVE` for risk-free Shadow Mode onboarding.
|
|
16
|
+
*/
|
|
17
|
+
export declare function applyPolicyPack(policy: PolicyDocument, packId: PolicyPackId, options?: {
|
|
18
|
+
mode?: 'observe' | 'enforce';
|
|
19
|
+
}): {
|
|
20
|
+
policy: PolicyDocument;
|
|
21
|
+
addedRuleIds: string[];
|
|
22
|
+
skippedRuleIds: string[];
|
|
23
|
+
};
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
export const POLICY_PACKS = [
|
|
2
|
+
{
|
|
3
|
+
id: 'coding-agent',
|
|
4
|
+
name: 'Coding Agent Guardrails',
|
|
5
|
+
description: 'Protects against destructive shell deletes, force pushes, remote script piping, and secret file access.',
|
|
6
|
+
tags: ['shell', 'git', 'secrets'],
|
|
7
|
+
rules: [
|
|
8
|
+
{
|
|
9
|
+
id: 'pack-coding-deny-remote-pipe',
|
|
10
|
+
name: 'Block remote script pipe to shell',
|
|
11
|
+
description: 'Denies downloading and piping remote scripts directly into a shell interpreter.',
|
|
12
|
+
tags: ['coding-agent', 'security'],
|
|
13
|
+
match: {
|
|
14
|
+
tool: '*bash*',
|
|
15
|
+
command: { tools: ['curl', 'wget'], intents: ['network', 'exec'] }
|
|
16
|
+
},
|
|
17
|
+
effect: 'DENY'
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
id: 'pack-coding-critical-sensitive-paths',
|
|
21
|
+
name: 'Gate access to sensitive credential paths',
|
|
22
|
+
description: 'Requires human approval whenever a shell command touches .env, SSH keys, or credential files.',
|
|
23
|
+
tags: ['coding-agent', 'secrets'],
|
|
24
|
+
match: {
|
|
25
|
+
tool: '*bash*',
|
|
26
|
+
command: { sensitive: true }
|
|
27
|
+
},
|
|
28
|
+
effect: 'REQUIRE_APPROVAL',
|
|
29
|
+
riskLevel: 'CRITICAL',
|
|
30
|
+
ttlSeconds: 300
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
id: 'pack-coding-high-git-force',
|
|
34
|
+
name: 'Gate destructive git push',
|
|
35
|
+
description: 'Requires approval for git push with --force or -f.',
|
|
36
|
+
tags: ['coding-agent', 'git'],
|
|
37
|
+
match: {
|
|
38
|
+
tool: '*bash*',
|
|
39
|
+
command: { tools: ['git'], subcommands: ['push'], flags: ['--force', '-f', '--force-with-lease'] }
|
|
40
|
+
},
|
|
41
|
+
effect: 'REQUIRE_APPROVAL',
|
|
42
|
+
riskLevel: 'HIGH',
|
|
43
|
+
ttlSeconds: 300
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
id: 'pack-coding-high-fs-delete',
|
|
47
|
+
name: 'Gate recursive shell deletions',
|
|
48
|
+
description: 'Requires approval for destructive delete commands such as rm -rf.',
|
|
49
|
+
tags: ['coding-agent', 'filesystem'],
|
|
50
|
+
match: {
|
|
51
|
+
tool: '*bash*',
|
|
52
|
+
command: { intents: ['delete'], flags: ['-rf', '-fr', '--recursive', '-r'] }
|
|
53
|
+
},
|
|
54
|
+
effect: 'REQUIRE_APPROVAL',
|
|
55
|
+
riskLevel: 'HIGH',
|
|
56
|
+
ttlSeconds: 300
|
|
57
|
+
}
|
|
58
|
+
]
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
id: 'devops',
|
|
62
|
+
name: 'DevOps & Cloud Infra',
|
|
63
|
+
description: 'Gates production Terraform/Kubernetes changes, cluster deletions, and IAM/cloud mutations.',
|
|
64
|
+
tags: ['terraform', 'kubernetes', 'aws', 'prod'],
|
|
65
|
+
rules: [
|
|
66
|
+
{
|
|
67
|
+
id: 'pack-devops-critical-tf-destroy',
|
|
68
|
+
name: 'Gate Terraform destroy',
|
|
69
|
+
description: 'Requires approval before running terraform destroy.',
|
|
70
|
+
tags: ['devops', 'terraform'],
|
|
71
|
+
match: {
|
|
72
|
+
tool: '*bash*',
|
|
73
|
+
command: { tools: ['terraform', 'tofu'], subcommands: ['destroy'] }
|
|
74
|
+
},
|
|
75
|
+
effect: 'REQUIRE_APPROVAL',
|
|
76
|
+
riskLevel: 'CRITICAL',
|
|
77
|
+
ttlSeconds: 600
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
id: 'pack-devops-high-k8s-delete',
|
|
81
|
+
name: 'Gate kubectl delete',
|
|
82
|
+
description: 'Requires approval for kubectl delete operations.',
|
|
83
|
+
tags: ['devops', 'kubernetes'],
|
|
84
|
+
match: {
|
|
85
|
+
tool: '*bash*',
|
|
86
|
+
command: { tools: ['kubectl'], subcommands: ['delete'] }
|
|
87
|
+
},
|
|
88
|
+
effect: 'REQUIRE_APPROVAL',
|
|
89
|
+
riskLevel: 'HIGH',
|
|
90
|
+
ttlSeconds: 300
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
id: 'pack-devops-critical-prod-deploy',
|
|
94
|
+
name: 'Gate production deployments',
|
|
95
|
+
description: 'Requires approval for deploy tools targeting prod.',
|
|
96
|
+
tags: ['devops', 'prod'],
|
|
97
|
+
match: {
|
|
98
|
+
tool: 'deploy.*',
|
|
99
|
+
environments: ['prod', 'production']
|
|
100
|
+
},
|
|
101
|
+
effect: 'REQUIRE_APPROVAL',
|
|
102
|
+
riskLevel: 'CRITICAL',
|
|
103
|
+
ttlSeconds: 600
|
|
104
|
+
}
|
|
105
|
+
]
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
id: 'fintech',
|
|
109
|
+
name: 'Fintech & Payments',
|
|
110
|
+
description: 'Protects Stripe/payment refunds, payouts, and webhook configuration changes.',
|
|
111
|
+
tags: ['stripe', 'payments', 'refunds'],
|
|
112
|
+
rules: [
|
|
113
|
+
{
|
|
114
|
+
id: 'pack-fintech-high-refund',
|
|
115
|
+
name: 'Gate refunds over 50',
|
|
116
|
+
description: 'Requires approval for refunds with amount greater than 50.',
|
|
117
|
+
tags: ['fintech', 'stripe'],
|
|
118
|
+
match: {
|
|
119
|
+
tool: 'stripe.refund*',
|
|
120
|
+
args: { amount: { gt: 50 } }
|
|
121
|
+
},
|
|
122
|
+
effect: 'REQUIRE_APPROVAL',
|
|
123
|
+
riskLevel: 'HIGH',
|
|
124
|
+
ttlSeconds: 300
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
id: 'pack-fintech-critical-payout',
|
|
128
|
+
name: 'Gate payouts and transfers',
|
|
129
|
+
description: 'Requires approval for all payout or transfer tool calls.',
|
|
130
|
+
tags: ['fintech', 'payouts'],
|
|
131
|
+
match: {
|
|
132
|
+
tool: '*.payout*'
|
|
133
|
+
},
|
|
134
|
+
effect: 'REQUIRE_APPROVAL',
|
|
135
|
+
riskLevel: 'CRITICAL',
|
|
136
|
+
ttlSeconds: 600
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
id: 'pack-fintech-medium-webhook',
|
|
140
|
+
name: 'Gate payment webhook mutations',
|
|
141
|
+
description: 'Requires approval when modifying payment webhook endpoints.',
|
|
142
|
+
tags: ['fintech', 'webhooks'],
|
|
143
|
+
match: {
|
|
144
|
+
tool: 'stripe.webhook*'
|
|
145
|
+
},
|
|
146
|
+
effect: 'REQUIRE_APPROVAL',
|
|
147
|
+
riskLevel: 'MEDIUM',
|
|
148
|
+
ttlSeconds: 300
|
|
149
|
+
}
|
|
150
|
+
]
|
|
151
|
+
},
|
|
152
|
+
{
|
|
153
|
+
id: 'database',
|
|
154
|
+
name: 'Database Safety',
|
|
155
|
+
description: 'Prevents accidental DROP/TRUNCATE and gates production SQL writes.',
|
|
156
|
+
tags: ['sql', 'postgres', 'mysql'],
|
|
157
|
+
rules: [
|
|
158
|
+
{
|
|
159
|
+
id: 'pack-db-deny-drop-truncate',
|
|
160
|
+
name: 'Block DROP and TRUNCATE SQL statements',
|
|
161
|
+
description: 'Blocks DROP TABLE/DATABASE and TRUNCATE statements in SQL tools.',
|
|
162
|
+
tags: ['database', 'sql'],
|
|
163
|
+
match: {
|
|
164
|
+
tool: 'sql.*',
|
|
165
|
+
args: { query: { regex: '(?i)\\b(DROP|TRUNCATE)\\b' } }
|
|
166
|
+
},
|
|
167
|
+
effect: 'DENY'
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
id: 'pack-db-critical-prod-write',
|
|
171
|
+
name: 'Gate production SQL writes',
|
|
172
|
+
description: 'Requires approval for SQL write/execute calls in production.',
|
|
173
|
+
tags: ['database', 'prod'],
|
|
174
|
+
match: {
|
|
175
|
+
tool: 'sql.*',
|
|
176
|
+
environments: ['prod', 'production']
|
|
177
|
+
},
|
|
178
|
+
effect: 'REQUIRE_APPROVAL',
|
|
179
|
+
riskLevel: 'CRITICAL',
|
|
180
|
+
ttlSeconds: 300
|
|
181
|
+
}
|
|
182
|
+
]
|
|
183
|
+
}
|
|
184
|
+
];
|
|
185
|
+
export function getPolicyPack(id) {
|
|
186
|
+
return POLICY_PACKS.find((p) => p.id === id);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Merge a curated PolicyPack into an existing PolicyDocument without
|
|
190
|
+
* duplicating rule IDs. In `observe` mode, enforcement rules are
|
|
191
|
+
* downgraded to `OBSERVE` for risk-free Shadow Mode onboarding.
|
|
192
|
+
*/
|
|
193
|
+
export function applyPolicyPack(policy, packId, options = {}) {
|
|
194
|
+
const pack = getPolicyPack(packId);
|
|
195
|
+
if (!pack) {
|
|
196
|
+
throw new Error(`Unknown policy pack: ${packId}`);
|
|
197
|
+
}
|
|
198
|
+
const mode = options.mode ?? 'enforce';
|
|
199
|
+
const existingIds = new Set(policy.rules.map((r) => r.id));
|
|
200
|
+
const addedRuleIds = [];
|
|
201
|
+
const skippedRuleIds = [];
|
|
202
|
+
const newRules = [...policy.rules];
|
|
203
|
+
for (const rule of pack.rules) {
|
|
204
|
+
if (existingIds.has(rule.id)) {
|
|
205
|
+
skippedRuleIds.push(rule.id);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const materialized = mode === 'observe'
|
|
209
|
+
? {
|
|
210
|
+
id: rule.id,
|
|
211
|
+
...(rule.name ? { name: rule.name } : {}),
|
|
212
|
+
...(rule.description ? { description: rule.description } : {}),
|
|
213
|
+
...(rule.tags ? { tags: rule.tags } : {}),
|
|
214
|
+
match: rule.match,
|
|
215
|
+
effect: 'OBSERVE'
|
|
216
|
+
}
|
|
217
|
+
: { ...rule };
|
|
218
|
+
newRules.push(materialized);
|
|
219
|
+
existingIds.add(rule.id);
|
|
220
|
+
addedRuleIds.push(rule.id);
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
policy: {
|
|
224
|
+
...policy,
|
|
225
|
+
rules: newRules
|
|
226
|
+
},
|
|
227
|
+
addedRuleIds,
|
|
228
|
+
skippedRuleIds
|
|
229
|
+
};
|
|
230
|
+
}
|
package/dist/policy/types.d.ts
CHANGED
|
@@ -56,6 +56,8 @@ export interface RuleMatch {
|
|
|
56
56
|
args?: Record<string, ArgPredicate>;
|
|
57
57
|
/** Structured shell command matching using analyzeCommand(). */
|
|
58
58
|
command?: CommandMatch;
|
|
59
|
+
/** Match only when any of these session taints are active. */
|
|
60
|
+
sessionTaints?: string[];
|
|
59
61
|
}
|
|
60
62
|
export interface PolicyRule {
|
|
61
63
|
id: string;
|
|
@@ -73,6 +75,14 @@ export interface PolicyRule {
|
|
|
73
75
|
approversRequired?: number;
|
|
74
76
|
/** Default from defaults.ttlSeconds, clamped to [30, 3600]. */
|
|
75
77
|
ttlSeconds?: number;
|
|
78
|
+
/** Session taints attached when this rule matches (e.g. ["touched_secrets"]). */
|
|
79
|
+
addTaints?: string[];
|
|
80
|
+
/** Optional routing group (e.g. "dba", "devops", "leads"). */
|
|
81
|
+
routingGroup?: string;
|
|
82
|
+
/** Optional TTL percentage [10..90] after which escalation triggers. */
|
|
83
|
+
escalationAtPercent?: number;
|
|
84
|
+
/** Allow desktop WebAuthn/Passkey approval for LOW/MEDIUM rules. */
|
|
85
|
+
allowDesktopPasskey?: boolean;
|
|
76
86
|
}
|
|
77
87
|
export interface PolicyDefaults {
|
|
78
88
|
/** What unmatched calls do: ALLOW, OBSERVE (shadow) or REQUIRE_APPROVAL (strict). */
|
|
@@ -103,6 +113,12 @@ export interface AutoRule {
|
|
|
103
113
|
maxUses?: number;
|
|
104
114
|
/** Uses consumed so far (supplied by the caller; 0 by default). */
|
|
105
115
|
uses?: number;
|
|
116
|
+
/** Cumulative numeric budget over a payload argument (e.g. refund amount). */
|
|
117
|
+
budget?: {
|
|
118
|
+
field: string;
|
|
119
|
+
maxTotal: number;
|
|
120
|
+
consumed?: number;
|
|
121
|
+
};
|
|
106
122
|
}
|
|
107
123
|
export type PauseMode = 'PASSTHROUGH' | 'AUTO_APPROVE' | 'AUTO_DENY';
|
|
108
124
|
/**
|
|
@@ -154,6 +170,8 @@ export interface EvalInput {
|
|
|
154
170
|
environment?: string;
|
|
155
171
|
/** Current time in ms epoch. */
|
|
156
172
|
nowMs: number;
|
|
173
|
+
/** Active session taints for sequential rules. */
|
|
174
|
+
activeTaints?: string[];
|
|
157
175
|
}
|
|
158
176
|
export interface EvalFlags {
|
|
159
177
|
/** Tenant (or scope) Kill Switch is active. */
|
|
@@ -172,4 +190,8 @@ export interface EvalResult {
|
|
|
172
190
|
ttlSeconds?: number;
|
|
173
191
|
/** True when a degraded (stale/missing/invalid) policy was in force. */
|
|
174
192
|
degraded?: boolean;
|
|
193
|
+
/** Taints added by the matched rule. */
|
|
194
|
+
addedTaints?: string[];
|
|
195
|
+
/** Routing group from the matched rule. */
|
|
196
|
+
routingGroup?: string;
|
|
175
197
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aithorized/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Deterministic crypto core and policy engine for aithorized (JCS RFC 8785, payload hashing, domain-separated ECDSA/Ed25519 signatures, fail-closed policy evaluation).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -16,6 +16,10 @@
|
|
|
16
16
|
"types": "./dist/policy/browser.d.ts",
|
|
17
17
|
"default": "./dist/policy/browser.js"
|
|
18
18
|
},
|
|
19
|
+
"./audit": {
|
|
20
|
+
"types": "./dist/audit.d.ts",
|
|
21
|
+
"default": "./dist/audit.js"
|
|
22
|
+
},
|
|
19
23
|
"./kill-switch": {
|
|
20
24
|
"types": "./dist/kill-switch.d.ts",
|
|
21
25
|
"default": "./dist/kill-switch.js"
|