@emilia-protocol/gate 0.9.5 → 0.11.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/LICENSE +190 -0
  3. package/README.md +95 -16
  4. package/action-control-manifest.js +26 -0
  5. package/action-escrow-custodian.js +395 -0
  6. package/action-escrow-evidence.js +859 -0
  7. package/action-escrow-package.js +1669 -0
  8. package/action-escrow-postgres.js +338 -0
  9. package/action-escrow-state.js +397 -0
  10. package/action-escrow-verifiers.js +332 -0
  11. package/action-escrow.js +2448 -0
  12. package/adapters/_kit.js +47 -5
  13. package/adapters/aws.js +15 -4
  14. package/adapters/github-demo.mjs +25 -22
  15. package/adapters/github.js +1 -1
  16. package/adapters/jira.js +1 -0
  17. package/adapters/linear.js +1 -0
  18. package/adapters/salesforce.js +1 -0
  19. package/adapters/stripe.js +1 -1
  20. package/adapters/supabase.js +26 -4
  21. package/adapters/vercel.js +33 -4
  22. package/aec-execution.js +1 -3
  23. package/breakglass.js +285 -51
  24. package/control-plane.js +341 -0
  25. package/coverage.js +722 -0
  26. package/custody-demo.mjs +13 -3
  27. package/demo.mjs +9 -3
  28. package/deploy/helm/README.md +16 -8
  29. package/deploy/helm/emilia-gate/Chart.yaml +3 -1
  30. package/deploy/helm/emilia-gate/templates/NOTES.txt +3 -2
  31. package/deploy/helm/emilia-gate/templates/deployment.yaml +55 -1
  32. package/deploy/helm/emilia-gate/values.yaml +18 -2
  33. package/deploy/helm/emilia-gate-service/Chart.yaml +11 -0
  34. package/deploy/helm/emilia-gate-service/README.md +81 -0
  35. package/deploy/helm/emilia-gate-service/templates/NOTES.txt +12 -0
  36. package/deploy/helm/emilia-gate-service/templates/_helpers.tpl +83 -0
  37. package/deploy/helm/emilia-gate-service/templates/deployment.yaml +153 -0
  38. package/deploy/helm/emilia-gate-service/templates/migration-job.yaml +73 -0
  39. package/deploy/helm/emilia-gate-service/templates/networkpolicy.yaml +113 -0
  40. package/deploy/helm/emilia-gate-service/templates/pdb.yaml +14 -0
  41. package/deploy/helm/emilia-gate-service/templates/service.yaml +20 -0
  42. package/deploy/helm/emilia-gate-service/templates/serviceaccount.yaml +8 -0
  43. package/deploy/helm/emilia-gate-service/tests/fixtures/001_gate.sql +26 -0
  44. package/deploy/helm/emilia-gate-service/tests/fixtures/002_runtime_access.sql +32 -0
  45. package/deploy/helm/emilia-gate-service/tests/fixtures/gate.config.mjs +29 -0
  46. package/deploy/helm/emilia-gate-service/tests/render-check.sh +145 -0
  47. package/deploy/helm/emilia-gate-service/values.schema.json +145 -0
  48. package/deploy/helm/emilia-gate-service/values.yaml +166 -0
  49. package/deploy/sql/001-runtime.sql +707 -0
  50. package/deploy/terraform/README.md +24 -14
  51. package/deploy/terraform/main.tf +59 -0
  52. package/deploy/terraform/service/README.md +81 -0
  53. package/deploy/terraform/service/main.tf +718 -0
  54. package/deploy/terraform/service/outputs.tf +19 -0
  55. package/deploy/terraform/service/tests/validate.sh +24 -0
  56. package/deploy/terraform/service/tests/validation.tftest.hcl +168 -0
  57. package/deploy/terraform/service/variables.tf +459 -0
  58. package/deploy/terraform/service/versions.tf +10 -0
  59. package/deploy/terraform/variables.tf +95 -2
  60. package/deployment-attestation.js +248 -0
  61. package/eg1-conformance.js +46 -12
  62. package/enterprise.js +6 -2
  63. package/ep-assure.mjs +3 -2
  64. package/evidence-postgres.js +357 -0
  65. package/evidence.js +10 -3
  66. package/execution-binding.js +141 -26
  67. package/index.js +556 -115
  68. package/key-registry.js +51 -19
  69. package/mcp.js +4 -2
  70. package/network-witness.js +500 -0
  71. package/package.json +39 -5
  72. package/reliance-kernel.js +5 -6
  73. package/reliance-packet.js +43 -10
  74. package/reports/assurance-package.js +45 -19
  75. package/reports/reperform.js +78 -18
  76. package/reports/underwriter.js +1 -1
  77. package/settlement.js +300 -0
  78. package/store-postgres.js +14 -0
  79. package/store.js +26 -5
  80. package/strict-json.js +103 -0
  81. package/witness-postgres.js +97 -0
