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/dist/state.js ADDED
@@ -0,0 +1,125 @@
1
+ import { sha256Hex } from "./canonical.js";
2
+ import { SXPError } from "./types.js";
3
+ /** Sized so the default 300 s replay window holds about 218 envelopes a second before it fails closed. */
4
+ export const DEFAULT_MAX_NONCES = 65_536;
5
+ /** The window is full of IDs that are still inside their TTL. Forgetting one would let it be replayed, so refuse instead. */
6
+ export function replayCapacityExceeded() {
7
+ return new SXPError("REPLAY_CAPACITY_EXCEEDED", "The replay window is full of unexpired envelope IDs.", "Retry later with a new envelope, or raise the capacity or use a shared StateStore.");
8
+ }
9
+ /**
10
+ * In-process store, so several `ReplayGuard`s (or one guard and a test) can share a window. Bounded: expired IDs go
11
+ * first, and a store that is still full of live IDs throws `REPLAY_CAPACITY_EXCEEDED` rather than forget one.
12
+ */
13
+ export class MemoryStateStore {
14
+ maxEntries;
15
+ seen = new Map();
16
+ earliest = Infinity; // a lower bound on every expiry, so a full store is not rescanned while nothing can have expired
17
+ constructor(maxEntries = DEFAULT_MAX_NONCES) {
18
+ this.maxEntries = maxEntries;
19
+ if (!Number.isSafeInteger(maxEntries) || maxEntries < 1)
20
+ throw new RangeError("maxEntries must be a positive integer.");
21
+ }
22
+ checkAndMarkNonce(nonce, { ttlMs, nowMs }) {
23
+ const expiry = this.seen.get(nonce);
24
+ if (expiry !== undefined && expiry > nowMs)
25
+ return false;
26
+ this.seen.delete(nonce); // an expired record is replaced by a young one
27
+ if (this.seen.size >= this.maxEntries) {
28
+ if (nowMs >= this.earliest) {
29
+ let next = Infinity;
30
+ for (const [id, until] of this.seen) {
31
+ if (until <= nowMs)
32
+ this.seen.delete(id);
33
+ else
34
+ next = Math.min(next, until);
35
+ }
36
+ this.earliest = next;
37
+ }
38
+ if (this.seen.size >= this.maxEntries)
39
+ throw replayCapacityExceeded();
40
+ }
41
+ this.seen.set(nonce, nowMs + ttlMs);
42
+ this.earliest = Math.min(this.earliest, nowMs + ttlMs);
43
+ return true;
44
+ }
45
+ }
46
+ function errorCode(error) {
47
+ return typeof error === "object" && error !== null ? error.code : undefined;
48
+ }
49
+ /**
50
+ * Durable replay memory in a directory, one small file per nonce: it survives restarts and is shared by every
51
+ * process on the same host that points at the same directory. For several hosts, implement `StateStore` over a
52
+ * shared service instead.
53
+ *
54
+ * A nonce is claimed with an atomic hard link from a fully written staging file, so another worker can never
55
+ * observe a half-written record. The one remaining gap is inherent to expiry: two workers that first see the
56
+ * same already-expired ID at the same instant can both claim it. A freshness window (which `ReplayGuard` must
57
+ * cover twice over) rejects such an old envelope before it ever reaches the store.
58
+ */
59
+ export class FileStateStore {
60
+ directory;
61
+ opts;
62
+ marks = 0;
63
+ constructor(directory, opts = {}) {
64
+ this.directory = directory;
65
+ this.opts = opts;
66
+ if (!directory)
67
+ throw new RangeError("A state directory is required.");
68
+ }
69
+ async checkAndMarkNonce(nonce, { ttlMs, nowMs }) {
70
+ const fs = await import("node:fs/promises");
71
+ await fs.mkdir(this.directory, { recursive: true, mode: 0o700 });
72
+ if (this.marks++ % (this.opts.sweepEvery ?? 256) === 0)
73
+ await this.sweep(nowMs);
74
+ const key = await sha256Hex(nonce); // never let a caller-chosen string become a path
75
+ const path = `${this.directory}/${key}.nonce`;
76
+ const staging = `${this.directory}/${key}.${crypto.randomUUID()}.tmp`;
77
+ await fs.writeFile(staging, String(nowMs + ttlMs), { flag: "wx" });
78
+ try {
79
+ for (let attempt = 0; attempt < 3; attempt += 1) {
80
+ try {
81
+ await fs.link(staging, path);
82
+ return true;
83
+ }
84
+ catch (error) {
85
+ if (errorCode(error) !== "EEXIST")
86
+ throw error;
87
+ }
88
+ let text;
89
+ try {
90
+ text = await fs.readFile(path, "utf8");
91
+ }
92
+ catch {
93
+ continue; // swept between the two calls: claim it on the next pass
94
+ }
95
+ const expiry = text.trim() === "" ? Number.NaN : Number(text);
96
+ if (!(expiry <= nowMs))
97
+ return false; // still remembered, or unreadable: fail closed
98
+ await fs.unlink(path).catch(() => undefined); // expired: forget it, then claim it
99
+ }
100
+ return false;
101
+ }
102
+ finally {
103
+ await fs.unlink(staging).catch(() => undefined);
104
+ }
105
+ }
106
+ /** Delete expired records and abandoned staging files; returns how many were removed. Runs periodically on its own. */
107
+ async sweep(nowMs = Date.now()) {
108
+ const fs = await import("node:fs/promises");
109
+ let removed = 0;
110
+ for (const name of await fs.readdir(this.directory).catch(() => [])) {
111
+ const path = `${this.directory}/${name}`;
112
+ if (name.endsWith(".nonce")) {
113
+ const text = await fs.readFile(path, "utf8").catch(() => "");
114
+ if (text.trim() !== "" && Number(text) <= nowMs)
115
+ removed += await fs.unlink(path).then(() => 1, () => 0);
116
+ }
117
+ else if (name.endsWith(".tmp")) {
118
+ const age = await fs.stat(path).then((s) => nowMs - s.mtimeMs, () => 0);
119
+ if (age > 60_000)
120
+ removed += await fs.unlink(path).then(() => 1, () => 0);
121
+ }
122
+ }
123
+ return removed;
124
+ }
125
+ }
@@ -0,0 +1,59 @@
1
+ import type { Clearance, DataPolicy, Provenance, RefHandle, TaintLevel } from "./types.js";
2
+ export declare function extractL0(payload: unknown, opts?: {
3
+ senderL0Hint?: string;
4
+ trustSenderHint?: boolean;
5
+ schemaKeys?: string[];
6
+ piiFields?: string[];
7
+ }): {
8
+ l0Summary: string;
9
+ l0Keys: string[];
10
+ unprojectedFields: string[];
11
+ };
12
+ export declare function buildL1View(payload: unknown, piiFields?: string[]): Record<string, unknown>;
13
+ export declare class HandleStore {
14
+ private blobs;
15
+ private handles;
16
+ private shortToFull;
17
+ private l1Cache;
18
+ private byShort;
19
+ private refShorts;
20
+ private counter;
21
+ private reservedShorts;
22
+ /** Allocate a `REF#N` alias that stays unreadable until `put({ shortId })` binds it to a real result. */
23
+ reserveShortId(): string;
24
+ /** Forget a reservation that will never be bound. The alias becomes an ordinary unknown reference. */
25
+ releaseShortId(shortId: string): void;
26
+ private refusePending;
27
+ private dropAlias;
28
+ private totalBytes;
29
+ private readonly maxBytes;
30
+ private readonly maxItems;
31
+ private readonly piiIdentityKey;
32
+ constructor(opts?: {
33
+ maxBytes?: number;
34
+ maxItems?: number;
35
+ piiIdentityKey?: Uint8Array;
36
+ });
37
+ private evictIfNeeded;
38
+ put(payload: unknown, opts?: {
39
+ label?: string;
40
+ taint?: TaintLevel;
41
+ policy?: DataPolicy;
42
+ provenance?: Provenance | null;
43
+ senderL0Hint?: string;
44
+ expiresAtMs?: number | null;
45
+ schemaKeys?: string[];
46
+ l1Override?: Record<string, unknown>;
47
+ shortId?: string;
48
+ }): Promise<RefHandle>;
49
+ getHandle(refOrShort: string): RefHandle | undefined;
50
+ inspect(refOrShort: string, view?: "l0" | "fields" | "raw", opts?: {
51
+ clearance?: Clearance;
52
+ keys?: string[];
53
+ offset?: number;
54
+ limit?: number;
55
+ }): Record<string, unknown>;
56
+ purge(refOrShort: string): boolean;
57
+ sweepExpired(nowMs?: number): string[];
58
+ allHandles(includeEphemeral?: boolean): RefHandle[];
59
+ }
package/dist/store.js ADDED
@@ -0,0 +1,270 @@
1
+ import { canonicalJson, sha256Hex } from "./canonical.js";
2
+ import { policyRegions, checkClearance, DEFAULT_POLICY, maskPii } from "./privacy.js";
3
+ import { SXPError } from "./types.js";
4
+ const MAX_L0_FIELDS = 5;
5
+ const MAX_L0_CHARS = 180;
6
+ const MAX_L1_KEYS = 64;
7
+ export function extractL0(payload, opts) {
8
+ const piiSet = new Set(opts?.piiFields ?? []);
9
+ let l0Keys = [];
10
+ let unprojectedFields = [];
11
+ let autoSummary = "";
12
+ if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
13
+ const obj = payload;
14
+ const allKeys = Object.keys(obj);
15
+ const safeKeys = allKeys.filter((k) => !piiSet.has(k));
16
+ const scalars = safeKeys.slice(0, MAX_L1_KEYS).filter((k) => {
17
+ const v = obj[k];
18
+ return (typeof v === "string" || typeof v === "number" || typeof v === "boolean") && String(v).length <= 64;
19
+ });
20
+ const chosen = opts?.schemaKeys
21
+ ? opts.schemaKeys.filter((k) => k in obj && !piiSet.has(k)).slice(0, MAX_L0_FIELDS)
22
+ : (scalars.length > 0 ? scalars : safeKeys).slice(0, MAX_L0_FIELDS);
23
+ l0Keys = chosen;
24
+ unprojectedFields = allKeys.filter((k) => !chosen.includes(k));
25
+ const parts = chosen.map((k) => {
26
+ const v = obj[k];
27
+ if (v !== null && typeof v === "object")
28
+ return `${k}=<${Array.isArray(v) ? "list" : "dict"}:${Array.isArray(v) ? v.length : Object.keys(v).length}>`;
29
+ const s = String(v).replace(/[\x00-\x1f\x7f]+/g, " ").trim();
30
+ return `${k}=${s.length <= 48 ? s : s.slice(0, 45) + "..."}`;
31
+ });
32
+ autoSummary = parts.length > 0 ? `object(${allKeys.length} keys): ${parts.join(", ")}` : `object(${allKeys.length} keys)`;
33
+ }
34
+ else if (Array.isArray(payload)) {
35
+ autoSummary = `list(${payload.length} items)`;
36
+ }
37
+ else if (typeof payload === "string") {
38
+ const clipped = payload.slice(0, MAX_L0_CHARS + 32).replace(/[\x00-\x1f\x7f]+/g, " ").trim();
39
+ autoSummary = `text(${payload.length} chars): ${clipped.length > MAX_L0_CHARS ? clipped.slice(0, MAX_L0_CHARS - 3) + "..." : clipped}`;
40
+ }
41
+ else {
42
+ autoSummary = `${typeof payload}: ${String(payload)}`;
43
+ }
44
+ return { l0Summary: opts?.trustSenderHint && opts.senderL0Hint ? opts.senderL0Hint : autoSummary, l0Keys, unprojectedFields };
45
+ }
46
+ export function buildL1View(payload, piiFields = []) {
47
+ const piiSet = new Set(piiFields);
48
+ if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
49
+ const obj = payload;
50
+ const allKeys = Object.keys(obj);
51
+ const fields = Object.fromEntries(allKeys.slice(0, MAX_L1_KEYS).map((k) => [k, piiSet.has(k) ? "[PII_REDACTED]" : obj[k]]));
52
+ return { kind: "object", key_count: allKeys.length, keys: allKeys, fields };
53
+ }
54
+ if (Array.isArray(payload))
55
+ return { kind: "list", count: payload.length, preview_items: payload.slice(0, 3) };
56
+ if (typeof payload === "string")
57
+ return { kind: "text", char_count: payload.length, head: payload.slice(0, 512) };
58
+ return { kind: typeof payload, value: payload };
59
+ }
60
+ export class HandleStore {
61
+ blobs = new Map();
62
+ handles = new Map();
63
+ shortToFull = new Map();
64
+ l1Cache = new Map();
65
+ byShort = new Map();
66
+ refShorts = new Map();
67
+ counter = 0;
68
+ reservedShorts = new Set();
69
+ /** Allocate a `REF#N` alias that stays unreadable until `put({ shortId })` binds it to a real result. */
70
+ reserveShortId() {
71
+ const shortId = `REF#${++this.counter}`;
72
+ this.reservedShorts.add(shortId);
73
+ return shortId;
74
+ }
75
+ /** Forget a reservation that will never be bound. The alias becomes an ordinary unknown reference. */
76
+ releaseShortId(shortId) {
77
+ this.reservedShorts.delete(shortId);
78
+ }
79
+ refusePending(refOrShort) {
80
+ if (this.reservedShorts.has(refOrShort))
81
+ throw new SXPError("REF_PENDING", "This reference has no result yet.", "Inspect it for status and retry once it completes.");
82
+ }
83
+ dropAlias(alias) {
84
+ this.byShort.delete(alias);
85
+ this.shortToFull.delete(alias);
86
+ this.l1Cache.delete(alias);
87
+ }
88
+ totalBytes = 0;
89
+ maxBytes;
90
+ maxItems;
91
+ piiIdentityKey;
92
+ constructor(opts) {
93
+ this.maxBytes = opts?.maxBytes ?? null;
94
+ this.maxItems = opts?.maxItems ?? null;
95
+ if (opts?.piiIdentityKey && opts.piiIdentityKey.byteLength < 32)
96
+ throw new Error("piiIdentityKey requires at least 32 bytes.");
97
+ this.piiIdentityKey = opts?.piiIdentityKey ? new Uint8Array(opts.piiIdentityKey) : crypto.getRandomValues(new Uint8Array(32));
98
+ }
99
+ evictIfNeeded() {
100
+ for (const [refId, entry] of this.blobs) {
101
+ if ((this.maxItems === null || this.blobs.size <= this.maxItems) && (this.maxBytes === null || this.totalBytes <= this.maxBytes))
102
+ break;
103
+ this.purge(refId);
104
+ }
105
+ }
106
+ async put(payload, opts) {
107
+ if (opts?.shortId !== undefined && !this.reservedShorts.has(opts.shortId)) {
108
+ throw new Error("shortId must be an alias reserved by reserveShortId().");
109
+ }
110
+ const taint = opts?.taint ?? "trusted_data";
111
+ const policy = structuredClone({ ...DEFAULT_POLICY, ...(opts?.policy ?? {}) });
112
+ const regions = policyRegions(policy);
113
+ policy.residency = regions.length > 1 ? "conflict:" + regions.join("+") : regions[0] ?? null;
114
+ if (regions.length > 1)
115
+ policy.residencies = regions;
116
+ else
117
+ delete policy.residencies;
118
+ const piiFields = new Set(policy.pii_fields ?? []);
119
+ const original = payload;
120
+ const canonical = canonicalJson(piiFields.size ? maskPii(payload, piiFields) : payload);
121
+ payload = JSON.parse(canonical);
122
+ const byteSize = new TextEncoder().encode(canonical).byteLength;
123
+ const createdAtMs = Date.now();
124
+ let expiresAtMs = opts?.expiresAtMs ?? null;
125
+ if (policy.ttl_ms != null)
126
+ expiresAtMs = Math.min(expiresAtMs ?? Infinity, createdAtMs + policy.ttl_ms);
127
+ const record = { payload, policy, taint, expires_at_ms: expiresAtMs };
128
+ const prefix = piiFields.size ? "SXP-REF/2\n" : "SXP-REF/1\n";
129
+ let recordJson;
130
+ if (piiFields.size) {
131
+ const originalBytes = new TextEncoder().encode(prefix + canonicalJson({ ...record, payload: original }));
132
+ const key = await crypto.subtle.importKey("raw", this.piiIdentityKey, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
133
+ const tag = new Uint8Array(await crypto.subtle.sign("HMAC", key, originalBytes));
134
+ const piiTag = Array.from(tag, (byte) => byte.toString(16).padStart(2, "0")).join("");
135
+ recordJson = canonicalJson({ ...record, pii_tag: piiTag });
136
+ }
137
+ else {
138
+ recordJson = canonicalJson(record);
139
+ }
140
+ const refId = `sha256:${await sha256Hex(prefix + recordJson)}`;
141
+ if (this.blobs.has(refId)) {
142
+ const existingBlob = this.blobs.get(refId);
143
+ this.blobs.delete(refId);
144
+ this.blobs.set(refId, existingBlob);
145
+ }
146
+ else {
147
+ this.blobs.set(refId, { value: payload, bytes: byteSize });
148
+ this.totalBytes += byteSize;
149
+ this.evictIfNeeded();
150
+ }
151
+ const trustHint = taint !== "untrusted_data";
152
+ const senderHint = piiFields.size ? undefined : opts?.senderL0Hint;
153
+ const l1Override = piiFields.size ? undefined : opts?.l1Override;
154
+ const { l0Summary, l0Keys, unprojectedFields } = extractL0(payload, {
155
+ senderL0Hint: senderHint, trustSenderHint: trustHint, schemaKeys: opts?.schemaKeys, piiFields: policy.pii_fields,
156
+ });
157
+ const anomalies = [];
158
+ if (unprojectedFields.length > 0 && !(l1Override && trustHint))
159
+ anomalies.push(`${unprojectedFields.length} unprojected field(s) in L1 (${unprojectedFields.slice(0, 4).join(", ")})`);
160
+ if (senderHint && !trustHint)
161
+ anomalies.push("Sender L0 summary ignored (untrusted peer); receiver extracted L0 deterministically.");
162
+ // `put` awaits above, so re-check: another caller may have bound the reservation in the meantime.
163
+ let shortId;
164
+ if (opts?.shortId !== undefined) {
165
+ if (!this.reservedShorts.delete(opts.shortId))
166
+ throw new Error("shortId must be an alias reserved by reserveShortId().");
167
+ shortId = opts.shortId;
168
+ }
169
+ else {
170
+ shortId = `REF#${++this.counter}`;
171
+ }
172
+ const handle = {
173
+ ref_id: refId, short_id: shortId, label: opts?.label ?? "artifact", taint, policy, byte_size: byteSize,
174
+ l0_summary: l0Summary, l0_keys: l0Keys, unprojected_fields: unprojectedFields, anomalies,
175
+ provenance: structuredClone(opts?.provenance ?? null), created_at_ms: createdAtMs, expires_at_ms: expiresAtMs,
176
+ };
177
+ if (!this.blobs.has(refId)) {
178
+ this.shortToFull.delete(shortId);
179
+ return handle;
180
+ }
181
+ const aliases = this.refShorts.get(refId) ?? new Set();
182
+ if (aliases.size >= 256) {
183
+ const oldest = aliases.values().next().value;
184
+ this.dropAlias(oldest);
185
+ aliases.delete(oldest);
186
+ }
187
+ aliases.add(shortId);
188
+ this.refShorts.set(refId, aliases);
189
+ this.byShort.set(shortId, handle);
190
+ this.shortToFull.set(shortId, refId);
191
+ this.handles.set(refId, handle);
192
+ if (l1Override && trustHint)
193
+ this.l1Cache.set(shortId, structuredClone(l1Override));
194
+ else
195
+ this.l1Cache.delete(refId);
196
+ return structuredClone(handle);
197
+ }
198
+ getHandle(refOrShort) {
199
+ return structuredClone(this.byShort.get(refOrShort) ?? this.handles.get(refOrShort));
200
+ }
201
+ inspect(refOrShort, view = "fields", opts) {
202
+ this.refusePending(refOrShort);
203
+ const refId = this.shortToFull.get(refOrShort) ?? refOrShort;
204
+ const handle = this.byShort.get(refOrShort) ?? this.handles.get(refId);
205
+ if (handle?.expires_at_ms != null && Date.now() > handle.expires_at_ms)
206
+ throw new Error(`REF has expired: ${refId}`);
207
+ if (handle && opts?.clearance)
208
+ checkClearance(opts.clearance, handle.policy, `inspect(${refOrShort})`);
209
+ let rawVal;
210
+ const blobEntry = this.blobs.get(refId);
211
+ if (blobEntry) {
212
+ this.blobs.delete(refId);
213
+ this.blobs.set(refId, blobEntry);
214
+ rawVal = blobEntry.value;
215
+ }
216
+ if (view === "fields") {
217
+ if (opts?.keys && rawVal !== null && typeof rawVal === "object" && !Array.isArray(rawVal)) {
218
+ const obj = rawVal;
219
+ const piiSet = new Set(handle?.policy.pii_fields ?? []);
220
+ const sliced = Object.fromEntries(opts.keys.filter((k) => Object.hasOwn(obj, k)).map((k) => [k, piiSet.has(k) ? "[PII_REDACTED]" : obj[k]]));
221
+ return { ref: handle?.short_id ?? refId, view: "l1", data: { kind: "object_slice", fields: structuredClone(sliced) } };
222
+ }
223
+ let l1 = this.l1Cache.get(handle?.short_id ?? refId);
224
+ if (!l1) {
225
+ l1 = buildL1View(rawVal, handle?.policy.pii_fields ?? []);
226
+ if (handle)
227
+ this.l1Cache.set(handle.short_id, l1);
228
+ }
229
+ return { ref: handle?.short_id ?? refId, view: "l1", data: structuredClone(l1) };
230
+ }
231
+ if (view === "raw") {
232
+ const offset = opts?.offset ?? 0;
233
+ const limit = opts?.limit;
234
+ if ((limit !== undefined || offset > 0) && (Array.isArray(rawVal) || typeof rawVal === "string")) {
235
+ return { ref: handle?.short_id ?? refId, view: "l2_chunk", offset, data: structuredClone(rawVal.slice(offset, limit === undefined ? undefined : offset + limit)) };
236
+ }
237
+ return { ref: handle?.short_id ?? refId, view: "l2", data: structuredClone(rawVal) };
238
+ }
239
+ return { view: "l0", ...structuredClone(handle ?? { ref_id: refId }) };
240
+ }
241
+ purge(refOrShort) {
242
+ const refId = this.shortToFull.get(refOrShort) ?? refOrShort;
243
+ const h = this.handles.get(refId);
244
+ for (const alias of this.refShorts.get(refId) ?? [])
245
+ this.dropAlias(alias);
246
+ this.refShorts.delete(refId);
247
+ this.handles.delete(refId);
248
+ this.l1Cache.delete(refId);
249
+ const entry = this.blobs.get(refId);
250
+ if (entry) {
251
+ this.totalBytes -= entry.bytes;
252
+ this.blobs.delete(refId);
253
+ return true;
254
+ }
255
+ return Boolean(h);
256
+ }
257
+ sweepExpired(nowMs = Date.now()) {
258
+ const purged = [];
259
+ for (const [refId, h] of this.handles) {
260
+ if ((h.expires_at_ms !== null && nowMs > h.expires_at_ms) || (h.policy.ttl_ms != null && nowMs > h.created_at_ms + h.policy.ttl_ms)) {
261
+ this.purge(refId);
262
+ purged.push(refId);
263
+ }
264
+ }
265
+ return purged;
266
+ }
267
+ allHandles(includeEphemeral = true) {
268
+ return structuredClone([...this.handles.values()].filter((h) => includeEphemeral || !h.policy.ephemeral));
269
+ }
270
+ }
@@ -0,0 +1,108 @@
1
+ import type { StateStore } from "./state.js";
2
+ import type { Clearance, CoreEnvelope, HardRail, ProfileDescriptor } from "./types.js";
3
+ export declare const CORE_PROFILE = "sxp:core/0.1";
4
+ export declare const MAX_FRAME_BYTES: number;
5
+ export declare const MAX_RAILS_CACHE_ENTRIES = 256;
6
+ /**
7
+ * Remembers envelope IDs for `ttlMs`: in memory by default (bounded by `maxEntries`), or in a `StateStore` to
8
+ * survive restarts and share the window between workers (for example `FileStateStore`).
9
+ *
10
+ * With the default memory a check is synchronous. With a store it returns whatever the store returns, so await it.
11
+ *
12
+ * It never forgets an ID that is still inside `ttlMs`. Expired IDs are dropped first; if the window is still full of
13
+ * live IDs it throws `REPLAY_CAPACITY_EXCEEDED` and records nothing, because evicting a live ID would let a captured
14
+ * envelope be replayed. The sender retries with a new envelope.
15
+ */
16
+ export declare class ReplayGuard {
17
+ private readonly maxEntries;
18
+ readonly ttlMs: number;
19
+ private readonly store?;
20
+ private seen;
21
+ constructor(opts?: {
22
+ maxEntries?: number;
23
+ ttlMs?: number;
24
+ store?: StateStore;
25
+ });
26
+ checkAndRecord(envelopeId: string, nowMs?: number): void | Promise<void>;
27
+ }
28
+ export declare const WIRE_HINT_TARGET = "SXP-Target";
29
+ export declare const WIRE_HINT_EFFECT = "SXP-Effect";
30
+ /**
31
+ * Header-safe form of a routing hint (`SXP-Target`, `SXP-Effect`), or `undefined` if it is too long to be useful.
32
+ * Visible ASCII is sent as is; anything else, including a value that merely looks encoded, is base64 wrapped so a
33
+ * hostile target name can never inject a header line.
34
+ */
35
+ export declare function encodeWireHint(value: string): string | undefined;
36
+ export declare function decodeWireHint(header: string): string;
37
+ /**
38
+ * Reject a request whose advisory routing headers disagree with its (already authenticated) envelope.
39
+ * The headers sit outside the HMAC, so they are never trusted: they let a gateway route or rate-limit on target
40
+ * and effect without parsing the body, and this check keeps the body from saying something else.
41
+ */
42
+ export declare function checkWireHints(envelope: CoreEnvelope, hints: Record<string, string | undefined>): void;
43
+ /**
44
+ * Reject a request whose `payload.iat_ms` is missing, malformed, or more than `windowMs` from now.
45
+ * The window is symmetric, so a `ReplayGuard` must remember IDs for at least `2 * windowMs`:
46
+ * nothing outside the window is accepted and nothing inside it twice.
47
+ */
48
+ export declare function checkFreshness(payload: Record<string, unknown>, windowMs: number, nowMs?: number): void;
49
+ export declare function signEnvelope(envelope: Omit<CoreEnvelope, "id"> & {
50
+ id?: string;
51
+ }, secret: string | Uint8Array): Promise<string>;
52
+ export declare function verifyEnvelope(envelope: Omit<CoreEnvelope, "id"> & {
53
+ id?: string;
54
+ }, secret: string | Uint8Array, signature: string): Promise<boolean>;
55
+ export declare function negotiate0rttProfile(localSupported: string[], remoteSupported: string[]): ProfileDescriptor;
56
+ export declare function encodeNdjsonFrame(envelope: CoreEnvelope, railsCache?: Map<string, HardRail[]>, signingSecret?: string | Uint8Array): Promise<string>;
57
+ export declare function decodeNdjsonFrame(line: string, railsCache?: Map<string, HardRail[]>, opts?: {
58
+ maxFrameBytes?: number;
59
+ signingSecret?: string | Uint8Array;
60
+ verifyFn?: (env: CoreEnvelope, sig: string) => boolean | Promise<boolean>;
61
+ }): Promise<CoreEnvelope>;
62
+ export interface FetchLikeRequest {
63
+ readonly body: ReadableStream<Uint8Array<ArrayBuffer>> | null;
64
+ readonly headers: {
65
+ get(name: string): string | null;
66
+ };
67
+ }
68
+ export interface FetchLikeResponse extends FetchLikeRequest {
69
+ readonly status: number;
70
+ text(): Promise<string>;
71
+ }
72
+ export declare function readFrame(message: FetchLikeRequest, limit: number, decompressRequest?: boolean): Promise<string>;
73
+ export interface EnvelopeKernelLike {
74
+ readonly supportedProfiles: string[];
75
+ handleEnvelope(envelopeOrLine: CoreEnvelope | string, opts?: {
76
+ signingSecret?: string | Uint8Array;
77
+ replayGuard?: ReplayGuard;
78
+ callerClearance?: Clearance;
79
+ railsCache?: Map<string, HardRail[]>;
80
+ freshnessWindowMs?: number;
81
+ wireHints?: Record<string, string>;
82
+ }): Promise<CoreEnvelope>;
83
+ }
84
+ export declare function createSxpFetchHandler(kernel: EnvelopeKernelLike, opts?: {
85
+ signingSecret?: string | Uint8Array;
86
+ replayGuard?: ReplayGuard;
87
+ callerClearance?: Clearance;
88
+ railsCache?: Map<string, HardRail[]>;
89
+ allowUnsigned?: boolean;
90
+ maxFrameBytes?: number;
91
+ freshnessWindowMs?: number;
92
+ }): (req: FetchLikeRequest) => Promise<Response>;
93
+ export declare class SxpHttpClient {
94
+ readonly endpointUrl: string;
95
+ readonly supportedProfiles: string[];
96
+ private readonly signingSecret?;
97
+ private readonly fetchFn;
98
+ private readonly railsCache;
99
+ constructor(endpointUrl: string, opts?: {
100
+ supportedProfiles?: string[];
101
+ signingSecret?: string | Uint8Array;
102
+ fetchFn?: (url: string, init: RequestInit) => Promise<FetchLikeResponse>;
103
+ });
104
+ sendAndReceive(envelope: CoreEnvelope): Promise<{
105
+ reply: CoreEnvelope;
106
+ profile: ProfileDescriptor;
107
+ }>;
108
+ }