scoped-execution-protocol 0.0.0-stage → 2.0.0-rc.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 +21 -0
- package/dist/apps.d.ts +90 -0
- package/dist/apps.js +231 -0
- package/dist/bridges/a2a.d.ts +55 -0
- package/dist/bridges/a2a.js +360 -0
- package/dist/bridges/agui.d.ts +25 -0
- package/dist/bridges/agui.js +82 -0
- package/dist/bridges/host.d.ts +36 -0
- package/dist/bridges/host.js +93 -0
- package/dist/bridges/http.d.ts +12 -0
- package/dist/bridges/http.js +55 -0
- package/dist/bridges/index.d.ts +7 -0
- package/dist/bridges/index.js +7 -0
- package/dist/bridges/mcp-proxy.d.ts +39 -0
- package/dist/bridges/mcp-proxy.js +122 -0
- package/dist/bridges/mcp.d.ts +88 -0
- package/dist/bridges/mcp.js +571 -0
- package/dist/bridges/providers.d.ts +16 -0
- package/dist/bridges/providers.js +9 -0
- package/dist/canonical.d.ts +3 -0
- package/dist/canonical.js +46 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/kernel.d.ts +416 -0
- package/dist/kernel.js +1927 -0
- package/dist/pending.d.ts +56 -0
- package/dist/pending.js +72 -0
- package/dist/policy.d.ts +20 -0
- package/dist/policy.js +100 -0
- package/dist/privacy.d.ts +52 -0
- package/dist/privacy.js +273 -0
- package/dist/state.d.ts +59 -0
- package/dist/state.js +125 -0
- package/dist/store.d.ts +59 -0
- package/dist/store.js +270 -0
- package/dist/transport.d.ts +108 -0
- package/dist/transport.js +358 -0
- package/dist/types.d.ts +167 -0
- package/dist/types.js +98 -0
- package/package.json +69 -6
- package/README.md +0 -3
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { DataPolicy, EffectClass } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Pending `REF#` handles: bounded background execution for long-running read tools.
|
|
4
|
+
*
|
|
5
|
+
* A tool only produces an outcome. Everything that touches the kernel (DAG, audit log, taint, branch
|
|
6
|
+
* policy, store, spend) happens when the owner pulls that outcome, so no event bus is needed.
|
|
7
|
+
*/
|
|
8
|
+
export type PendingStatus = "running" | "completed" | "failed" | "cancelled";
|
|
9
|
+
export declare const MAX_PENDING_RUNNING = 64;
|
|
10
|
+
export declare const MAX_PENDING_RECORDS = 1024;
|
|
11
|
+
/** Handed to a long-running tool as its third argument. */
|
|
12
|
+
export interface ToolContext {
|
|
13
|
+
/** Report completion as a finite number in [0, 1]. Free text is rejected: it would be an unscreened string in a model-visible view. */
|
|
14
|
+
progress(value: number): void;
|
|
15
|
+
/** Aborted when the call is cancelled. A late result is dropped whether or not the tool honours it. */
|
|
16
|
+
signal: AbortSignal;
|
|
17
|
+
}
|
|
18
|
+
/** Thrown from `progress()` once the handle has been cancelled. */
|
|
19
|
+
export declare class PendingCancelled extends Error {
|
|
20
|
+
constructor();
|
|
21
|
+
}
|
|
22
|
+
/** A tool controls its own error text, so only a well-formed code ever reaches a model-visible view. */
|
|
23
|
+
export declare function failureCode(error: unknown, isElicitation: boolean): string;
|
|
24
|
+
export declare class PendingCall {
|
|
25
|
+
readonly shortId: string;
|
|
26
|
+
readonly target: string;
|
|
27
|
+
readonly effect: EffectClass;
|
|
28
|
+
readonly subject: string;
|
|
29
|
+
readonly branch: string;
|
|
30
|
+
readonly policy: DataPolicy;
|
|
31
|
+
status: PendingStatus;
|
|
32
|
+
progress: number | null;
|
|
33
|
+
errorCode: string | null;
|
|
34
|
+
outcome: {
|
|
35
|
+
ok: true;
|
|
36
|
+
value: unknown;
|
|
37
|
+
} | {
|
|
38
|
+
ok: false;
|
|
39
|
+
error: unknown;
|
|
40
|
+
} | null;
|
|
41
|
+
/** Set while the outcome is being applied, so concurrent pulls share one settlement and cancel is refused. */
|
|
42
|
+
settlement: Promise<void> | null;
|
|
43
|
+
readonly abort: AbortController;
|
|
44
|
+
readonly createdAtMs: number;
|
|
45
|
+
/** Apply a result to the kernel exactly as a synchronous call would. Released when the call ends. */
|
|
46
|
+
commit: ((value: unknown) => Promise<unknown>) | null;
|
|
47
|
+
refund: (() => void) | null;
|
|
48
|
+
/** Keep the reservation and issue a receipt, for a failure that does not prove nothing was committed. Resolves to null when nothing is at stake. */
|
|
49
|
+
hold: ((code: string) => Promise<string | null>) | null;
|
|
50
|
+
constructor(shortId: string, target: string, effect: EffectClass, subject: string, branch: string, policy: DataPolicy);
|
|
51
|
+
reportProgress(value: unknown): void;
|
|
52
|
+
finish(outcome: NonNullable<PendingCall["outcome"]>): void;
|
|
53
|
+
end(status: Exclude<PendingStatus, "running">, errorCode?: string | null): void;
|
|
54
|
+
/** Model-visible status. It carries no tool output: only the target name, a number and a code. */
|
|
55
|
+
view(): Record<string, unknown>;
|
|
56
|
+
}
|
package/dist/pending.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { SXPError } from "./types.js";
|
|
2
|
+
export const MAX_PENDING_RUNNING = 64;
|
|
3
|
+
export const MAX_PENDING_RECORDS = 1024;
|
|
4
|
+
const ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
5
|
+
/** Thrown from `progress()` once the handle has been cancelled. */
|
|
6
|
+
export class PendingCancelled extends Error {
|
|
7
|
+
constructor() { super("This call was cancelled."); this.name = "PendingCancelled"; }
|
|
8
|
+
}
|
|
9
|
+
/** A tool controls its own error text, so only a well-formed code ever reaches a model-visible view. */
|
|
10
|
+
export function failureCode(error, isElicitation) {
|
|
11
|
+
if (isElicitation)
|
|
12
|
+
return "ELICITATION_UNSUPPORTED";
|
|
13
|
+
return error instanceof SXPError && typeof error.code === "string" && ERROR_CODE.test(error.code) ? error.code : "TOOL_ERROR";
|
|
14
|
+
}
|
|
15
|
+
export class PendingCall {
|
|
16
|
+
shortId;
|
|
17
|
+
target;
|
|
18
|
+
effect;
|
|
19
|
+
subject;
|
|
20
|
+
branch;
|
|
21
|
+
policy;
|
|
22
|
+
status = "running";
|
|
23
|
+
progress = null;
|
|
24
|
+
errorCode = null;
|
|
25
|
+
outcome = null;
|
|
26
|
+
/** Set while the outcome is being applied, so concurrent pulls share one settlement and cancel is refused. */
|
|
27
|
+
settlement = null;
|
|
28
|
+
abort = new AbortController();
|
|
29
|
+
createdAtMs = Date.now();
|
|
30
|
+
/** Apply a result to the kernel exactly as a synchronous call would. Released when the call ends. */
|
|
31
|
+
commit = null;
|
|
32
|
+
refund = null;
|
|
33
|
+
/** Keep the reservation and issue a receipt, for a failure that does not prove nothing was committed. Resolves to null when nothing is at stake. */
|
|
34
|
+
hold = null;
|
|
35
|
+
constructor(shortId, target, effect, subject, branch, policy) {
|
|
36
|
+
this.shortId = shortId;
|
|
37
|
+
this.target = target;
|
|
38
|
+
this.effect = effect;
|
|
39
|
+
this.subject = subject;
|
|
40
|
+
this.branch = branch;
|
|
41
|
+
this.policy = policy;
|
|
42
|
+
}
|
|
43
|
+
reportProgress(value) {
|
|
44
|
+
if (this.abort.signal.aborted)
|
|
45
|
+
throw new PendingCancelled();
|
|
46
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
47
|
+
throw new TypeError("progress must be a finite number between 0 and 1.");
|
|
48
|
+
this.progress = Math.round(Math.min(1, Math.max(0, value)) * 10_000) / 10_000;
|
|
49
|
+
}
|
|
50
|
+
finish(outcome) {
|
|
51
|
+
// A cancelled or settled call has already released its result, so a late one is dropped here.
|
|
52
|
+
if (this.status === "running" && this.outcome === null)
|
|
53
|
+
this.outcome = outcome;
|
|
54
|
+
}
|
|
55
|
+
end(status, errorCode = null) {
|
|
56
|
+
this.status = status;
|
|
57
|
+
this.errorCode = errorCode;
|
|
58
|
+
this.outcome = null;
|
|
59
|
+
this.commit = null;
|
|
60
|
+
this.refund = null;
|
|
61
|
+
this.hold = null;
|
|
62
|
+
}
|
|
63
|
+
/** Model-visible status. It carries no tool output: only the target name, a number and a code. */
|
|
64
|
+
view() {
|
|
65
|
+
const out = { ref: this.shortId, view: "status", status: this.status, label: this.target };
|
|
66
|
+
if (this.status === "running" && this.progress !== null)
|
|
67
|
+
out.progress = this.progress;
|
|
68
|
+
if (this.status === "failed")
|
|
69
|
+
out.error_code = this.errorCode;
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
}
|
package/dist/policy.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export declare class ResultProjection {
|
|
2
|
+
private readonly source?;
|
|
3
|
+
private readonly fields;
|
|
4
|
+
private readonly reducer;
|
|
5
|
+
readonly declassify: boolean;
|
|
6
|
+
constructor(config: unknown, opts?: {
|
|
7
|
+
declassify?: boolean;
|
|
8
|
+
});
|
|
9
|
+
/** Return only declared, validated fields. Errors contain no result values. */
|
|
10
|
+
project(result: unknown): Record<string, unknown>;
|
|
11
|
+
/** Report a policy decision without disclosing data values. */
|
|
12
|
+
explain(result: unknown): {
|
|
13
|
+
allowed: true;
|
|
14
|
+
fields: string[];
|
|
15
|
+
} | {
|
|
16
|
+
allowed: false;
|
|
17
|
+
code: string;
|
|
18
|
+
reason: string;
|
|
19
|
+
};
|
|
20
|
+
}
|
package/dist/policy.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/** Portable, deterministic projection of selected fields from a read result. */
|
|
2
|
+
import { Reducer } from "./privacy.js";
|
|
3
|
+
import { SXPError } from "./types.js";
|
|
4
|
+
const NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}(?![\s\S])/;
|
|
5
|
+
const TOKEN = "[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}(?![\\s\\S])";
|
|
6
|
+
const IS_TOKEN = new RegExp("^" + TOKEN);
|
|
7
|
+
const REJECTED = "RESULT_PROJECTION_REJECTED";
|
|
8
|
+
function object(value) {
|
|
9
|
+
if (value === null || typeof value !== "object")
|
|
10
|
+
return false;
|
|
11
|
+
const prototype = Object.getPrototypeOf(value);
|
|
12
|
+
return prototype === Object.prototype || prototype === null;
|
|
13
|
+
}
|
|
14
|
+
function name(value) {
|
|
15
|
+
return typeof value === "string" && NAME.test(value);
|
|
16
|
+
}
|
|
17
|
+
function compile(rule) {
|
|
18
|
+
if (!object(rule) || !Object.hasOwn(rule, "kind"))
|
|
19
|
+
throw new TypeError("Each projection field requires a rule object with a kind.");
|
|
20
|
+
const keys = Object.keys(rule);
|
|
21
|
+
if (rule.kind === "bool" && keys.length === 1)
|
|
22
|
+
return { kind: "bool" };
|
|
23
|
+
if (rule.kind === "identifier" && keys.length === 1)
|
|
24
|
+
return { kind: "regex", pattern: TOKEN };
|
|
25
|
+
if (rule.kind === "int" && keys.every((key) => ["kind", "minimum", "maximum"].includes(key))) {
|
|
26
|
+
const lower = Object.hasOwn(rule, "minimum") ? rule.minimum : Number.MIN_SAFE_INTEGER;
|
|
27
|
+
const upper = Object.hasOwn(rule, "maximum") ? rule.maximum : Number.MAX_SAFE_INTEGER;
|
|
28
|
+
if (typeof lower === "number" && typeof upper === "number" &&
|
|
29
|
+
Number.isSafeInteger(lower) && Number.isSafeInteger(upper) && lower <= upper) {
|
|
30
|
+
return { kind: "int", minValue: lower, maxValue: upper };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (rule.kind === "enum" && keys.length === 2 && Object.hasOwn(rule, "allowed")) {
|
|
34
|
+
const values = rule.allowed;
|
|
35
|
+
if (Array.isArray(values) && values.length > 0 &&
|
|
36
|
+
[...values].every((value) => typeof value === "string" && IS_TOKEN.test(value))) {
|
|
37
|
+
return { kind: "enum", allowed: [...values] };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
throw new TypeError("Invalid projection field rule.");
|
|
41
|
+
}
|
|
42
|
+
export class ResultProjection {
|
|
43
|
+
source;
|
|
44
|
+
fields;
|
|
45
|
+
reducer;
|
|
46
|
+
declassify;
|
|
47
|
+
constructor(config, opts) {
|
|
48
|
+
this.declassify = opts?.declassify === true;
|
|
49
|
+
if (!object(config) || Object.keys(config).some((key) => !["version", "source", "fields"].includes(key))) {
|
|
50
|
+
throw new TypeError("Expected a version 1 projection object.");
|
|
51
|
+
}
|
|
52
|
+
if (!Object.hasOwn(config, "version") || config.version !== 1) {
|
|
53
|
+
throw new TypeError("Unsupported result projection version.");
|
|
54
|
+
}
|
|
55
|
+
if (Object.hasOwn(config, "source")) {
|
|
56
|
+
if (!name(config.source))
|
|
57
|
+
throw new TypeError("Projection source must be a field name.");
|
|
58
|
+
this.source = config.source;
|
|
59
|
+
}
|
|
60
|
+
const fields = config.fields;
|
|
61
|
+
if (!Object.hasOwn(config, "fields") || !object(fields) || !Object.keys(fields).length || !Object.keys(fields).every(name)) {
|
|
62
|
+
throw new TypeError("Projection fields must be a nonempty object with valid names.");
|
|
63
|
+
}
|
|
64
|
+
this.fields = Object.keys(fields).sort();
|
|
65
|
+
this.reducer = new Reducer({ schema: Object.fromEntries(this.fields.map((key) => [key, compile(fields[key])])) });
|
|
66
|
+
}
|
|
67
|
+
/** Return only declared, validated fields. Errors contain no result values. */
|
|
68
|
+
project(result) {
|
|
69
|
+
if (this.source !== undefined) {
|
|
70
|
+
result = object(result) ? Object.getOwnPropertyDescriptor(result, this.source)?.value : undefined;
|
|
71
|
+
}
|
|
72
|
+
if (!object(result) || this.fields.some((key) => !Object.hasOwn(result, key))) {
|
|
73
|
+
throw new SXPError(REJECTED, "Read result is missing the required projection fields.");
|
|
74
|
+
}
|
|
75
|
+
const selected = Object.fromEntries(this.fields.map((key) => {
|
|
76
|
+
const value = Object.getOwnPropertyDescriptor(result, key)?.value;
|
|
77
|
+
return [key, Object.is(value, -0) ? 0 : value];
|
|
78
|
+
}));
|
|
79
|
+
try {
|
|
80
|
+
return this.reducer.extract(selected, (value) => value);
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (!(error instanceof SXPError))
|
|
84
|
+
throw error;
|
|
85
|
+
throw new SXPError(REJECTED, "Read result did not match the declared field rules.");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** Report a policy decision without disclosing data values. */
|
|
89
|
+
explain(result) {
|
|
90
|
+
try {
|
|
91
|
+
this.project(result);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (!(error instanceof SXPError))
|
|
95
|
+
throw error;
|
|
96
|
+
return { allowed: false, code: error.code, reason: error.message };
|
|
97
|
+
}
|
|
98
|
+
return { allowed: true, fields: [...this.fields] };
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type Clearance, type DataClassification, type DataPolicy } from "./types.js";
|
|
2
|
+
export declare const DEFAULT_CLEARANCE: Clearance;
|
|
3
|
+
export declare const DEFAULT_POLICY: DataPolicy;
|
|
4
|
+
export declare function maskPii(value: unknown, fields: Set<string>): unknown;
|
|
5
|
+
export declare function intersectGrants(left: string[], right: string[]): string[];
|
|
6
|
+
export declare function intersectClearance(left: Clearance, right: Clearance): Clearance;
|
|
7
|
+
export interface FieldRule {
|
|
8
|
+
kind: "bool" | "int" | "float" | "enum" | "regex";
|
|
9
|
+
allowed?: unknown[];
|
|
10
|
+
pattern?: string;
|
|
11
|
+
minValue?: number;
|
|
12
|
+
maxValue?: number;
|
|
13
|
+
maxLength?: number;
|
|
14
|
+
}
|
|
15
|
+
export interface VerifiedSpan {
|
|
16
|
+
field: string;
|
|
17
|
+
start: number;
|
|
18
|
+
end: number;
|
|
19
|
+
verbatim: string;
|
|
20
|
+
value: unknown;
|
|
21
|
+
}
|
|
22
|
+
export declare function policyRegions(policy: DataPolicy): string[];
|
|
23
|
+
export declare function mergePolicyWatermark(a: DataPolicy, b: DataPolicy): DataPolicy;
|
|
24
|
+
export declare function checkClearance(clearance: Clearance, policy: DataPolicy, contextLabel?: string, declaredPurpose?: string): void;
|
|
25
|
+
export declare function canAccessPolicy(clearance: Clearance, policy: DataPolicy, declaredPurpose?: string): boolean;
|
|
26
|
+
export declare function attenuateClearance(parent: Clearance, child: Partial<Clearance>): Clearance;
|
|
27
|
+
export declare function scrubPiiText(text: string): string;
|
|
28
|
+
/** Unified deterministic boundary sanitizer (extract, span-grounded extractSpans, redact, attest). */
|
|
29
|
+
export declare class Reducer {
|
|
30
|
+
private readonly schema;
|
|
31
|
+
private readonly dropFields;
|
|
32
|
+
private readonly maskFields;
|
|
33
|
+
private readonly targetClassification;
|
|
34
|
+
private readonly targetResidency;
|
|
35
|
+
constructor(opts?: {
|
|
36
|
+
schema?: Record<string, FieldRule>;
|
|
37
|
+
dropFields?: string[];
|
|
38
|
+
maskFields?: string[];
|
|
39
|
+
targetClassification?: DataClassification;
|
|
40
|
+
targetResidency?: string | null;
|
|
41
|
+
});
|
|
42
|
+
extract(raw: unknown, extractor: (v: unknown) => Record<string, unknown>): Record<string, unknown>;
|
|
43
|
+
extractSpans(sourceText: string, spanExtractor: (text: string) => Record<string, [number, number] | [number, number, unknown]>): {
|
|
44
|
+
data: Record<string, unknown>;
|
|
45
|
+
spans: VerifiedSpan[];
|
|
46
|
+
};
|
|
47
|
+
redact(raw: unknown, sourcePolicy?: DataPolicy): {
|
|
48
|
+
data: unknown;
|
|
49
|
+
policy: DataPolicy;
|
|
50
|
+
};
|
|
51
|
+
static attest(raw: unknown, predicateName: string, fn: (v: unknown) => boolean): Promise<Record<string, unknown>>;
|
|
52
|
+
}
|
package/dist/privacy.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { contentHash } from "./canonical.js";
|
|
2
|
+
import { CLASSIFICATION_RANK, SXPError, } from "./types.js";
|
|
3
|
+
export const DEFAULT_CLEARANCE = {
|
|
4
|
+
max_classification: "restricted",
|
|
5
|
+
allowed_residencies: ["*"],
|
|
6
|
+
allowed_purposes: ["*"],
|
|
7
|
+
};
|
|
8
|
+
export const DEFAULT_POLICY = {
|
|
9
|
+
classification: "internal",
|
|
10
|
+
residency: null,
|
|
11
|
+
allowed_purposes: [],
|
|
12
|
+
ephemeral: false,
|
|
13
|
+
ttl_ms: null,
|
|
14
|
+
pii_fields: [],
|
|
15
|
+
};
|
|
16
|
+
export function maskPii(value, fields) {
|
|
17
|
+
if (Array.isArray(value))
|
|
18
|
+
return value.map((item) => maskPii(item, fields));
|
|
19
|
+
if (value !== null && typeof value === "object") {
|
|
20
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [
|
|
21
|
+
key, fields.has(key) ? "[PII_REDACTED]" : maskPii(item, fields),
|
|
22
|
+
]));
|
|
23
|
+
}
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
export function intersectGrants(left, right) {
|
|
27
|
+
if (left.includes("*"))
|
|
28
|
+
return [...new Set(right)].sort();
|
|
29
|
+
if (right.includes("*"))
|
|
30
|
+
return [...new Set(left)].sort();
|
|
31
|
+
return [...new Set(left.filter((value) => right.includes(value)))].sort();
|
|
32
|
+
}
|
|
33
|
+
export function intersectClearance(left, right) {
|
|
34
|
+
return {
|
|
35
|
+
max_classification: CLASSIFICATION_RANK[left.max_classification] <= CLASSIFICATION_RANK[right.max_classification]
|
|
36
|
+
? left.max_classification : right.max_classification,
|
|
37
|
+
allowed_residencies: intersectGrants(left.allowed_residencies, right.allowed_residencies),
|
|
38
|
+
allowed_purposes: intersectGrants(left.allowed_purposes, right.allowed_purposes),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export function policyRegions(policy) {
|
|
42
|
+
const legacy = policy.residency?.startsWith("conflict:")
|
|
43
|
+
? policy.residency.slice(9).split("+") : (policy.residency ? [policy.residency] : []);
|
|
44
|
+
return [...new Set([...legacy, ...(policy.residencies ?? [])])].sort();
|
|
45
|
+
}
|
|
46
|
+
export function mergePolicyWatermark(a, b) {
|
|
47
|
+
const classification = CLASSIFICATION_RANK[a.classification] >= CLASSIFICATION_RANK[b.classification] ? a.classification : b.classification;
|
|
48
|
+
const residencies = [...new Set([...policyRegions(a), ...policyRegions(b)])].sort();
|
|
49
|
+
const residency = residencies.length > 1 ? "conflict:" + residencies.join("+") : residencies[0] ?? null;
|
|
50
|
+
const aPurp = a.allowed_purposes ?? [];
|
|
51
|
+
const bPurp = b.allowed_purposes ?? [];
|
|
52
|
+
const allowed_purposes = aPurp.length === 0 ? [...bPurp] : bPurp.length === 0 ? [...aPurp] : (() => {
|
|
53
|
+
const common = aPurp.filter((p) => bPurp.includes(p)).sort();
|
|
54
|
+
return common.length > 0 ? common : ["__purpose_conflict__"];
|
|
55
|
+
})();
|
|
56
|
+
const pii_fields = [...new Set([...(a.pii_fields ?? []), ...(b.pii_fields ?? [])])].sort();
|
|
57
|
+
const ttl_ms = a.ttl_ms == null ? (b.ttl_ms ?? null) : b.ttl_ms == null ? a.ttl_ms : Math.min(a.ttl_ms, b.ttl_ms);
|
|
58
|
+
return { classification, residency, ...(residencies.length > 1 ? { residencies } : {}), allowed_purposes, ephemeral: Boolean(a.ephemeral || b.ephemeral), ttl_ms, pii_fields };
|
|
59
|
+
}
|
|
60
|
+
export function checkClearance(clearance, policy, contextLabel = "sink", declaredPurpose) {
|
|
61
|
+
if (CLASSIFICATION_RANK[policy.classification] > CLASSIFICATION_RANK[clearance.max_classification]) {
|
|
62
|
+
throw new SXPError("PRIVACY_VIOLATION", `Data classified '${policy.classification}' exceeds ${contextLabel} clearance '${clearance.max_classification}'.`);
|
|
63
|
+
}
|
|
64
|
+
const reqRes = policyRegions(policy);
|
|
65
|
+
if (reqRes.length > 0 && !clearance.allowed_residencies.includes("*")) {
|
|
66
|
+
const missing = reqRes.filter((r) => !clearance.allowed_residencies.includes(r));
|
|
67
|
+
if (missing.length > 0) {
|
|
68
|
+
throw new SXPError("PRIVACY_VIOLATION", `Data requires residencies [${reqRes.join(", ")}] (unpermitted: [${missing.join(", ")}]) at ${contextLabel}.`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const purposes = policy.allowed_purposes ?? [];
|
|
72
|
+
if (purposes.length > 0) {
|
|
73
|
+
if (purposes.includes("__purpose_conflict__"))
|
|
74
|
+
throw new SXPError("PRIVACY_VIOLATION", "Disjoint data purposes cannot egress.");
|
|
75
|
+
if (declaredPurpose !== undefined && !purposes.includes(declaredPurpose)) {
|
|
76
|
+
throw new SXPError("PRIVACY_VIOLATION", `Unauthorized purpose '${declaredPurpose}'.`);
|
|
77
|
+
}
|
|
78
|
+
else if (declaredPurpose === undefined && !clearance.allowed_purposes.includes("*") && !clearance.allowed_purposes.some((p) => purposes.includes(p))) {
|
|
79
|
+
throw new SXPError("PRIVACY_VIOLATION", `Data purposes do not overlap ${contextLabel} allowed_purposes.`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export function canAccessPolicy(clearance, policy, declaredPurpose) {
|
|
84
|
+
try {
|
|
85
|
+
checkClearance(clearance, policy, "check", declaredPurpose);
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export function attenuateClearance(parent, child) {
|
|
93
|
+
const max_classification = child.max_classification ?? parent.max_classification;
|
|
94
|
+
if (CLASSIFICATION_RANK[max_classification] > CLASSIFICATION_RANK[parent.max_classification]) {
|
|
95
|
+
throw new SXPError("PRIVACY_VIOLATION", "Cannot escalate clearance classification.");
|
|
96
|
+
}
|
|
97
|
+
const allowed_residencies = child.allowed_residencies ?? parent.allowed_residencies;
|
|
98
|
+
if (!parent.allowed_residencies.includes("*")) {
|
|
99
|
+
const ps = new Set(parent.allowed_residencies);
|
|
100
|
+
if (allowed_residencies.includes("*") || allowed_residencies.some((r) => !ps.has(r))) {
|
|
101
|
+
throw new SXPError("PRIVACY_VIOLATION", "Cannot widen allowed_residencies.");
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const allowed_purposes = child.allowed_purposes ?? parent.allowed_purposes;
|
|
105
|
+
if (!parent.allowed_purposes.includes("*")) {
|
|
106
|
+
const ps = new Set(parent.allowed_purposes);
|
|
107
|
+
if (allowed_purposes.includes("*") || allowed_purposes.some((p) => !ps.has(p))) {
|
|
108
|
+
throw new SXPError("PRIVACY_VIOLATION", "Cannot widen allowed_purposes.");
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return { max_classification, allowed_residencies: [...allowed_residencies], allowed_purposes: [...allowed_purposes] };
|
|
112
|
+
}
|
|
113
|
+
const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
|
|
114
|
+
const SSN_RE = /\b\d{3}-\d{2}-\d{4}\b/g;
|
|
115
|
+
export function scrubPiiText(text) {
|
|
116
|
+
return text.replace(EMAIL_RE, "[REDACTED_EMAIL]").replace(SSN_RE, "[REDACTED_SSN]");
|
|
117
|
+
}
|
|
118
|
+
function scrubValue(val, drop, mask) {
|
|
119
|
+
if (typeof val === "string")
|
|
120
|
+
return scrubPiiText(val);
|
|
121
|
+
if (Array.isArray(val))
|
|
122
|
+
return val.map((v) => scrubValue(v, drop, mask));
|
|
123
|
+
if (val !== null && typeof val === "object") {
|
|
124
|
+
const out = {};
|
|
125
|
+
for (const [k, v] of Object.entries(val)) {
|
|
126
|
+
if (!drop.has(k))
|
|
127
|
+
out[k] = mask.has(k) ? "[REDACTED]" : scrubValue(v, drop, mask);
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
return val;
|
|
132
|
+
}
|
|
133
|
+
function validateRule(name, rule, val) {
|
|
134
|
+
if (rule.kind === "bool") {
|
|
135
|
+
if (typeof val !== "boolean")
|
|
136
|
+
throw new SXPError("REDUCER_SCHEMA", `Field '${name}' must be boolean.`);
|
|
137
|
+
return val;
|
|
138
|
+
}
|
|
139
|
+
if (rule.kind === "int") {
|
|
140
|
+
if (typeof val !== "number" || !Number.isInteger(val))
|
|
141
|
+
throw new SXPError("REDUCER_SCHEMA", `Field '${name}' must be int.`);
|
|
142
|
+
if ((rule.minValue !== undefined && val < rule.minValue) || (rule.maxValue !== undefined && val > rule.maxValue))
|
|
143
|
+
throw new SXPError("REDUCER_SCHEMA", `Int out of bounds for '${name}'.`);
|
|
144
|
+
return val;
|
|
145
|
+
}
|
|
146
|
+
if (rule.kind === "float") {
|
|
147
|
+
if (typeof val !== "number" || !Number.isFinite(val))
|
|
148
|
+
throw new SXPError("REDUCER_SCHEMA", `Field '${name}' must be float.`);
|
|
149
|
+
if ((rule.minValue !== undefined && val < rule.minValue) || (rule.maxValue !== undefined && val > rule.maxValue))
|
|
150
|
+
throw new SXPError("REDUCER_SCHEMA", `Float out of bounds for '${name}'.`);
|
|
151
|
+
return val;
|
|
152
|
+
}
|
|
153
|
+
if (rule.kind === "enum") {
|
|
154
|
+
if (!rule.allowed || !rule.allowed.includes(val))
|
|
155
|
+
throw new SXPError("REDUCER_SCHEMA", `Field '${name}' not in allowed enum.`);
|
|
156
|
+
return val;
|
|
157
|
+
}
|
|
158
|
+
if (typeof val !== "string" || val.length > (rule.maxLength ?? 64) || !rule.pattern || !new RegExp(`^(?:${rule.pattern})$`).test(val)) {
|
|
159
|
+
throw new SXPError("REDUCER_SCHEMA", `Field '${name}' failed regex rule.`);
|
|
160
|
+
}
|
|
161
|
+
return val;
|
|
162
|
+
}
|
|
163
|
+
/** Unified deterministic boundary sanitizer (extract, span-grounded extractSpans, redact, attest). */
|
|
164
|
+
export class Reducer {
|
|
165
|
+
schema;
|
|
166
|
+
dropFields;
|
|
167
|
+
maskFields;
|
|
168
|
+
targetClassification;
|
|
169
|
+
targetResidency;
|
|
170
|
+
constructor(opts) {
|
|
171
|
+
this.schema = opts?.schema ?? {};
|
|
172
|
+
this.dropFields = new Set(opts?.dropFields ?? []);
|
|
173
|
+
this.maskFields = new Set(opts?.maskFields ?? []);
|
|
174
|
+
this.targetClassification = opts?.targetClassification ?? "public";
|
|
175
|
+
this.targetResidency = opts?.targetResidency ?? null;
|
|
176
|
+
}
|
|
177
|
+
extract(raw, extractor) {
|
|
178
|
+
const extracted = extractor(raw);
|
|
179
|
+
const allowed = new Set(Object.keys(this.schema));
|
|
180
|
+
for (const k of Object.keys(extracted)) {
|
|
181
|
+
if (!allowed.has(k))
|
|
182
|
+
throw new SXPError("REDUCER_SCHEMA", `Unexpected field '${k}'.`);
|
|
183
|
+
}
|
|
184
|
+
const out = {};
|
|
185
|
+
for (const [k, rule] of Object.entries(this.schema)) {
|
|
186
|
+
if (!Object.hasOwn(extracted, k))
|
|
187
|
+
throw new SXPError("REDUCER_SCHEMA", `Missing required field '${k}'.`);
|
|
188
|
+
out[k] = validateRule(k, rule, extracted[k]);
|
|
189
|
+
}
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
extractSpans(sourceText, spanExtractor) {
|
|
193
|
+
const extracted = spanExtractor(sourceText);
|
|
194
|
+
const allowed = new Set(Object.keys(this.schema));
|
|
195
|
+
for (const k of Object.keys(extracted)) {
|
|
196
|
+
if (!allowed.has(k))
|
|
197
|
+
throw new SXPError("REDUCER_SCHEMA", `Unexpected field '${k}'.`);
|
|
198
|
+
}
|
|
199
|
+
const data = {};
|
|
200
|
+
const spans = [];
|
|
201
|
+
const characters = [...sourceText];
|
|
202
|
+
for (const [field, rule] of Object.entries(this.schema)) {
|
|
203
|
+
const entry = extracted[field];
|
|
204
|
+
if (!entry)
|
|
205
|
+
throw new SXPError("REDUCER_SCHEMA", `Missing span for '${field}'.`);
|
|
206
|
+
const [start, end] = entry;
|
|
207
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end <= start || end > characters.length) {
|
|
208
|
+
throw new SXPError("SPAN_OUT_OF_BOUNDS", `Span (${start}, ${end}) out of bounds.`);
|
|
209
|
+
}
|
|
210
|
+
const verbatim = characters.slice(start, end).join("");
|
|
211
|
+
const trimmed = verbatim.trim();
|
|
212
|
+
let parsed;
|
|
213
|
+
if (rule.kind === "int") {
|
|
214
|
+
const number = trimmed.replace(/[,$\s£€]/g, "");
|
|
215
|
+
parsed = /^[+-]?\d+$/.test(number) ? Number(number) : NaN;
|
|
216
|
+
if (entry.length === 3 && entry[2] !== parsed)
|
|
217
|
+
throw new SXPError("SPAN_GROUNDING_MISMATCH", `Int mismatch for '${field}'.`);
|
|
218
|
+
}
|
|
219
|
+
else if (rule.kind === "float") {
|
|
220
|
+
const number = trimmed.replace(/[,$\s£€]/g, "");
|
|
221
|
+
parsed = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(number) ? Number(number) : NaN;
|
|
222
|
+
if (entry.length === 3 && Math.abs(Number(entry[2]) - Number(parsed)) > 1e-9)
|
|
223
|
+
throw new SXPError("SPAN_GROUNDING_MISMATCH", `Float mismatch for '${field}'.`);
|
|
224
|
+
}
|
|
225
|
+
else if (rule.kind === "bool") {
|
|
226
|
+
const low = trimmed.toLowerCase();
|
|
227
|
+
if (!["true", "false", "yes", "no", "1", "0"].includes(low))
|
|
228
|
+
throw new SXPError("SPAN_PARSE_ERROR", `Invalid bool '${verbatim}'.`);
|
|
229
|
+
parsed = ["true", "yes", "1"].includes(low);
|
|
230
|
+
if (entry.length === 3 && entry[2] !== parsed)
|
|
231
|
+
throw new SXPError("SPAN_GROUNDING_MISMATCH", `Bool mismatch for '${field}'.`);
|
|
232
|
+
}
|
|
233
|
+
else if (rule.kind === "enum") {
|
|
234
|
+
const match = (rule.allowed ?? []).find((x) => String(x).toLowerCase() === trimmed.toLowerCase());
|
|
235
|
+
if (entry.length === 3 && String(entry[2]).toLowerCase() !== trimmed.toLowerCase())
|
|
236
|
+
throw new SXPError("SPAN_GROUNDING_MISMATCH", `Enum mismatch for '${field}'.`);
|
|
237
|
+
parsed = match;
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
if (entry.length === 3 && entry[2] !== verbatim && entry[2] !== trimmed)
|
|
241
|
+
throw new SXPError("SPAN_GROUNDING_MISMATCH", `Regex mismatch for '${field}'.`);
|
|
242
|
+
parsed = trimmed;
|
|
243
|
+
}
|
|
244
|
+
const val = validateRule(field, rule, parsed);
|
|
245
|
+
data[field] = val;
|
|
246
|
+
spans.push({ field, start, end, verbatim, value: val });
|
|
247
|
+
}
|
|
248
|
+
return { data, spans };
|
|
249
|
+
}
|
|
250
|
+
redact(raw, sourcePolicy) {
|
|
251
|
+
const drops = new Set(this.dropFields);
|
|
252
|
+
for (const f of sourcePolicy?.pii_fields ?? [])
|
|
253
|
+
drops.add(f);
|
|
254
|
+
return {
|
|
255
|
+
data: scrubValue(raw, drops, this.maskFields),
|
|
256
|
+
policy: {
|
|
257
|
+
classification: this.targetClassification,
|
|
258
|
+
residency: this.targetResidency,
|
|
259
|
+
allowed_purposes: sourcePolicy?.allowed_purposes ?? [],
|
|
260
|
+
ephemeral: false,
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
static async attest(raw, predicateName, fn) {
|
|
265
|
+
return {
|
|
266
|
+
predicate: predicateName,
|
|
267
|
+
satisfied: Boolean(fn(raw)),
|
|
268
|
+
disclosure_tier: "predicate_only",
|
|
269
|
+
commitment_hash: await contentHash(raw),
|
|
270
|
+
issued_at_ms: Date.now(),
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
}
|
package/dist/state.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { SXPError } from "./types.js";
|
|
2
|
+
/** Sized so the default 300 s replay window holds about 218 envelopes a second before it fails closed. */
|
|
3
|
+
export declare const DEFAULT_MAX_NONCES = 65536;
|
|
4
|
+
/** The window is full of IDs that are still inside their TTL. Forgetting one would let it be replayed, so refuse instead. */
|
|
5
|
+
export declare function replayCapacityExceeded(): SXPError;
|
|
6
|
+
/**
|
|
7
|
+
* What replay protection needs from shared state: atomically remember a nonce for `ttlMs`.
|
|
8
|
+
*
|
|
9
|
+
* This is the replay slice of Python's `StateStore`. Python's also holds spend counters; in TypeScript those
|
|
10
|
+
* stay in the kernel (`railTotals`), so a durable spend ledger is Python-only.
|
|
11
|
+
*
|
|
12
|
+
* A store may throw `REPLAY_CAPACITY_EXCEEDED` when it cannot remember another live ID. It must never forget a live
|
|
13
|
+
* ID to make room: failing closed is the contract.
|
|
14
|
+
*/
|
|
15
|
+
export interface StateStore {
|
|
16
|
+
/** Resolves to `true` when `nonce` is new (and is now remembered until `nowMs + ttlMs`), `false` when it is already remembered. */
|
|
17
|
+
checkAndMarkNonce(nonce: string, opts: {
|
|
18
|
+
ttlMs: number;
|
|
19
|
+
nowMs: number;
|
|
20
|
+
}): boolean | Promise<boolean>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* In-process store, so several `ReplayGuard`s (or one guard and a test) can share a window. Bounded: expired IDs go
|
|
24
|
+
* first, and a store that is still full of live IDs throws `REPLAY_CAPACITY_EXCEEDED` rather than forget one.
|
|
25
|
+
*/
|
|
26
|
+
export declare class MemoryStateStore implements StateStore {
|
|
27
|
+
private readonly maxEntries;
|
|
28
|
+
private readonly seen;
|
|
29
|
+
private earliest;
|
|
30
|
+
constructor(maxEntries?: number);
|
|
31
|
+
checkAndMarkNonce(nonce: string, { ttlMs, nowMs }: {
|
|
32
|
+
ttlMs: number;
|
|
33
|
+
nowMs: number;
|
|
34
|
+
}): boolean;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Durable replay memory in a directory, one small file per nonce: it survives restarts and is shared by every
|
|
38
|
+
* process on the same host that points at the same directory. For several hosts, implement `StateStore` over a
|
|
39
|
+
* shared service instead.
|
|
40
|
+
*
|
|
41
|
+
* A nonce is claimed with an atomic hard link from a fully written staging file, so another worker can never
|
|
42
|
+
* observe a half-written record. The one remaining gap is inherent to expiry: two workers that first see the
|
|
43
|
+
* same already-expired ID at the same instant can both claim it. A freshness window (which `ReplayGuard` must
|
|
44
|
+
* cover twice over) rejects such an old envelope before it ever reaches the store.
|
|
45
|
+
*/
|
|
46
|
+
export declare class FileStateStore implements StateStore {
|
|
47
|
+
readonly directory: string;
|
|
48
|
+
private readonly opts;
|
|
49
|
+
private marks;
|
|
50
|
+
constructor(directory: string, opts?: {
|
|
51
|
+
sweepEvery?: number;
|
|
52
|
+
});
|
|
53
|
+
checkAndMarkNonce(nonce: string, { ttlMs, nowMs }: {
|
|
54
|
+
ttlMs: number;
|
|
55
|
+
nowMs: number;
|
|
56
|
+
}): Promise<boolean>;
|
|
57
|
+
/** Delete expired records and abandoned staging files; returns how many were removed. Runs periodically on its own. */
|
|
58
|
+
sweep(nowMs?: number): Promise<number>;
|
|
59
|
+
}
|