package/key-registry.js CHANGED
@@ -21,54 +21,83 @@
21
21
  * entry (back-compatible).
22
22
  */
23
23
 
24
- function toMs(t) {
25
- if (t == null) return null;
26
- const ms = typeof t === 'number' ? t : Date.parse(t);
27
- return Number.isFinite(ms) ? ms : null;
24
+ const RFC3339_INSTANT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|([+-])(\d{2}):(\d{2}))$/;
25
+
26
+ function strictInstantMs(value) {
27
+ if (typeof value !== 'string') return NaN;
28
+ const match = value.match(RFC3339_INSTANT);
29
+ if (!match) return NaN;
30
+ const [, y, mo, d, h, mi, s, , oh, om] = match;
31
+ const calendar = new Date(0);
32
+ calendar.setUTCFullYear(Number(y), Number(mo) - 1, Number(d));
33
+ calendar.setUTCHours(Number(h), Number(mi), Number(s), 0);
34
+ if (calendar.toISOString().slice(0, 19) !== `${y}-${mo}-${d}T${h}:${mi}:${s}`) return NaN;
35
+ if (oh !== undefined && (Number(oh) > 23 || Number(om) > 59)) return NaN;
36
+ const ms = Date.parse(value);
37
+ return Number.isFinite(ms) ? ms : NaN;
38
+ }
39
+
40
+ function optionalInstant(entry, field) {
41
+ if (!Object.hasOwn(entry, field)) return null;
42
+ const ms = strictInstantMs(entry[field]);
43
+ if (!Number.isFinite(ms)) {
44
+ throw new Error(`key registry: ${field} must be a valid RFC3339 instant when supplied`);
45
+ }
46
+ return ms;
28
47
  }
29
48
 
30
49
  /**
31
50
  * @param {Array<object>} entries each: {
32
51
  * kid?: string, key: string (base64url SPKI-DER public key),
33
- * not_before?: string|number, not_after?: string|number, revoked_at?: string|number
52
+ * not_before?: string, not_after?: string, revoked_at?: string (strict RFC3339)
34
53
  * }
35
54
  */
36
55
  export function createKeyRegistry(entries = []) {
37
56
  const list = [];
38
57
  function normalize(e) {
39
58
  if (!e || !e.key || typeof e.key !== 'string') throw new Error('key registry entry requires a base64url SPKI key');
40
- return {
59
+ const normalized = {
41
60
  kid: e.kid || e.key.slice(0, 16),
42
61
  key: e.key,
43
- not_before: toMs(e.not_before),
44
- not_after: toMs(e.not_after),
45
- revoked_at: toMs(e.revoked_at),
62
+ not_before: optionalInstant(e, 'not_before'),
63
+ not_after: optionalInstant(e, 'not_after'),
64
+ revoked_at: optionalInstant(e, 'revoked_at'),
46
65
  };
66
+ if (normalized.not_before != null && normalized.not_after != null
67
+ && normalized.not_after < normalized.not_before) {
68
+ throw new Error('key registry: not_after must not precede not_before');
69
+ }
70
+ return normalized;
47
71
  }
48
72
  for (const e of entries) list.push(normalize(e));
49
73
 
50
74
  /** Is this entry usable to verify a receipt issued at `atMs`? */
51
75
  function entryActiveAt(entry, atMs) {
52
76
  if (entry.revoked_at != null) return false; // HARD revocation: never trust a revoked key
53
- if (entry.not_before != null && atMs != null && atMs < entry.not_before) return false;
54
- if (entry.not_after != null && atMs != null && atMs > entry.not_after) return false;
55
- // A windowed key with an unknown issuance time cannot be safely placed in
56
- // its window — fail closed and exclude it. An unwindowed key still applies.
57
- if ((entry.not_before != null || entry.not_after != null) && atMs == null) return false;
77
+ if (!Number.isFinite(atMs)) return false;
78
+ if (entry.not_before != null && atMs < entry.not_before) return false;
79
+ if (entry.not_after != null && atMs > entry.not_after) return false;
58
80
  return true;
59
81
  }
60
82
 
61
83
  return {
62
- /** The base64url public keys to verify a receipt issued at `at` (ISO or ms). */
84
+ /** The base64url public keys to verify a receipt issued at strict RFC3339 `at`. */
63
85
  keysValidAt(at) {
64
- const atMs = toMs(at);
86
+ const atMs = strictInstantMs(at);
65
87
  return list.filter((e) => entryActiveAt(e, atMs)).map((e) => e.key);
66
88
  },
67
89
  /** Mark a kid revoked as of `at` (default: now-as-supplied). Fail-closed thereafter. */
68
90
  revoke(kid, at) {
91
+ let revokedAt = 0;
92
+ if (arguments.length > 1) {
93
+ revokedAt = strictInstantMs(at);
94
+ if (!Number.isFinite(revokedAt)) {
95
+ throw new Error('key registry: revoked_at must be a valid RFC3339 instant when supplied');
96
+ }
97
+ }
69
98
  let n = 0;
70
99
  for (const e of list) {
71
- if (e.kid === kid && e.revoked_at == null) { e.revoked_at = toMs(at) ?? 0; n += 1; }
100
+ if (e.kid === kid && e.revoked_at == null) { e.revoked_at = revokedAt; n += 1; }
72
101
  }
73
102
  if (n === 0) throw new Error(`key registry: no active key with kid "${kid}" to revoke`);
74
103
  return n;
@@ -77,11 +106,14 @@ export function createKeyRegistry(entries = []) {
77
106
  add(entry) { list.push(normalize(entry)); return this; },
78
107
  /** Operational snapshot (no private material; keys are public). */
79
108
  status(at) {
80
- const atMs = toMs(at);
109
+ const supplied = arguments.length > 0;
110
+ const atMs = supplied ? strictInstantMs(at) : NaN;
81
111
  return list.map((e) => ({
82
112
  kid: e.kid,
83
113
  revoked: e.revoked_at != null,
84
- active: entryActiveAt(e, atMs),
114
+ active: supplied
115
+ ? entryActiveAt(e, atMs)
116
+ : e.revoked_at == null && e.not_before == null && e.not_after == null,
85
117
  not_before: e.not_before,
86
118
  not_after: e.not_after,
87
119
  revoked_at: e.revoked_at,
package/mcp.js CHANGED
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * import { createTrustedActionFirewall } from '@emilia-protocol/gate';
8
8
  * import { gateMcpTool } from '@emilia-protocol/gate/mcp';
9
- * const gate = createTrustedActionFirewall({ trustedKeys: [ISSUER] });
9
+ * const gate = createTrustedActionFirewall({ trustedKeys: [ISSUER], store: sharedConsumptionStore });
10
10
  *
11
11
  * server.tool('release_payment',
12
12
  * gateMcpTool(gate, { tool: 'release_payment' }, async (args) => actuallyPay(args)));
@@ -21,6 +21,8 @@
21
21
  * args.emilia_receipt, then a base64 string in args._emilia_receipt_b64.
22
22
  */
23
23
 
24
+ import { parseReceiptCarrier } from '@emilia-protocol/require-receipt';
25
+
24
26
  function resolveReceipt(args, opts) {
25
27
  if (typeof opts.receipt === 'function') return opts.receipt(args);
26
28
  if (opts.receipt) return opts.receipt;
@@ -28,7 +30,7 @@ function resolveReceipt(args, opts) {
28
30
  if (args._emilia_receipt) return args._emilia_receipt;
29
31
  if (args.emilia_receipt) return args.emilia_receipt;
30
32
  if (typeof args._emilia_receipt_b64 === 'string') {
31
- try { return JSON.parse(Buffer.from(args._emilia_receipt_b64, 'base64').toString('utf8')); } catch { return null; }
33
+ return parseReceiptCarrier(args._emilia_receipt_b64);
32
34
  }
33
35
  }
34
36
  return null;
@@ -0,0 +1,500 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Independent, privacy-minimized observation evidence for EMILIA Gate.
4
+ *
5
+ * A network witness is deliberately NOT an enforcement point. It can prove a
6
+ * pinned sensor observed bytes associated with an action digest at a named
7
+ * capture point. It cannot prove the action was authorized, blocked, executed,
8
+ * or physically completed. Keeping that boundary in the artifact prevents a
9
+ * passive TAP from being marketed as a firewall.
10
+ */
11
+ import crypto from 'node:crypto';
12
+ import { canonicalize } from './execution-binding.js';
13
+ import { strictJsonGate } from './strict-json.js';
14
+
15
+ export const NETWORK_WITNESS_VERSION = 'EP-GATE-NETWORK-WITNESS-v1';
16
+ export const NETWORK_WITNESS_ACCEPTANCE_VERSION = 'EP-GATE-NETWORK-WITNESS-ACCEPTANCE-v1';
17
+ export const NETWORK_WITNESS_DOMAIN = `${NETWORK_WITNESS_VERSION}\0`;
18
+ export const NETWORK_WITNESS_EVENTS = Object.freeze([
19
+ 'request_observed',
20
+ 'response_observed',
21
+ 'effect_observed',
22
+ ]);
23
+
24
+ const DIGEST_RE = /^sha256:[0-9a-f]{64}$/;
25
+ const DIRECTIONS = new Set(['ingress', 'egress', 'internal']);
26
+ const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/;
27
+
28
+ function strictInstantMs(value) {
29
+ if (typeof value !== 'string') return NaN;
30
+ const match = value.match(RFC3339);
31
+ if (!match) return NaN;
32
+ const [, year, month, day, hour, minute, second] = match;
33
+ const base = new Date(0);
34
+ base.setUTCFullYear(Number(year), Number(month) - 1, Number(day));
35
+ base.setUTCHours(Number(hour), Number(minute), Number(second), 0);
36
+ if (base.toISOString().slice(0, 19) !== `${year}-${month}-${day}T${hour}:${minute}:${second}`) return NaN;
37
+ const parsed = Date.parse(value);
38
+ return Number.isFinite(parsed) ? parsed : NaN;
39
+ }
40
+
41
+ function isPlainObject(value) {
42
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
43
+ const prototype = Object.getPrototypeOf(value);
44
+ return prototype === Object.prototype || prototype === null;
45
+ }
46
+
47
+ function exactKeys(value, allowed) {
48
+ return isPlainObject(value) && Object.keys(value).every((key) => allowed.has(key));
49
+ }
50
+
51
+ function nonEmptyString(value, max = 256) {
52
+ return typeof value === 'string' && value.length > 0 && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value);
53
+ }
54
+
55
+ function digest(value) {
56
+ return typeof value === 'string' && DIGEST_RE.test(value);
57
+ }
58
+
59
+ function sha256(bytes) {
60
+ return crypto.createHash('sha256').update(bytes).digest('hex');
61
+ }
62
+
63
+ function decodeBase64Url(value, maxBytes) {
64
+ if (typeof value !== 'string' || value.length === 0 || !/^[A-Za-z0-9_-]+$/.test(value)) return null;
65
+ try {
66
+ const bytes = Buffer.from(value, 'base64url');
67
+ if (bytes.length === 0 || bytes.length > maxBytes || bytes.toString('base64url') !== value) return null;
68
+ return bytes;
69
+ } catch { return null; }
70
+ }
71
+
72
+ function keyIdFor(key) {
73
+ const der = crypto.createPublicKey(key).export({ type: 'spki', format: 'der' });
74
+ return `ep:witness-key:sha256:${sha256(der).slice(0, 16)}`;
75
+ }
76
+
77
+ function signingBytes(body) {
78
+ return Buffer.from(NETWORK_WITNESS_DOMAIN + canonicalize(body), 'utf8');
79
+ }
80
+
81
+ function unsigned(statement) {
82
+ if (!isPlainObject(statement)) throw new TypeError('network witness statement must be an object');
83
+ const { signature: _signature, ...body } = statement;
84
+ return body;
85
+ }
86
+
87
+ export function networkWitnessDigest(statement) {
88
+ return `sha256:${sha256(signingBytes(unsigned(statement)))}`;
89
+ }
90
+
91
+ /** Duplicate-key-safe parser for an untrusted serialized witness artifact. */
92
+ export function parseNetworkWitnessStatement(raw, { maxBytes = 64 * 1024 } = {}) {
93
+ if (typeof raw !== 'string' || !Number.isSafeInteger(maxBytes) || maxBytes < 1
94
+ || Buffer.byteLength(raw, 'utf8') > maxBytes) return null;
95
+ const gated = strictJsonGate(raw);
96
+ if (!gated.ok) return null;
97
+ try {
98
+ const parsed = JSON.parse(raw);
99
+ return isPlainObject(parsed) ? parsed : null;
100
+ } catch { return null; }
101
+ }
102
+
103
+ function validateBody(body) {
104
+ if (!exactKeys(body, new Set(['@version', 'witness', 'observation', 'deployment', 'privacy', 'limitations']))) {
105
+ return 'statement_shape_invalid';
106
+ }
107
+ if (body['@version'] !== NETWORK_WITNESS_VERSION) return 'version_invalid';
108
+ if (!exactKeys(body.witness, new Set(['id', 'key_id', 'capture_point_id']))) return 'witness_shape_invalid';
109
+ if (!nonEmptyString(body.witness.id) || !nonEmptyString(body.witness.key_id)
110
+ || !nonEmptyString(body.witness.capture_point_id)) return 'witness_identity_invalid';
111
+ if (!exactKeys(body.observation, new Set([
112
+ 'sequence', 'observed_at', 'event', 'direction', 'action_digest', 'flow_digest', 'byte_count',
113
+ ]))) return 'observation_shape_invalid';
114
+ if (!Number.isSafeInteger(body.observation.sequence) || body.observation.sequence < 0) return 'sequence_invalid';
115
+ if (!Number.isFinite(strictInstantMs(body.observation.observed_at))) return 'observed_at_invalid';
116
+ if (!NETWORK_WITNESS_EVENTS.includes(body.observation.event)) return 'event_invalid';
117
+ if (!DIRECTIONS.has(body.observation.direction)) return 'direction_invalid';
118
+ if (!digest(body.observation.action_digest)) return 'action_digest_invalid';
119
+ if (body.observation.flow_digest !== undefined && !digest(body.observation.flow_digest)) return 'flow_digest_invalid';
120
+ if (body.observation.byte_count !== undefined
121
+ && (!Number.isSafeInteger(body.observation.byte_count) || body.observation.byte_count < 0)) return 'byte_count_invalid';
122
+ if (!exactKeys(body.deployment, new Set(['config_digest', 'attestation_ref']))) return 'deployment_shape_invalid';
123
+ if (!digest(body.deployment.config_digest)) return 'config_digest_invalid';
124
+ if (body.deployment.attestation_ref !== undefined && !digest(body.deployment.attestation_ref)) {
125
+ return 'attestation_ref_invalid';
126
+ }
127
+ if (!exactKeys(body.privacy, new Set(['payload_captured']))) return 'privacy_shape_invalid';
128
+ if (body.privacy.payload_captured !== false) return 'payload_capture_forbidden';
129
+ if (!Array.isArray(body.limitations) || body.limitations.length < 2 || body.limitations.length > 8
130
+ || body.limitations.some((item) => !nonEmptyString(item, 512))) return 'limitations_invalid';
131
+ try { canonicalize(body); } catch { return 'canonical_body_invalid'; }
132
+ return null;
133
+ }
134
+
135
+ /** Create a signed observation. The public key is intentionally not embedded. */
136
+ export function signNetworkWitnessStatement(input, privateKey) {
137
+ if (!privateKey) throw new TypeError('privateKey is required');
138
+ const keyId = input?.key_id ?? keyIdFor(privateKey);
139
+ const body = {
140
+ '@version': NETWORK_WITNESS_VERSION,
141
+ witness: {
142
+ id: input?.witness_id,
143
+ key_id: keyId,
144
+ capture_point_id: input?.capture_point_id,
145
+ },
146
+ observation: {
147
+ sequence: input?.sequence,
148
+ observed_at: input?.observed_at,
149
+ event: input?.event,
150
+ direction: input?.direction,
151
+ action_digest: input?.action_digest,
152
+ ...(input?.flow_digest !== undefined ? { flow_digest: input.flow_digest } : {}),
153
+ ...(input?.byte_count !== undefined ? { byte_count: input.byte_count } : {}),
154
+ },
155
+ deployment: {
156
+ config_digest: input?.config_digest,
157
+ ...(input?.attestation_ref !== undefined ? { attestation_ref: input.attestation_ref } : {}),
158
+ },
159
+ privacy: { payload_captured: false },
160
+ limitations: [
161
+ 'This artifact proves only that a pinned witness key signed an observation at a named capture point.',
162
+ 'A passive network witness does not authorize, block, execute, or prove the physical outcome of an action.',
163
+ 'Coverage and completeness depend on the relying party pinning the capture topology and expected witness set.',
164
+ 'Rollback detection begins at a relying-party-pinned stream checkpoint; first-seen sequence numbers are not self-authenticating history.',
165
+ ],
166
+ };
167
+ const invalid = validateBody(body);
168
+ if (invalid) throw new TypeError(invalid);
169
+ const statementDigest = networkWitnessDigest(body);
170
+ return Object.freeze({
171
+ ...body,
172
+ signature: Object.freeze({
173
+ algorithm: 'Ed25519',
174
+ key_id: keyId,
175
+ statement_digest: statementDigest,
176
+ signature_b64u: crypto.sign(null, signingBytes(body), privateKey).toString('base64url'),
177
+ }),
178
+ });
179
+ }
180
+
181
+ function findPin(pins, witness) {
182
+ if (!Array.isArray(pins)) return null;
183
+ return pins.find((pin) => isPlainObject(pin)
184
+ && pin.witness_id === witness.id
185
+ && pin.key_id === witness.key_id
186
+ && Array.isArray(pin.capture_point_ids)
187
+ && pin.capture_point_ids.includes(witness.capture_point_id)) ?? null;
188
+ }
189
+
190
+ /**
191
+ * Offline signature and context verification. This function never throws on a
192
+ * presenter-controlled statement. Sequence consumption is a separate online
193
+ * operation performed by acceptNetworkWitnessStatement.
194
+ */
195
+ export function verifyNetworkWitnessStatement(statement, options = {}) {
196
+ const fail = (reason, checks = {}) => ({
197
+ verified: false,
198
+ accepted: false,
199
+ reason,
200
+ checks: {
201
+ shape: false,
202
+ pin: false,
203
+ signature: false,
204
+ action_binding: false,
205
+ freshness: false,
206
+ config_binding: false,
207
+ ...checks,
208
+ },
209
+ });
210
+ try {
211
+ if (!isPlainObject(statement)
212
+ || !exactKeys(statement, new Set(['@version', 'witness', 'observation', 'deployment', 'privacy', 'limitations', 'signature']))) {
213
+ return fail('statement_shape_invalid');
214
+ }
215
+ const body = unsigned(statement);
216
+ const invalid = validateBody(body);
217
+ if (invalid) return fail(invalid);
218
+ if (!exactKeys(statement.signature, new Set(['algorithm', 'key_id', 'statement_digest', 'signature_b64u']))) {
219
+ return fail('signature_shape_invalid', { shape: true });
220
+ }
221
+ if (statement.signature.algorithm !== 'Ed25519'
222
+ || statement.signature.key_id !== body.witness.key_id
223
+ || !digest(statement.signature.statement_digest)
224
+ || !nonEmptyString(statement.signature.signature_b64u, 512)) {
225
+ return fail('signature_envelope_invalid', { shape: true });
226
+ }
227
+ const pin = findPin(options.pinnedWitnesses, body.witness);
228
+ if (!pin || !nonEmptyString(pin.public_key, 4096)) return fail('witness_key_unpinned', { shape: true });
229
+ if (!Array.isArray(pin.config_digests) || pin.config_digests.length === 0
230
+ || !pin.config_digests.includes(body.deployment.config_digest)) {
231
+ return fail('witness_config_unpinned', { shape: true, pin: true });
232
+ }
233
+ if (options.expectedActionDigest !== undefined
234
+ && body.observation.action_digest !== options.expectedActionDigest) {
235
+ return fail('action_digest_mismatch', { shape: true, pin: true, config_binding: true });
236
+ }
237
+ if (options.expectedEvent !== undefined && body.observation.event !== options.expectedEvent) {
238
+ return fail('event_mismatch', { shape: true, pin: true, config_binding: true });
239
+ }
240
+ const now = options.now === undefined ? Date.now() : Number(options.now);
241
+ const maxAgeSec = options.maxAgeSec === undefined ? 300 : options.maxAgeSec;
242
+ const maxFutureSkewSec = options.maxFutureSkewSec === undefined ? 30 : options.maxFutureSkewSec;
243
+ if (!Number.isFinite(now) || !Number.isSafeInteger(maxAgeSec) || maxAgeSec < 0
244
+ || !Number.isSafeInteger(maxFutureSkewSec) || maxFutureSkewSec < 0) {
245
+ return fail('verification_profile_invalid', { shape: true, pin: true, config_binding: true });
246
+ }
247
+ const observedMs = strictInstantMs(body.observation.observed_at);
248
+ if (observedMs > now + (maxFutureSkewSec * 1000)) {
249
+ return fail('observation_from_future', { shape: true, pin: true, action_binding: true, config_binding: true });
250
+ }
251
+ if (now - observedMs > maxAgeSec * 1000) {
252
+ return fail('observation_stale', { shape: true, pin: true, action_binding: true, config_binding: true });
253
+ }
254
+ const computedDigest = networkWitnessDigest(body);
255
+ if (computedDigest !== statement.signature.statement_digest) {
256
+ return fail('statement_digest_mismatch', {
257
+ shape: true, pin: true, action_binding: true, freshness: true, config_binding: true,
258
+ });
259
+ }
260
+ let publicKey;
261
+ try {
262
+ const keyBytes = decodeBase64Url(pin.public_key, 4096);
263
+ if (!keyBytes) throw new TypeError('invalid base64url key');
264
+ publicKey = crypto.createPublicKey({
265
+ key: keyBytes,
266
+ type: 'spki',
267
+ format: 'der',
268
+ });
269
+ if (publicKey.asymmetricKeyType !== 'ed25519') throw new TypeError('witness key must be Ed25519');
270
+ } catch {
271
+ return fail('pinned_key_invalid', {
272
+ shape: true, pin: true, action_binding: true, freshness: true, config_binding: true,
273
+ });
274
+ }
275
+ const signature = decodeBase64Url(statement.signature.signature_b64u, 64);
276
+ if (!signature || signature.length !== 64) {
277
+ return fail('signature_invalid', {
278
+ shape: true, pin: true, action_binding: true, freshness: true, config_binding: true,
279
+ });
280
+ }
281
+ if (!crypto.verify(null, signingBytes(body), publicKey, signature)) {
282
+ return fail('signature_invalid', {
283
+ shape: true, pin: true, action_binding: true, freshness: true, config_binding: true,
284
+ });
285
+ }
286
+ return {
287
+ verified: true,
288
+ accepted: true,
289
+ reason: null,
290
+ statement_digest: computedDigest,
291
+ stream_id: `${body.witness.id}\0${body.witness.capture_point_id}`,
292
+ sequence: body.observation.sequence,
293
+ action_digest: body.observation.action_digest,
294
+ event: body.observation.event,
295
+ observed_at: body.observation.observed_at,
296
+ witness_id: body.witness.id,
297
+ capture_point_id: body.witness.capture_point_id,
298
+ checks: {
299
+ shape: true,
300
+ pin: true,
301
+ signature: true,
302
+ action_binding: true,
303
+ freshness: true,
304
+ config_binding: true,
305
+ },
306
+ limitation: 'Observation is not authorization, enforcement, execution, or physical truth.',
307
+ };
308
+ } catch {
309
+ return fail('hostile_input_refused');
310
+ }
311
+ }
312
+
313
+ export function createMemoryWitnessSequenceStore() {
314
+ const streams = new Map();
315
+ return {
316
+ durable: false,
317
+ async advance(streamId, sequence, statementDigest) {
318
+ const previous = streams.get(streamId);
319
+ if (previous) {
320
+ if (previous.equivocated === true) {
321
+ return { accepted: false, reason: 'sequence_equivocation' };
322
+ }
323
+ if (sequence < previous.sequence) return { accepted: false, reason: 'sequence_rollback' };
324
+ if (sequence === previous.sequence) {
325
+ if (previous.digest === statementDigest) {
326
+ return { accepted: false, reason: 'statement_replay' };
327
+ }
328
+ streams.set(streamId, { ...previous, equivocated: true });
329
+ return { accepted: false, reason: 'sequence_equivocation' };
330
+ }
331
+ }
332
+ streams.set(streamId, { sequence, digest: statementDigest, equivocated: false });
333
+ return { accepted: true, reason: null };
334
+ },
335
+ snapshot() { return [...streams.entries()].map(([stream_id, value]) => ({ stream_id, ...value })); },
336
+ };
337
+ }
338
+
339
+ function acceptanceResult(verified, {
340
+ accepted,
341
+ consumed,
342
+ reason,
343
+ sequenceStoreDurable,
344
+ }) {
345
+ return Object.freeze({
346
+ ...verified,
347
+ acceptance_version: NETWORK_WITNESS_ACCEPTANCE_VERSION,
348
+ accepted,
349
+ consumed,
350
+ reason,
351
+ sequence_store_durable: sequenceStoreDurable === true,
352
+ ...(isPlainObject(verified.checks) ? { checks: Object.freeze({ ...verified.checks }) } : {}),
353
+ });
354
+ }
355
+
356
+ /**
357
+ * Validate an ingestion result supplied through a relying-party-trusted option.
358
+ * This does not authenticate presenter-controlled JSON; callers must never move
359
+ * an untrusted bundle field into this trust channel.
360
+ */
361
+ export function validateTrustedNetworkWitnessAcceptance(result, options = {}) {
362
+ const fail = (reason, fields = {}, statementVerified = false) => ({
363
+ verified: statementVerified === true,
364
+ accepted: false,
365
+ consumed: false,
366
+ reason,
367
+ ...fields,
368
+ });
369
+ try {
370
+ if (!isPlainObject(result)
371
+ || result.acceptance_version !== NETWORK_WITNESS_ACCEPTANCE_VERSION) {
372
+ return fail('trusted_witness_acceptance_invalid');
373
+ }
374
+
375
+ const common = {
376
+ acceptance_version: NETWORK_WITNESS_ACCEPTANCE_VERSION,
377
+ statement_digest: result.statement_digest,
378
+ stream_id: result.stream_id,
379
+ sequence: result.sequence,
380
+ action_digest: result.action_digest,
381
+ event: result.event,
382
+ observed_at: result.observed_at,
383
+ witness_id: result.witness_id,
384
+ capture_point_id: result.capture_point_id,
385
+ sequence_store_durable: result.sequence_store_durable === true,
386
+ };
387
+ const statementVerified = result.verified === true
388
+ && digest(common.statement_digest) && digest(common.action_digest)
389
+ && Number.isSafeInteger(common.sequence) && common.sequence >= 0
390
+ && nonEmptyString(common.witness_id) && nonEmptyString(common.capture_point_id)
391
+ && common.stream_id === `${common.witness_id}\0${common.capture_point_id}`
392
+ && NETWORK_WITNESS_EVENTS.includes(common.event)
393
+ && Number.isFinite(strictInstantMs(common.observed_at));
394
+ if (result.accepted !== true || result.consumed !== true) {
395
+ return fail(
396
+ nonEmptyString(result.reason) ? result.reason : 'trusted_witness_acceptance_rejected',
397
+ common,
398
+ statementVerified,
399
+ );
400
+ }
401
+ if (!statementVerified || result.reason !== null) {
402
+ return fail('trusted_witness_acceptance_invalid');
403
+ }
404
+ if (!common.sequence_store_durable && options.allowEphemeralStore !== true) {
405
+ return fail('durable_sequence_store_required', common);
406
+ }
407
+ if (options.expectedStatementDigest !== undefined) {
408
+ if (!digest(options.expectedStatementDigest)) return fail('verification_profile_invalid', common);
409
+ if (common.statement_digest !== options.expectedStatementDigest) {
410
+ return fail('witness_acceptance_digest_mismatch', common);
411
+ }
412
+ }
413
+ if (options.expectedActionDigest !== undefined
414
+ && common.action_digest !== options.expectedActionDigest) {
415
+ return fail('action_digest_mismatch', common);
416
+ }
417
+ if (options.expectedEvent !== undefined && common.event !== options.expectedEvent) {
418
+ return fail('event_mismatch', common);
419
+ }
420
+ const now = options.now === undefined ? Date.now() : Number(options.now);
421
+ const maxAgeSec = options.maxAgeSec === undefined ? 300 : options.maxAgeSec;
422
+ const maxFutureSkewSec = options.maxFutureSkewSec === undefined ? 30 : options.maxFutureSkewSec;
423
+ if (!Number.isFinite(now) || !Number.isSafeInteger(maxAgeSec) || maxAgeSec < 0
424
+ || !Number.isSafeInteger(maxFutureSkewSec) || maxFutureSkewSec < 0) {
425
+ return fail('verification_profile_invalid', common);
426
+ }
427
+ const observedMs = strictInstantMs(common.observed_at);
428
+ if (observedMs > now + (maxFutureSkewSec * 1000)) return fail('observation_from_future', common);
429
+ if (now - observedMs > maxAgeSec * 1000) return fail('observation_stale', common);
430
+ return {
431
+ ...common,
432
+ verified: true,
433
+ accepted: true,
434
+ consumed: true,
435
+ reason: null,
436
+ };
437
+ } catch {
438
+ return fail('trusted_witness_acceptance_invalid');
439
+ }
440
+ }
441
+
442
+ /** Verify and atomically advance a witness stream for online ingestion. */
443
+ export async function acceptNetworkWitnessStatement(statement, options = {}) {
444
+ const verified = verifyNetworkWitnessStatement(statement, options);
445
+ if (!verified.accepted) {
446
+ return acceptanceResult(verified, {
447
+ accepted: false,
448
+ consumed: false,
449
+ reason: verified.reason,
450
+ sequenceStoreDurable: false,
451
+ });
452
+ }
453
+ const store = options.sequenceStore;
454
+ if (!store || typeof store.advance !== 'function'
455
+ || (store.durable !== true && options.allowEphemeralStore !== true)) {
456
+ return acceptanceResult(verified, {
457
+ accepted: false,
458
+ consumed: false,
459
+ reason: 'durable_sequence_store_required',
460
+ sequenceStoreDurable: false,
461
+ });
462
+ }
463
+ try {
464
+ const advanced = await store.advance(verified.stream_id, verified.sequence, verified.statement_digest);
465
+ if (!isPlainObject(advanced) || advanced.accepted !== true || advanced.reason !== null) {
466
+ return acceptanceResult(verified, {
467
+ accepted: false,
468
+ consumed: false,
469
+ reason: nonEmptyString(advanced?.reason) ? advanced.reason : 'sequence_store_refused',
470
+ sequenceStoreDurable: store.durable === true,
471
+ });
472
+ }
473
+ return acceptanceResult(verified, {
474
+ accepted: true,
475
+ consumed: true,
476
+ reason: null,
477
+ sequenceStoreDurable: store.durable === true,
478
+ });
479
+ } catch {
480
+ return acceptanceResult(verified, {
481
+ accepted: false,
482
+ consumed: false,
483
+ reason: 'sequence_store_unavailable',
484
+ sequenceStoreDurable: store.durable === true,
485
+ });
486
+ }
487
+ }
488
+
489
+ export default {
490
+ NETWORK_WITNESS_VERSION,
491
+ NETWORK_WITNESS_ACCEPTANCE_VERSION,
492
+ NETWORK_WITNESS_EVENTS,
493
+ parseNetworkWitnessStatement,
494
+ networkWitnessDigest,
495
+ signNetworkWitnessStatement,
496
+ verifyNetworkWitnessStatement,
497
+ acceptNetworkWitnessStatement,
498
+ validateTrustedNetworkWitnessAcceptance,
499
+ createMemoryWitnessSequenceStore,
500
+ };