@kya-os/checkpoint-express 1.1.0 → 1.1.2

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/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var nodeCrypto = require('crypto');
4
- var zlib = require('zlib');
4
+ var orchestrator = require('@kya-os/checkpoint-wasm-runtime/orchestrator');
5
+ var adapters = require('@kya-os/checkpoint-wasm-runtime/adapters');
5
6
  var checkpointShared = require('@kya-os/checkpoint-shared');
6
7
 
7
8
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -658,18 +659,18 @@ function createAutoPipelineProxy(_redis, namespace = "root") {
658
659
  }
659
660
  });
660
661
  }
661
- var __defProp3, __export3, error_exports, UpstashError, UrlError, UpstashJSONParseError, MAX_BUFFER_SIZE, HttpClient, defaultSerializer, Command, ExecCommand, FIELD_TYPES, SearchIndex, HRandFieldCommand, AppendCommand, BitCountCommand, BitFieldCommand, BitOpCommand, BitPosCommand, ClientSetInfoCommand, CopyCommand, DBSizeCommand, DecrCommand, DecrByCommand, DelCommand, EchoCommand, EvalROCommand, EvalCommand, EvalshaROCommand, EvalshaCommand, ExistsCommand, ExpireCommand, ExpireAtCommand, FCallCommand, FCallRoCommand, FlushAllCommand, FlushDBCommand, FunctionDeleteCommand, FunctionFlushCommand, FunctionListCommand, FunctionLoadCommand, FunctionStatsCommand, GeoAddCommand, GeoDistCommand, GeoHashCommand, GeoPosCommand, GeoSearchCommand, GeoSearchStoreCommand, GetCommand, GetBitCommand, GetDelCommand, GetExCommand, GetRangeCommand, GetSetCommand, HDelCommand, HExistsCommand, HExpireCommand, HExpireAtCommand, HExpireTimeCommand, HPersistCommand, HPExpireCommand, HPExpireAtCommand, HPExpireTimeCommand, HPTtlCommand, HGetCommand, HGetAllCommand, HMGetCommand, HGetDelCommand, HGetExCommand, HIncrByCommand, HIncrByFloatCommand, HKeysCommand, HLenCommand, HMSetCommand, HScanCommand, HSetCommand, HSetExCommand, HSetNXCommand, HStrLenCommand, HTtlCommand, HValsCommand, IncrCommand, IncrByCommand, IncrByFloatCommand, JsonArrAppendCommand, JsonArrIndexCommand, JsonArrInsertCommand, JsonArrLenCommand, JsonArrPopCommand, JsonArrTrimCommand, JsonClearCommand, JsonDelCommand, JsonForgetCommand, JsonGetCommand, JsonMergeCommand, JsonMGetCommand, JsonMSetCommand, JsonNumIncrByCommand, JsonNumMultByCommand, JsonObjKeysCommand, JsonObjLenCommand, JsonRespCommand, JsonSetCommand, JsonStrAppendCommand, JsonStrLenCommand, JsonToggleCommand, JsonTypeCommand, KeysCommand, LIndexCommand, LInsertCommand, LLenCommand, LMoveCommand, LmPopCommand, LPopCommand, LPosCommand, LPushCommand, LPushXCommand, LRangeCommand, LRemCommand, LSetCommand, LTrimCommand, MGetCommand, MSetCommand, MSetNXCommand, PersistCommand, PExpireCommand, PExpireAtCommand, PfAddCommand, PfCountCommand, PfMergeCommand, PingCommand, PSetEXCommand, PTtlCommand, PublishCommand, RandomKeyCommand, RenameCommand, RenameNXCommand, RPopCommand, RPushCommand, RPushXCommand, SAddCommand, ScanCommand, SCardCommand, ScriptExistsCommand, ScriptFlushCommand, ScriptLoadCommand, SDiffCommand, SDiffStoreCommand, SetCommand, SetBitCommand, SetExCommand, SetNxCommand, SetRangeCommand, SInterCommand, SInterCardCommand, SInterStoreCommand, SIsMemberCommand, SMembersCommand, SMIsMemberCommand, SMoveCommand, SPopCommand, SRandMemberCommand, SRemCommand, SScanCommand, StrLenCommand, SUnionCommand, SUnionStoreCommand, TimeCommand, TouchCommand, TtlCommand, TypeCommand, UnlinkCommand, XAckCommand, XAckDelCommand, XAddCommand, XAutoClaim, XClaimCommand, XDelCommand, XDelExCommand, XGroupCommand, XInfoCommand, XLenCommand, XPendingCommand, XRangeCommand, UNBALANCED_XREAD_ERR, XReadCommand, UNBALANCED_XREADGROUP_ERR, XReadGroupCommand, XRevRangeCommand, XTrimCommand, ZAddCommand, ZCardCommand, ZCountCommand, ZIncrByCommand, ZInterStoreCommand, ZLexCountCommand, ZPopMaxCommand, ZPopMinCommand, ZRangeCommand, ZRankCommand, ZRemCommand, ZRemRangeByLexCommand, ZRemRangeByRankCommand, ZRemRangeByScoreCommand, ZRevRankCommand, ZScanCommand, ZScoreCommand, ZUnionCommand, ZUnionStoreCommand, ZDiffStoreCommand, ZMScoreCommand, Pipeline, EXCLUDE_COMMANDS, AutoPipelineExecutor, PSubscribeCommand, Subscriber, SubscribeCommand, parseWithTryCatch, Script, ScriptRO, Redis, VERSION;
662
+ var __defProp2, __export2, error_exports, UpstashError, UrlError, UpstashJSONParseError, MAX_BUFFER_SIZE, HttpClient, defaultSerializer, Command, ExecCommand, FIELD_TYPES, SearchIndex, HRandFieldCommand, AppendCommand, BitCountCommand, BitFieldCommand, BitOpCommand, BitPosCommand, ClientSetInfoCommand, CopyCommand, DBSizeCommand, DecrCommand, DecrByCommand, DelCommand, EchoCommand, EvalROCommand, EvalCommand, EvalshaROCommand, EvalshaCommand, ExistsCommand, ExpireCommand, ExpireAtCommand, FCallCommand, FCallRoCommand, FlushAllCommand, FlushDBCommand, FunctionDeleteCommand, FunctionFlushCommand, FunctionListCommand, FunctionLoadCommand, FunctionStatsCommand, GeoAddCommand, GeoDistCommand, GeoHashCommand, GeoPosCommand, GeoSearchCommand, GeoSearchStoreCommand, GetCommand, GetBitCommand, GetDelCommand, GetExCommand, GetRangeCommand, GetSetCommand, HDelCommand, HExistsCommand, HExpireCommand, HExpireAtCommand, HExpireTimeCommand, HPersistCommand, HPExpireCommand, HPExpireAtCommand, HPExpireTimeCommand, HPTtlCommand, HGetCommand, HGetAllCommand, HMGetCommand, HGetDelCommand, HGetExCommand, HIncrByCommand, HIncrByFloatCommand, HKeysCommand, HLenCommand, HMSetCommand, HScanCommand, HSetCommand, HSetExCommand, HSetNXCommand, HStrLenCommand, HTtlCommand, HValsCommand, IncrCommand, IncrByCommand, IncrByFloatCommand, JsonArrAppendCommand, JsonArrIndexCommand, JsonArrInsertCommand, JsonArrLenCommand, JsonArrPopCommand, JsonArrTrimCommand, JsonClearCommand, JsonDelCommand, JsonForgetCommand, JsonGetCommand, JsonMergeCommand, JsonMGetCommand, JsonMSetCommand, JsonNumIncrByCommand, JsonNumMultByCommand, JsonObjKeysCommand, JsonObjLenCommand, JsonRespCommand, JsonSetCommand, JsonStrAppendCommand, JsonStrLenCommand, JsonToggleCommand, JsonTypeCommand, KeysCommand, LIndexCommand, LInsertCommand, LLenCommand, LMoveCommand, LmPopCommand, LPopCommand, LPosCommand, LPushCommand, LPushXCommand, LRangeCommand, LRemCommand, LSetCommand, LTrimCommand, MGetCommand, MSetCommand, MSetNXCommand, PersistCommand, PExpireCommand, PExpireAtCommand, PfAddCommand, PfCountCommand, PfMergeCommand, PingCommand, PSetEXCommand, PTtlCommand, PublishCommand, RandomKeyCommand, RenameCommand, RenameNXCommand, RPopCommand, RPushCommand, RPushXCommand, SAddCommand, ScanCommand, SCardCommand, ScriptExistsCommand, ScriptFlushCommand, ScriptLoadCommand, SDiffCommand, SDiffStoreCommand, SetCommand, SetBitCommand, SetExCommand, SetNxCommand, SetRangeCommand, SInterCommand, SInterCardCommand, SInterStoreCommand, SIsMemberCommand, SMembersCommand, SMIsMemberCommand, SMoveCommand, SPopCommand, SRandMemberCommand, SRemCommand, SScanCommand, StrLenCommand, SUnionCommand, SUnionStoreCommand, TimeCommand, TouchCommand, TtlCommand, TypeCommand, UnlinkCommand, XAckCommand, XAckDelCommand, XAddCommand, XAutoClaim, XClaimCommand, XDelCommand, XDelExCommand, XGroupCommand, XInfoCommand, XLenCommand, XPendingCommand, XRangeCommand, UNBALANCED_XREAD_ERR, XReadCommand, UNBALANCED_XREADGROUP_ERR, XReadGroupCommand, XRevRangeCommand, XTrimCommand, ZAddCommand, ZCardCommand, ZCountCommand, ZIncrByCommand, ZInterStoreCommand, ZLexCountCommand, ZPopMaxCommand, ZPopMinCommand, ZRangeCommand, ZRankCommand, ZRemCommand, ZRemRangeByLexCommand, ZRemRangeByRankCommand, ZRemRangeByScoreCommand, ZRevRankCommand, ZScanCommand, ZScoreCommand, ZUnionCommand, ZUnionStoreCommand, ZDiffStoreCommand, ZMScoreCommand, Pipeline, EXCLUDE_COMMANDS, AutoPipelineExecutor, PSubscribeCommand, Subscriber, SubscribeCommand, parseWithTryCatch, Script, ScriptRO, Redis, VERSION;
662
663
  var init_chunk_IH7W44G6 = __esm({
663
664
  "../../node_modules/.pnpm/@upstash+redis@1.37.0/node_modules/@upstash/redis/chunk-IH7W44G6.mjs"() {
664
665
  init_crypto_node();
665
666
  init_crypto_node();
666
- __defProp3 = Object.defineProperty;
667
- __export3 = (target, all) => {
667
+ __defProp2 = Object.defineProperty;
668
+ __export2 = (target, all) => {
668
669
  for (var name in all)
669
- __defProp3(target, name, { get: all[name], enumerable: true });
670
+ __defProp2(target, name, { get: all[name], enumerable: true });
670
671
  };
671
672
  error_exports = {};
672
- __export3(error_exports, {
673
+ __export2(error_exports, {
673
674
  UpstashError: () => UpstashError,
674
675
  UpstashJSONParseError: () => UpstashJSONParseError,
675
676
  UrlError: () => UrlError
@@ -4926,10 +4927,10 @@ var init_nodejs = __esm({
4926
4927
  _noTokenize;
4927
4928
  _noStem;
4928
4929
  _from;
4929
- constructor(noTokenize = { noTokenize: false }, noStem = { noStem: false }, from2 = { from: null }) {
4930
+ constructor(noTokenize = { noTokenize: false }, noStem = { noStem: false }, from = { from: null }) {
4930
4931
  this._noTokenize = noTokenize;
4931
4932
  this._noStem = noStem;
4932
- this._from = from2;
4933
+ this._from = from;
4933
4934
  }
4934
4935
  noTokenize() {
4935
4936
  return new _TextFieldBuilder({ noTokenize: true }, this._noStem, this._from);
@@ -4952,9 +4953,9 @@ var init_nodejs = __esm({
4952
4953
  NumericFieldBuilder = class _NumericFieldBuilder {
4953
4954
  type;
4954
4955
  _from;
4955
- constructor(type, from2 = { from: null }) {
4956
+ constructor(type, from = { from: null }) {
4956
4957
  this.type = type;
4957
- this._from = from2;
4958
+ this._from = from;
4958
4959
  }
4959
4960
  from(field) {
4960
4961
  return new _NumericFieldBuilder(this.type, { from: field });
@@ -4973,9 +4974,9 @@ var init_nodejs = __esm({
4973
4974
  BoolFieldBuilder = class _BoolFieldBuilder {
4974
4975
  _fast;
4975
4976
  _from;
4976
- constructor(fast = { fast: false }, from2 = { from: null }) {
4977
+ constructor(fast = { fast: false }, from = { from: null }) {
4977
4978
  this._fast = fast;
4978
- this._from = from2;
4979
+ this._from = from;
4979
4980
  }
4980
4981
  fast() {
4981
4982
  return new _BoolFieldBuilder({ fast: true }, this._from);
@@ -5011,9 +5012,9 @@ var init_nodejs = __esm({
5011
5012
  DateFieldBuilder = class _DateFieldBuilder {
5012
5013
  _fast;
5013
5014
  _from;
5014
- constructor(fast = { fast: false }, from2 = { from: null }) {
5015
+ constructor(fast = { fast: false }, from = { from: null }) {
5015
5016
  this._fast = fast;
5016
- this._from = from2;
5017
+ this._from = from;
5017
5018
  }
5018
5019
  fast() {
5019
5020
  return new _DateFieldBuilder({ fast: true }, this._from);
@@ -5196,1782 +5197,6 @@ var init_nodejs = __esm({
5196
5197
  };
5197
5198
  }
5198
5199
  });
5199
-
5200
- // ../checkpoint-wasm-runtime/dist/orchestrator.mjs
5201
- var __defProp2 = Object.defineProperty;
5202
- var __export2 = (target, all) => {
5203
- for (var name in all)
5204
- __defProp2(target, name, { get: all[name], enumerable: true });
5205
- };
5206
- var kya_os_engine_exports = {};
5207
- __export2(kya_os_engine_exports, {
5208
- default: () => kya_os_engine_default,
5209
- initSync: () => initSync,
5210
- verify: () => verify
5211
- });
5212
- function getUint8ArrayMemory0() {
5213
- if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
5214
- cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
5215
- }
5216
- return cachedUint8ArrayMemory0;
5217
- }
5218
- function decodeText(ptr, len) {
5219
- numBytesDecoded += len;
5220
- if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
5221
- cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
5222
- cachedTextDecoder.decode();
5223
- numBytesDecoded = len;
5224
- }
5225
- return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
5226
- }
5227
- function getStringFromWasm0(ptr, len) {
5228
- ptr = ptr >>> 0;
5229
- return decodeText(ptr, len);
5230
- }
5231
- function addHeapObject(obj) {
5232
- if (heap_next === heap.length) heap.push(heap.length + 1);
5233
- const idx = heap_next;
5234
- heap_next = heap[idx];
5235
- heap[idx] = obj;
5236
- return idx;
5237
- }
5238
- function getObject(idx) {
5239
- return heap[idx];
5240
- }
5241
- function passStringToWasm0(arg, malloc, realloc) {
5242
- if (realloc === void 0) {
5243
- const buf = cachedTextEncoder.encode(arg);
5244
- const ptr2 = malloc(buf.length, 1) >>> 0;
5245
- getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
5246
- WASM_VECTOR_LEN = buf.length;
5247
- return ptr2;
5248
- }
5249
- let len = arg.length;
5250
- let ptr = malloc(len, 1) >>> 0;
5251
- const mem = getUint8ArrayMemory0();
5252
- let offset = 0;
5253
- for (; offset < len; offset++) {
5254
- const code = arg.charCodeAt(offset);
5255
- if (code > 127) break;
5256
- mem[ptr + offset] = code;
5257
- }
5258
- if (offset !== len) {
5259
- if (offset !== 0) {
5260
- arg = arg.slice(offset);
5261
- }
5262
- ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
5263
- const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
5264
- const ret = cachedTextEncoder.encodeInto(arg, view);
5265
- offset += ret.written;
5266
- ptr = realloc(ptr, len, offset, 1) >>> 0;
5267
- }
5268
- WASM_VECTOR_LEN = offset;
5269
- return ptr;
5270
- }
5271
- function getDataViewMemory0() {
5272
- if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm.memory.buffer) {
5273
- cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
5274
- }
5275
- return cachedDataViewMemory0;
5276
- }
5277
- function isLikeNone(x) {
5278
- return x === void 0 || x === null;
5279
- }
5280
- function debugString(val) {
5281
- const type = typeof val;
5282
- if (type == "number" || type == "boolean" || val == null) {
5283
- return `${val}`;
5284
- }
5285
- if (type == "string") {
5286
- return `"${val}"`;
5287
- }
5288
- if (type == "symbol") {
5289
- const description = val.description;
5290
- if (description == null) {
5291
- return "Symbol";
5292
- } else {
5293
- return `Symbol(${description})`;
5294
- }
5295
- }
5296
- if (type == "function") {
5297
- const name = val.name;
5298
- if (typeof name == "string" && name.length > 0) {
5299
- return `Function(${name})`;
5300
- } else {
5301
- return "Function";
5302
- }
5303
- }
5304
- if (Array.isArray(val)) {
5305
- const length = val.length;
5306
- let debug = "[";
5307
- if (length > 0) {
5308
- debug += debugString(val[0]);
5309
- }
5310
- for (let i = 1; i < length; i++) {
5311
- debug += ", " + debugString(val[i]);
5312
- }
5313
- debug += "]";
5314
- return debug;
5315
- }
5316
- const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
5317
- let className;
5318
- if (builtInMatches && builtInMatches.length > 1) {
5319
- className = builtInMatches[1];
5320
- } else {
5321
- return toString.call(val);
5322
- }
5323
- if (className == "Object") {
5324
- try {
5325
- return "Object(" + JSON.stringify(val) + ")";
5326
- } catch (_) {
5327
- return "Object";
5328
- }
5329
- }
5330
- if (val instanceof Error) {
5331
- return `${val.name}: ${val.message}
5332
- ${val.stack}`;
5333
- }
5334
- return className;
5335
- }
5336
- function handleError(f, args) {
5337
- try {
5338
- return f.apply(this, args);
5339
- } catch (e) {
5340
- wasm.__wbindgen_export3(addHeapObject(e));
5341
- }
5342
- }
5343
- function getArrayU8FromWasm0(ptr, len) {
5344
- ptr = ptr >>> 0;
5345
- return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
5346
- }
5347
- function dropObject(idx) {
5348
- if (idx < 132) return;
5349
- heap[idx] = heap_next;
5350
- heap_next = idx;
5351
- }
5352
- function takeObject(idx) {
5353
- const ret = getObject(idx);
5354
- dropObject(idx);
5355
- return ret;
5356
- }
5357
- function verify(input_js, ctx_js) {
5358
- try {
5359
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
5360
- wasm.verify(retptr, addHeapObject(input_js), addHeapObject(ctx_js));
5361
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
5362
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
5363
- var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
5364
- if (r2) {
5365
- throw takeObject(r1);
5366
- }
5367
- return takeObject(r0);
5368
- } finally {
5369
- wasm.__wbindgen_add_to_stack_pointer(16);
5370
- }
5371
- }
5372
- function __wbg_get_imports() {
5373
- const imports = {};
5374
- imports.wbg = {};
5375
- imports.wbg.__wbg_Error_e83987f665cf5504 = function(arg0, arg1) {
5376
- const ret = Error(getStringFromWasm0(arg0, arg1));
5377
- return addHeapObject(ret);
5378
- };
5379
- imports.wbg.__wbg_Number_bb48ca12f395cd08 = function(arg0) {
5380
- const ret = Number(getObject(arg0));
5381
- return ret;
5382
- };
5383
- imports.wbg.__wbg_String_8f0eb39a4a4c2f66 = function(arg0, arg1) {
5384
- const ret = String(getObject(arg1));
5385
- const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2);
5386
- const len1 = WASM_VECTOR_LEN;
5387
- getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
5388
- getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
5389
- };
5390
- imports.wbg.__wbg___wbindgen_bigint_get_as_i64_f3ebc5a755000afd = function(arg0, arg1) {
5391
- const v = getObject(arg1);
5392
- const ret = typeof v === "bigint" ? v : void 0;
5393
- getDataViewMemory0().setBigInt64(arg0 + 8 * 1, isLikeNone(ret) ? BigInt(0) : ret, true);
5394
- getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
5395
- };
5396
- imports.wbg.__wbg___wbindgen_boolean_get_6d5a1ee65bab5f68 = function(arg0) {
5397
- const v = getObject(arg0);
5398
- const ret = typeof v === "boolean" ? v : void 0;
5399
- return isLikeNone(ret) ? 16777215 : ret ? 1 : 0;
5400
- };
5401
- imports.wbg.__wbg___wbindgen_debug_string_df47ffb5e35e6763 = function(arg0, arg1) {
5402
- const ret = debugString(getObject(arg1));
5403
- const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2);
5404
- const len1 = WASM_VECTOR_LEN;
5405
- getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
5406
- getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
5407
- };
5408
- imports.wbg.__wbg___wbindgen_in_bb933bd9e1b3bc0f = function(arg0, arg1) {
5409
- const ret = getObject(arg0) in getObject(arg1);
5410
- return ret;
5411
- };
5412
- imports.wbg.__wbg___wbindgen_is_bigint_cb320707dcd35f0b = function(arg0) {
5413
- const ret = typeof getObject(arg0) === "bigint";
5414
- return ret;
5415
- };
5416
- imports.wbg.__wbg___wbindgen_is_function_ee8a6c5833c90377 = function(arg0) {
5417
- const ret = typeof getObject(arg0) === "function";
5418
- return ret;
5419
- };
5420
- imports.wbg.__wbg___wbindgen_is_object_c818261d21f283a4 = function(arg0) {
5421
- const val = getObject(arg0);
5422
- const ret = typeof val === "object" && val !== null;
5423
- return ret;
5424
- };
5425
- imports.wbg.__wbg___wbindgen_is_string_fbb76cb2940daafd = function(arg0) {
5426
- const ret = typeof getObject(arg0) === "string";
5427
- return ret;
5428
- };
5429
- imports.wbg.__wbg___wbindgen_is_undefined_2d472862bd29a478 = function(arg0) {
5430
- const ret = getObject(arg0) === void 0;
5431
- return ret;
5432
- };
5433
- imports.wbg.__wbg___wbindgen_jsval_eq_6b13ab83478b1c50 = function(arg0, arg1) {
5434
- const ret = getObject(arg0) === getObject(arg1);
5435
- return ret;
5436
- };
5437
- imports.wbg.__wbg___wbindgen_jsval_loose_eq_b664b38a2f582147 = function(arg0, arg1) {
5438
- const ret = getObject(arg0) == getObject(arg1);
5439
- return ret;
5440
- };
5441
- imports.wbg.__wbg___wbindgen_number_get_a20bf9b85341449d = function(arg0, arg1) {
5442
- const obj = getObject(arg1);
5443
- const ret = typeof obj === "number" ? obj : void 0;
5444
- getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);
5445
- getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
5446
- };
5447
- imports.wbg.__wbg___wbindgen_string_get_e4f06c90489ad01b = function(arg0, arg1) {
5448
- const obj = getObject(arg1);
5449
- const ret = typeof obj === "string" ? obj : void 0;
5450
- var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2);
5451
- var len1 = WASM_VECTOR_LEN;
5452
- getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
5453
- getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
5454
- };
5455
- imports.wbg.__wbg___wbindgen_throw_b855445ff6a94295 = function(arg0, arg1) {
5456
- throw new Error(getStringFromWasm0(arg0, arg1));
5457
- };
5458
- imports.wbg.__wbg_call_e762c39fa8ea36bf = function() {
5459
- return handleError(function(arg0, arg1) {
5460
- const ret = getObject(arg0).call(getObject(arg1));
5461
- return addHeapObject(ret);
5462
- }, arguments);
5463
- };
5464
- imports.wbg.__wbg_done_2042aa2670fb1db1 = function(arg0) {
5465
- const ret = getObject(arg0).done;
5466
- return ret;
5467
- };
5468
- imports.wbg.__wbg_entries_e171b586f8f6bdbf = function(arg0) {
5469
- const ret = Object.entries(getObject(arg0));
5470
- return addHeapObject(ret);
5471
- };
5472
- imports.wbg.__wbg_get_7bed016f185add81 = function(arg0, arg1) {
5473
- const ret = getObject(arg0)[arg1 >>> 0];
5474
- return addHeapObject(ret);
5475
- };
5476
- imports.wbg.__wbg_get_efcb449f58ec27c2 = function() {
5477
- return handleError(function(arg0, arg1) {
5478
- const ret = Reflect.get(getObject(arg0), getObject(arg1));
5479
- return addHeapObject(ret);
5480
- }, arguments);
5481
- };
5482
- imports.wbg.__wbg_get_with_ref_key_1dc361bd10053bfe = function(arg0, arg1) {
5483
- const ret = getObject(arg0)[getObject(arg1)];
5484
- return addHeapObject(ret);
5485
- };
5486
- imports.wbg.__wbg_instanceof_ArrayBuffer_70beb1189ca63b38 = function(arg0) {
5487
- let result;
5488
- try {
5489
- result = getObject(arg0) instanceof ArrayBuffer;
5490
- } catch (_) {
5491
- result = false;
5492
- }
5493
- const ret = result;
5494
- return ret;
5495
- };
5496
- imports.wbg.__wbg_instanceof_Map_8579b5e2ab5437c7 = function(arg0) {
5497
- let result;
5498
- try {
5499
- result = getObject(arg0) instanceof Map;
5500
- } catch (_) {
5501
- result = false;
5502
- }
5503
- const ret = result;
5504
- return ret;
5505
- };
5506
- imports.wbg.__wbg_instanceof_Uint8Array_20c8e73002f7af98 = function(arg0) {
5507
- let result;
5508
- try {
5509
- result = getObject(arg0) instanceof Uint8Array;
5510
- } catch (_) {
5511
- result = false;
5512
- }
5513
- const ret = result;
5514
- return ret;
5515
- };
5516
- imports.wbg.__wbg_isArray_96e0af9891d0945d = function(arg0) {
5517
- const ret = Array.isArray(getObject(arg0));
5518
- return ret;
5519
- };
5520
- imports.wbg.__wbg_isSafeInteger_d216eda7911dde36 = function(arg0) {
5521
- const ret = Number.isSafeInteger(getObject(arg0));
5522
- return ret;
5523
- };
5524
- imports.wbg.__wbg_iterator_e5822695327a3c39 = function() {
5525
- const ret = Symbol.iterator;
5526
- return addHeapObject(ret);
5527
- };
5528
- imports.wbg.__wbg_length_69bca3cb64fc8748 = function(arg0) {
5529
- const ret = getObject(arg0).length;
5530
- return ret;
5531
- };
5532
- imports.wbg.__wbg_length_cdd215e10d9dd507 = function(arg0) {
5533
- const ret = getObject(arg0).length;
5534
- return ret;
5535
- };
5536
- imports.wbg.__wbg_new_1acc0b6eea89d040 = function() {
5537
- const ret = new Object();
5538
- return addHeapObject(ret);
5539
- };
5540
- imports.wbg.__wbg_new_5a79be3ab53b8aa5 = function(arg0) {
5541
- const ret = new Uint8Array(getObject(arg0));
5542
- return addHeapObject(ret);
5543
- };
5544
- imports.wbg.__wbg_new_68651c719dcda04e = function() {
5545
- const ret = /* @__PURE__ */ new Map();
5546
- return addHeapObject(ret);
5547
- };
5548
- imports.wbg.__wbg_new_e17d9f43105b08be = function() {
5549
- const ret = new Array();
5550
- return addHeapObject(ret);
5551
- };
5552
- imports.wbg.__wbg_next_020810e0ae8ebcb0 = function() {
5553
- return handleError(function(arg0) {
5554
- const ret = getObject(arg0).next();
5555
- return addHeapObject(ret);
5556
- }, arguments);
5557
- };
5558
- imports.wbg.__wbg_next_2c826fe5dfec6b6a = function(arg0) {
5559
- const ret = getObject(arg0).next;
5560
- return addHeapObject(ret);
5561
- };
5562
- imports.wbg.__wbg_prototypesetcall_2a6620b6922694b2 = function(arg0, arg1, arg2) {
5563
- Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), getObject(arg2));
5564
- };
5565
- imports.wbg.__wbg_set_3f1d0b984ed272ed = function(arg0, arg1, arg2) {
5566
- getObject(arg0)[takeObject(arg1)] = takeObject(arg2);
5567
- };
5568
- imports.wbg.__wbg_set_907fb406c34a251d = function(arg0, arg1, arg2) {
5569
- const ret = getObject(arg0).set(getObject(arg1), getObject(arg2));
5570
- return addHeapObject(ret);
5571
- };
5572
- imports.wbg.__wbg_set_c213c871859d6500 = function(arg0, arg1, arg2) {
5573
- getObject(arg0)[arg1 >>> 0] = takeObject(arg2);
5574
- };
5575
- imports.wbg.__wbg_value_692627309814bb8c = function(arg0) {
5576
- const ret = getObject(arg0).value;
5577
- return addHeapObject(ret);
5578
- };
5579
- imports.wbg.__wbindgen_cast_2241b6af4c4b2941 = function(arg0, arg1) {
5580
- const ret = getStringFromWasm0(arg0, arg1);
5581
- return addHeapObject(ret);
5582
- };
5583
- imports.wbg.__wbindgen_cast_4625c577ab2ec9ee = function(arg0) {
5584
- const ret = BigInt.asUintN(64, arg0);
5585
- return addHeapObject(ret);
5586
- };
5587
- imports.wbg.__wbindgen_cast_9ae0607507abb057 = function(arg0) {
5588
- const ret = arg0;
5589
- return addHeapObject(ret);
5590
- };
5591
- imports.wbg.__wbindgen_cast_d6cd19b81560fd6e = function(arg0) {
5592
- const ret = arg0;
5593
- return addHeapObject(ret);
5594
- };
5595
- imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
5596
- const ret = getObject(arg0);
5597
- return addHeapObject(ret);
5598
- };
5599
- imports.wbg.__wbindgen_object_drop_ref = function(arg0) {
5600
- takeObject(arg0);
5601
- };
5602
- return imports;
5603
- }
5604
- function __wbg_finalize_init(instance, module) {
5605
- wasm = instance.exports;
5606
- cachedDataViewMemory0 = null;
5607
- cachedUint8ArrayMemory0 = null;
5608
- return wasm;
5609
- }
5610
- function initSync(module) {
5611
- if (wasm !== void 0) return wasm;
5612
- if (typeof module !== "undefined") {
5613
- if (Object.getPrototypeOf(module) === Object.prototype) {
5614
- ({ module } = module);
5615
- } else {
5616
- console.warn("using deprecated parameters for `initSync()`; pass a single object instead");
5617
- }
5618
- }
5619
- const imports = __wbg_get_imports();
5620
- if (!(module instanceof WebAssembly.Module)) {
5621
- module = new WebAssembly.Module(module);
5622
- }
5623
- const instance = new WebAssembly.Instance(module, imports);
5624
- return __wbg_finalize_init(instance);
5625
- }
5626
- var wasm;
5627
- var cachedUint8ArrayMemory0;
5628
- var cachedTextDecoder;
5629
- var MAX_SAFARI_DECODE_BYTES;
5630
- var numBytesDecoded;
5631
- var heap;
5632
- var heap_next;
5633
- var WASM_VECTOR_LEN;
5634
- var cachedTextEncoder;
5635
- var cachedDataViewMemory0;
5636
- var kya_os_engine_default;
5637
- var BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "metadata", "metadata.google.internal"]);
5638
- var UnsafeOutboundUrl = class extends Error {
5639
- kind = "UnsafeOutboundUrl";
5640
- };
5641
- function assertSafeHttpsUrl(rawUrl, label = "outbound URL") {
5642
- let parsed;
5643
- try {
5644
- parsed = new URL(rawUrl);
5645
- } catch {
5646
- throw new UnsafeOutboundUrl(`${label} must be a valid URL: ${rawUrl}`);
5647
- }
5648
- if (parsed.protocol !== "https:") {
5649
- throw new UnsafeOutboundUrl(`${label} must use https: ${rawUrl}`);
5650
- }
5651
- if (parsed.username || parsed.password) {
5652
- throw new UnsafeOutboundUrl(`${label} must not contain credentials: ${rawUrl}`);
5653
- }
5654
- const hostname = normalizeHostname(parsed.hostname);
5655
- if (!hostname || isBlockedHostname(hostname)) {
5656
- throw new UnsafeOutboundUrl(`${label} targets a local or private host: ${rawUrl}`);
5657
- }
5658
- return rawUrl;
5659
- }
5660
- function normalizeHostname(hostname) {
5661
- let normalized = hostname.trim().toLowerCase();
5662
- if (normalized.startsWith("[") && normalized.endsWith("]")) {
5663
- normalized = normalized.slice(1, -1);
5664
- }
5665
- while (normalized.endsWith(".")) {
5666
- normalized = normalized.slice(0, -1);
5667
- }
5668
- return normalized;
5669
- }
5670
- function isBlockedHostname(hostname) {
5671
- if (BLOCKED_HOSTNAMES.has(hostname) || hostname.endsWith(".localhost")) {
5672
- return true;
5673
- }
5674
- const ipv4 = parseIpv4(hostname);
5675
- if (ipv4) {
5676
- return isBlockedIpv4(ipv4);
5677
- }
5678
- return isBlockedIpv6(hostname);
5679
- }
5680
- function parseIpv4(hostname) {
5681
- const parts = hostname.split(".");
5682
- if (parts.length !== 4) return null;
5683
- const octets = parts.map((part) => {
5684
- if (!/^\d{1,3}$/.test(part)) return Number.NaN;
5685
- const value = Number(part);
5686
- return value >= 0 && value <= 255 ? value : Number.NaN;
5687
- });
5688
- if (octets.some(Number.isNaN)) return null;
5689
- return octets;
5690
- }
5691
- function isBlockedIpv4([a, b]) {
5692
- return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a >= 224;
5693
- }
5694
- function isBlockedIpv6(hostname) {
5695
- if (!hostname.includes(":")) return false;
5696
- const ipv4Mapped = hostname.match(/(?:^|:)ffff:(\d{1,3}(?:\.\d{1,3}){3})$/);
5697
- if (ipv4Mapped) {
5698
- const ipv4 = parseIpv4(ipv4Mapped[1]);
5699
- return ipv4 ? isBlockedIpv4(ipv4) : true;
5700
- }
5701
- if (hostname === "::" || hostname === "::1" || hostname === "0:0:0:0:0:0:0:1") {
5702
- return true;
5703
- }
5704
- const firstSegment = Number.parseInt(hostname.split(":")[0] || "0", 16);
5705
- if (Number.isNaN(firstSegment)) return true;
5706
- return (firstSegment & 65024) === 64512 || // unique local fc00::/7
5707
- (firstSegment & 65472) === 65152 || // link-local fe80::/10
5708
- (firstSegment & 65280) === 65280;
5709
- }
5710
- function engineVerify(input, ctx) {
5711
- const result = (void 0)(input, ctx);
5712
- return result;
5713
- }
5714
- function base64UrlDecode(input) {
5715
- const padded = input.replace(/-/g, "+").replace(/_/g, "/");
5716
- const padding = padded.length % 4 === 0 ? "" : "=".repeat(4 - padded.length % 4);
5717
- return new Uint8Array(Buffer.from(padded + padding, "base64"));
5718
- }
5719
- function buildAgentRequest(req, opts = {}) {
5720
- const mcpI = tryBuildMcpIFromBody(req);
5721
- if (mcpI) {
5722
- return { protocol: "McpI", request: mcpI };
5723
- }
5724
- if (opts.legacyEnvelopeFallback) {
5725
- const legacyMcpI = tryBuildMcpIFromLegacyHeader(req);
5726
- if (legacyMcpI) {
5727
- return { protocol: "McpI", request: legacyMcpI };
5728
- }
5729
- }
5730
- if (getHeader(req, "signature-input")) {
5731
- return { protocol: "HttpSigned", request: buildHttpSigned(req) };
5732
- }
5733
- return { protocol: "PlainHttp", request: buildPlainHttp(req) };
5734
- }
5735
- function hasMalformedJwsBody(req) {
5736
- const parsed = parseBodyAsObject(req.body);
5737
- if (!parsed || typeof parsed !== "object") return false;
5738
- const meta = parsed._meta;
5739
- if (!meta || typeof meta !== "object") return false;
5740
- const proof = meta.proof;
5741
- if (!proof || typeof proof !== "object") return false;
5742
- const jws = proof.jws;
5743
- if (typeof jws !== "string" || jws.length === 0) return false;
5744
- const raw = Array.from(Buffer.from(jws, "utf8"));
5745
- return parseJwsPayloadStruct(raw) === null;
5746
- }
5747
- function extractIssuer(request) {
5748
- if (request.protocol === "McpI") return request.request.payload.iss || null;
5749
- return null;
5750
- }
5751
- function extractAgentDid(request) {
5752
- if (request.protocol === "McpI") return request.request.payload.sub || null;
5753
- return null;
5754
- }
5755
- function extractCredentialStatusUrl(request) {
5756
- if (request.protocol !== "McpI") return null;
5757
- const raw = decodeJwsPayloadJson(request.request.raw);
5758
- if (!raw) return null;
5759
- const vc = raw.vc;
5760
- if (!vc || typeof vc !== "object") return null;
5761
- const credentialStatus = vc.credentialStatus;
5762
- if (!credentialStatus || typeof credentialStatus !== "object") return null;
5763
- const id = credentialStatus.id;
5764
- return typeof id === "string" ? id : null;
5765
- }
5766
- function tryBuildMcpIFromBody(req) {
5767
- const parsed = parseBodyAsObject(req.body);
5768
- if (!parsed) return null;
5769
- const meta = parsed._meta;
5770
- if (!meta || typeof meta !== "object") return null;
5771
- const proof = meta.proof;
5772
- if (!proof || typeof proof !== "object") return null;
5773
- const jws = proof.jws;
5774
- if (typeof jws !== "string" || jws.length === 0) return null;
5775
- const raw = Array.from(Buffer.from(jws, "utf8"));
5776
- const payload = parseJwsPayloadStruct(raw);
5777
- if (!payload) return null;
5778
- return { raw, payload };
5779
- }
5780
- function parseBodyAsObject(body) {
5781
- if (!body) return null;
5782
- if (Buffer.isBuffer(body)) {
5783
- try {
5784
- return JSON.parse(body.toString("utf8"));
5785
- } catch {
5786
- return null;
5787
- }
5788
- }
5789
- if (typeof body === "string") {
5790
- try {
5791
- return JSON.parse(body);
5792
- } catch {
5793
- return null;
5794
- }
5795
- }
5796
- if (typeof body === "object") return body;
5797
- return null;
5798
- }
5799
- function tryBuildMcpIFromLegacyHeader(req) {
5800
- const header = getHeader(req, "kya-delegation");
5801
- if (!header) return null;
5802
- let parsed;
5803
- try {
5804
- parsed = JSON.parse(header);
5805
- } catch {
5806
- return null;
5807
- }
5808
- if (!parsed || typeof parsed !== "object") return null;
5809
- const obj = parsed;
5810
- const protectedSeg = obj.protected;
5811
- const payloadSeg = obj.payload;
5812
- const signatureSeg = obj.signature;
5813
- if (typeof protectedSeg !== "string" || typeof payloadSeg !== "string" || typeof signatureSeg !== "string") {
5814
- return null;
5815
- }
5816
- const compact = `${protectedSeg}.${payloadSeg}.${signatureSeg}`;
5817
- const raw = Array.from(Buffer.from(compact, "utf8"));
5818
- const payload = parseJwsPayloadStruct(raw);
5819
- if (!payload) return null;
5820
- return { raw, payload };
5821
- }
5822
- function parseJwsPayloadStruct(rawBytes) {
5823
- const json = decodeJwsPayloadJson(rawBytes);
5824
- if (!json || typeof json !== "object") return null;
5825
- return projectMcpIPayload(json);
5826
- }
5827
- function decodeJwsPayloadJson(rawBytes) {
5828
- const text = Buffer.from(rawBytes).toString("utf8");
5829
- const segments = text.split(".");
5830
- if (segments.length !== 3) return null;
5831
- let decoded;
5832
- try {
5833
- decoded = base64UrlDecode(segments[1]);
5834
- } catch {
5835
- return null;
5836
- }
5837
- try {
5838
- return JSON.parse(Buffer.from(decoded).toString("utf8"));
5839
- } catch {
5840
- return null;
5841
- }
5842
- }
5843
- function projectMcpIPayload(raw) {
5844
- const aud = raw.aud;
5845
- const iss = raw.iss;
5846
- const sub = raw.sub;
5847
- const nonce = raw.nonce;
5848
- const sessionId = raw.sessionId;
5849
- const ts = raw.ts;
5850
- const requestHash = raw.requestHash;
5851
- const responseHash = raw.responseHash;
5852
- if (typeof aud !== "string" || typeof iss !== "string" || typeof sub !== "string" || typeof nonce !== "string" || typeof sessionId !== "string" || typeof ts !== "number" || typeof requestHash !== "string" || typeof responseHash !== "string") {
5853
- return null;
5854
- }
5855
- return { aud, iss, sub, nonce, sessionId, ts, requestHash, responseHash };
5856
- }
5857
- function buildHttpSigned(req) {
5858
- return {
5859
- raw: bodyAsBytes(req.body),
5860
- method: req.method,
5861
- path: req.url,
5862
- headers: flattenHeaders(req.headers)
5863
- };
5864
- }
5865
- function buildPlainHttp(req) {
5866
- return {
5867
- raw: bodyAsBytes(req.body),
5868
- method: req.method,
5869
- path: req.url,
5870
- headers: flattenHeaders(req.headers),
5871
- userAgent: getHeader(req, "user-agent") ?? null,
5872
- remoteIp: req.remoteAddress ?? null
5873
- };
5874
- }
5875
- function getHeader(req, name) {
5876
- const lowered = name.toLowerCase();
5877
- for (const [key, value] of Object.entries(req.headers)) {
5878
- if (key.toLowerCase() !== lowered) continue;
5879
- if (Array.isArray(value)) return value[0] ?? null;
5880
- if (typeof value === "string") return value;
5881
- }
5882
- return null;
5883
- }
5884
- function flattenHeaders(headers) {
5885
- const out = [];
5886
- for (const [key, value] of Object.entries(headers)) {
5887
- if (value === void 0) continue;
5888
- if (Array.isArray(value)) {
5889
- for (const v of value) out.push([key, v]);
5890
- } else {
5891
- out.push([key, value]);
5892
- }
5893
- }
5894
- return out;
5895
- }
5896
- function bodyAsBytes(body) {
5897
- if (!body) return [];
5898
- if (Buffer.isBuffer(body)) return Array.from(body);
5899
- if (typeof body === "string") return Array.from(Buffer.from(body, "utf8"));
5900
- if (typeof body === "object") return Array.from(Buffer.from(JSON.stringify(body), "utf8"));
5901
- return [];
5902
- }
5903
- var DEFAULT_REPUTATION_BASELINE = 1;
5904
- async function verifyRequest(req, opts) {
5905
- return verifyRequest_internal(req, opts);
5906
- }
5907
- async function verifyRequest_internal(req, opts) {
5908
- if (hasMalformedJwsBody(req)) {
5909
- return blockWithParseError("malformed JWS body", opts.enforcementMode);
5910
- }
5911
- const agentRequest = buildAgentRequest(req, {
5912
- legacyEnvelopeFallback: opts.legacyEnvelopeFallback
5913
- });
5914
- const issuer = extractIssuer(agentRequest);
5915
- const agentDid = extractAgentDid(agentRequest);
5916
- const credentialStatusUrl = extractCredentialStatusUrl(agentRequest);
5917
- const baseline = opts.reputationBaseline ?? DEFAULT_REPUTATION_BASELINE;
5918
- const [didResult, statusResult, repResult] = await Promise.allSettled([
5919
- issuer ? opts.didResolver.resolve(issuer) : Promise.resolve(null),
5920
- credentialStatusUrl ? fetchCredentialStatus(credentialStatusUrl, opts.statusListCache) : Promise.resolve(null),
5921
- agentDid ? opts.reputationOracle.score(agentDid) : Promise.resolve(baseline)
5922
- ]);
5923
- if (didResult.status === "rejected") {
5924
- if (isDidResolverError(didResult.reason)) {
5925
- return blockWithParseError(
5926
- didResult.reason instanceof Error ? didResult.reason.message : String(didResult.reason),
5927
- opts.enforcementMode
5928
- );
5929
- }
5930
- throw didResult.reason;
5931
- }
5932
- if (statusResult.status === "rejected") {
5933
- if (statusResult.reason instanceof UnsafeOutboundUrl) {
5934
- return blockWithParseError(statusResult.reason.message, opts.enforcementMode);
5935
- }
5936
- throw statusResult.reason;
5937
- }
5938
- if (repResult.status === "rejected") {
5939
- throw repResult.reason;
5940
- }
5941
- const didDoc = didResult.value;
5942
- const revokedIndices = statusResult.value;
5943
- const repScore = repResult.value;
5944
- const tenantDecision = await opts.policyEvaluator.evaluate({
5945
- tenantHost: opts.tenantHost,
5946
- reputation: repScore
5947
- });
5948
- const ctx = {
5949
- didDocs: didDoc && issuer ? { [issuer]: didDoc } : {},
5950
- revoked: revokedIndices !== null && credentialStatusUrl ? { [credentialStatusUrl]: revokedIndices } : {},
5951
- reputation: agentDid ? { [agentDid]: repScore } : {},
5952
- tenantDecision,
5953
- nowUnix: opts.clock.nowUnix(),
5954
- enforcementMode: opts.enforcementMode
5955
- };
5956
- return engineVerify(agentRequest, ctx);
5957
- }
5958
- async function fetchCredentialStatus(credentialStatusUrl, statusListCache) {
5959
- assertSafeHttpsUrl(credentialStatusUrl, "credential status URL");
5960
- return statusListCache.fetch(credentialStatusUrl);
5961
- }
5962
- function isDidResolverError(err) {
5963
- if (!(err instanceof Error)) return false;
5964
- const kind = err.kind;
5965
- return kind === "DidNotFound" || kind === "DidResolverTimeout" || kind === "DidResolverError" || kind === "MalformedDid" || kind === "UnsupportedKeyType" || kind === "UnsupportedDidMethod";
5966
- }
5967
- function blockWithParseError(detail, enforcementMode) {
5968
- return {
5969
- decision: {
5970
- kind: "Block",
5971
- reason: {
5972
- kind: "ParseError",
5973
- detail
5974
- }
5975
- },
5976
- enforcementMode,
5977
- engineInfo: {
5978
- name: "checkpoint-engine-wasm",
5979
- version: "0.0.0-host-synth",
5980
- rulesetHash: "sha256:host-synthesized",
5981
- rulesetVersion: "0.0.0-host-synth",
5982
- extras: { synthesized: true }
5983
- }
5984
- };
5985
- }
5986
- function renderDecisionAsResponse(result) {
5987
- const baseHeaders = buildBaseHeaders(result);
5988
- if (result.enforcementMode === "observe") {
5989
- return {
5990
- status: null,
5991
- headers: {
5992
- ...baseHeaders,
5993
- "X-Checkpoint-Mode": "observe",
5994
- "X-Checkpoint-Would-Have-Been": result.decision.kind,
5995
- ...wouldHaveBeenReasonHeader(result)
5996
- }
5997
- };
5998
- }
5999
- switch (result.decision.kind) {
6000
- case "Permit":
6001
- return {
6002
- status: null,
6003
- headers: { ...baseHeaders, "X-Checkpoint-Decision": "permit" }
6004
- };
6005
- case "Block": {
6006
- const reason = result.decision.reason;
6007
- return {
6008
- status: httpStatusForBlockReason(reason),
6009
- headers: {
6010
- ...baseHeaders,
6011
- ...blockHeaders(reason),
6012
- "X-Checkpoint-Decision": "block",
6013
- "X-Checkpoint-Reason": reason.kind
6014
- },
6015
- body: blockResponseBody(reason)
6016
- };
6017
- }
6018
- case "Challenge": {
6019
- const params = result.decision.params;
6020
- return {
6021
- status: 401,
6022
- headers: {
6023
- ...baseHeaders,
6024
- "X-Checkpoint-Decision": "challenge",
6025
- "X-Checkpoint-Challenge": params.nonce
6026
- },
6027
- body: {
6028
- challenge: params
6029
- }
6030
- };
6031
- }
6032
- case "Redirect": {
6033
- const target = result.decision.target;
6034
- return {
6035
- status: 302,
6036
- headers: {
6037
- ...baseHeaders,
6038
- "X-Checkpoint-Decision": "redirect",
6039
- Location: target.url,
6040
- "X-Checkpoint-Redirect-Reason": target.reason
6041
- }
6042
- };
6043
- }
6044
- case "Instruct": {
6045
- const payload = result.decision.payload;
6046
- return {
6047
- status: 422,
6048
- headers: {
6049
- ...baseHeaders,
6050
- "X-Checkpoint-Decision": "instruct",
6051
- "Content-Type": "application/problem+json"
6052
- },
6053
- body: {
6054
- type: payload.problem,
6055
- title: payload.title,
6056
- suggestedActions: payload.suggestedActions
6057
- }
6058
- };
6059
- }
6060
- }
6061
- }
6062
- function buildBaseHeaders(result) {
6063
- const headers = {
6064
- "X-Checkpoint-Engine": result.engineInfo.name,
6065
- "X-Checkpoint-Engine-Version": result.engineInfo.version
6066
- };
6067
- if (result.engineInfo.rulesetHash) {
6068
- headers["X-Checkpoint-Ruleset-Hash"] = result.engineInfo.rulesetHash;
6069
- }
6070
- return headers;
6071
- }
6072
- function httpStatusForBlockReason(reason) {
6073
- switch (reason.kind) {
6074
- case "Unauthenticated":
6075
- case "Expired":
6076
- return 401;
6077
- case "ParseError":
6078
- return 400;
6079
- case "InvalidSignature":
6080
- case "Revoked":
6081
- case "OutOfScope":
6082
- case "LowReputation":
6083
- case "PolicyDenied":
6084
- return 403;
6085
- }
6086
- }
6087
- function blockHeaders(reason) {
6088
- if (reason.kind === "Unauthenticated") {
6089
- return { "WWW-Authenticate": 'KyaProof realm="checkpoint"' };
6090
- }
6091
- return {};
6092
- }
6093
- function blockResponseBody(reason) {
6094
- switch (reason.kind) {
6095
- case "Revoked":
6096
- case "InvalidSignature":
6097
- case "Unauthenticated":
6098
- case "Expired":
6099
- return { error: humanError(reason.kind), reason: reason.kind };
6100
- case "OutOfScope":
6101
- return {
6102
- error: "requested scope is not granted",
6103
- reason: "OutOfScope",
6104
- requested: reason.requested,
6105
- granted: reason.granted
6106
- };
6107
- case "LowReputation":
6108
- return {
6109
- error: "agent reputation below tenant threshold",
6110
- reason: "LowReputation",
6111
- score: reason.score,
6112
- threshold: reason.threshold
6113
- };
6114
- case "PolicyDenied":
6115
- return {
6116
- error: "tenant policy denied the request",
6117
- reason: "PolicyDenied",
6118
- detail: reason.detail
6119
- };
6120
- case "ParseError":
6121
- return {
6122
- error: "request envelope could not be parsed",
6123
- reason: "ParseError",
6124
- detail: reason.detail
6125
- };
6126
- }
6127
- }
6128
- function humanError(kind) {
6129
- switch (kind) {
6130
- case "Revoked":
6131
- return "credential has been revoked";
6132
- case "InvalidSignature":
6133
- return "request signature failed verification";
6134
- case "Unauthenticated":
6135
- return "authentication required";
6136
- case "Expired":
6137
- return "credential is expired";
6138
- }
6139
- }
6140
- function wouldHaveBeenReasonHeader(result) {
6141
- if (result.decision.kind === "Block") {
6142
- return { "X-Checkpoint-Would-Have-Been-Reason": result.decision.reason.kind };
6143
- }
6144
- return {};
6145
- }
6146
- function coerce(o) {
6147
- if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") {
6148
- return o;
6149
- }
6150
- if (o instanceof ArrayBuffer) {
6151
- return new Uint8Array(o);
6152
- }
6153
- if (ArrayBuffer.isView(o)) {
6154
- return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
6155
- }
6156
- throw new Error("Unknown type, must be binary type");
6157
- }
6158
-
6159
- // ../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/vendor/base-x.js
6160
- function base(ALPHABET, name) {
6161
- if (ALPHABET.length >= 255) {
6162
- throw new TypeError("Alphabet too long");
6163
- }
6164
- var BASE_MAP = new Uint8Array(256);
6165
- for (var j = 0; j < BASE_MAP.length; j++) {
6166
- BASE_MAP[j] = 255;
6167
- }
6168
- for (var i = 0; i < ALPHABET.length; i++) {
6169
- var x = ALPHABET.charAt(i);
6170
- var xc = x.charCodeAt(0);
6171
- if (BASE_MAP[xc] !== 255) {
6172
- throw new TypeError(x + " is ambiguous");
6173
- }
6174
- BASE_MAP[xc] = i;
6175
- }
6176
- var BASE = ALPHABET.length;
6177
- var LEADER = ALPHABET.charAt(0);
6178
- var FACTOR = Math.log(BASE) / Math.log(256);
6179
- var iFACTOR = Math.log(256) / Math.log(BASE);
6180
- function encode(source) {
6181
- if (source instanceof Uint8Array)
6182
- ;
6183
- else if (ArrayBuffer.isView(source)) {
6184
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
6185
- } else if (Array.isArray(source)) {
6186
- source = Uint8Array.from(source);
6187
- }
6188
- if (!(source instanceof Uint8Array)) {
6189
- throw new TypeError("Expected Uint8Array");
6190
- }
6191
- if (source.length === 0) {
6192
- return "";
6193
- }
6194
- var zeroes = 0;
6195
- var length = 0;
6196
- var pbegin = 0;
6197
- var pend = source.length;
6198
- while (pbegin !== pend && source[pbegin] === 0) {
6199
- pbegin++;
6200
- zeroes++;
6201
- }
6202
- var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
6203
- var b58 = new Uint8Array(size);
6204
- while (pbegin !== pend) {
6205
- var carry = source[pbegin];
6206
- var i2 = 0;
6207
- for (var it1 = size - 1; (carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++) {
6208
- carry += 256 * b58[it1] >>> 0;
6209
- b58[it1] = carry % BASE >>> 0;
6210
- carry = carry / BASE >>> 0;
6211
- }
6212
- if (carry !== 0) {
6213
- throw new Error("Non-zero carry");
6214
- }
6215
- length = i2;
6216
- pbegin++;
6217
- }
6218
- var it2 = size - length;
6219
- while (it2 !== size && b58[it2] === 0) {
6220
- it2++;
6221
- }
6222
- var str = LEADER.repeat(zeroes);
6223
- for (; it2 < size; ++it2) {
6224
- str += ALPHABET.charAt(b58[it2]);
6225
- }
6226
- return str;
6227
- }
6228
- function decodeUnsafe(source) {
6229
- if (typeof source !== "string") {
6230
- throw new TypeError("Expected String");
6231
- }
6232
- if (source.length === 0) {
6233
- return new Uint8Array();
6234
- }
6235
- var psz = 0;
6236
- if (source[psz] === " ") {
6237
- return;
6238
- }
6239
- var zeroes = 0;
6240
- var length = 0;
6241
- while (source[psz] === LEADER) {
6242
- zeroes++;
6243
- psz++;
6244
- }
6245
- var size = (source.length - psz) * FACTOR + 1 >>> 0;
6246
- var b256 = new Uint8Array(size);
6247
- while (source[psz]) {
6248
- var carry = BASE_MAP[source.charCodeAt(psz)];
6249
- if (carry === 255) {
6250
- return;
6251
- }
6252
- var i2 = 0;
6253
- for (var it3 = size - 1; (carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++) {
6254
- carry += BASE * b256[it3] >>> 0;
6255
- b256[it3] = carry % 256 >>> 0;
6256
- carry = carry / 256 >>> 0;
6257
- }
6258
- if (carry !== 0) {
6259
- throw new Error("Non-zero carry");
6260
- }
6261
- length = i2;
6262
- psz++;
6263
- }
6264
- if (source[psz] === " ") {
6265
- return;
6266
- }
6267
- var it4 = size - length;
6268
- while (it4 !== size && b256[it4] === 0) {
6269
- it4++;
6270
- }
6271
- var vch = new Uint8Array(zeroes + (size - it4));
6272
- var j2 = zeroes;
6273
- while (it4 !== size) {
6274
- vch[j2++] = b256[it4++];
6275
- }
6276
- return vch;
6277
- }
6278
- function decode2(string) {
6279
- var buffer = decodeUnsafe(string);
6280
- if (buffer) {
6281
- return buffer;
6282
- }
6283
- throw new Error(`Non-${name} character`);
6284
- }
6285
- return {
6286
- encode,
6287
- decodeUnsafe,
6288
- decode: decode2
6289
- };
6290
- }
6291
- var src = base;
6292
- var _brrp__multiformats_scope_baseX = src;
6293
- var base_x_default = _brrp__multiformats_scope_baseX;
6294
-
6295
- // ../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base.js
6296
- var Encoder = class {
6297
- name;
6298
- prefix;
6299
- baseEncode;
6300
- constructor(name, prefix, baseEncode) {
6301
- this.name = name;
6302
- this.prefix = prefix;
6303
- this.baseEncode = baseEncode;
6304
- }
6305
- encode(bytes) {
6306
- if (bytes instanceof Uint8Array) {
6307
- return `${this.prefix}${this.baseEncode(bytes)}`;
6308
- } else {
6309
- throw Error("Unknown type, must be binary type");
6310
- }
6311
- }
6312
- };
6313
- var Decoder = class {
6314
- name;
6315
- prefix;
6316
- baseDecode;
6317
- prefixCodePoint;
6318
- constructor(name, prefix, baseDecode) {
6319
- this.name = name;
6320
- this.prefix = prefix;
6321
- const prefixCodePoint = prefix.codePointAt(0);
6322
- if (prefixCodePoint === void 0) {
6323
- throw new Error("Invalid prefix character");
6324
- }
6325
- this.prefixCodePoint = prefixCodePoint;
6326
- this.baseDecode = baseDecode;
6327
- }
6328
- decode(text) {
6329
- if (typeof text === "string") {
6330
- if (text.codePointAt(0) !== this.prefixCodePoint) {
6331
- throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
6332
- }
6333
- return this.baseDecode(text.slice(this.prefix.length));
6334
- } else {
6335
- throw Error("Can only multibase decode strings");
6336
- }
6337
- }
6338
- or(decoder) {
6339
- return or(this, decoder);
6340
- }
6341
- };
6342
- var ComposedDecoder = class {
6343
- decoders;
6344
- constructor(decoders) {
6345
- this.decoders = decoders;
6346
- }
6347
- or(decoder) {
6348
- return or(this, decoder);
6349
- }
6350
- decode(input) {
6351
- const prefix = input[0];
6352
- const decoder = this.decoders[prefix];
6353
- if (decoder != null) {
6354
- return decoder.decode(input);
6355
- } else {
6356
- throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
6357
- }
6358
- }
6359
- };
6360
- function or(left, right) {
6361
- return new ComposedDecoder({
6362
- ...left.decoders ?? { [left.prefix]: left },
6363
- ...right.decoders ?? { [right.prefix]: right }
6364
- });
6365
- }
6366
- var Codec = class {
6367
- name;
6368
- prefix;
6369
- baseEncode;
6370
- baseDecode;
6371
- encoder;
6372
- decoder;
6373
- constructor(name, prefix, baseEncode, baseDecode) {
6374
- this.name = name;
6375
- this.prefix = prefix;
6376
- this.baseEncode = baseEncode;
6377
- this.baseDecode = baseDecode;
6378
- this.encoder = new Encoder(name, prefix, baseEncode);
6379
- this.decoder = new Decoder(name, prefix, baseDecode);
6380
- }
6381
- encode(input) {
6382
- return this.encoder.encode(input);
6383
- }
6384
- decode(input) {
6385
- return this.decoder.decode(input);
6386
- }
6387
- };
6388
- function from({ name, prefix, encode, decode: decode2 }) {
6389
- return new Codec(name, prefix, encode, decode2);
6390
- }
6391
- function baseX({ name, prefix, alphabet }) {
6392
- const { encode, decode: decode2 } = base_x_default(alphabet, name);
6393
- return from({
6394
- prefix,
6395
- name,
6396
- encode,
6397
- decode: (text) => coerce(decode2(text))
6398
- });
6399
- }
6400
-
6401
- // ../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base58.js
6402
- var base58btc = baseX({
6403
- name: "base58btc",
6404
- prefix: "z",
6405
- alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
6406
- });
6407
- baseX({
6408
- name: "base58flickr",
6409
- prefix: "Z",
6410
- alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
6411
- });
6412
- var BLOCKED_HOSTNAMES2 = /* @__PURE__ */ new Set(["localhost", "metadata", "metadata.google.internal"]);
6413
- var UnsafeOutboundUrl2 = class extends Error {
6414
- kind = "UnsafeOutboundUrl";
6415
- };
6416
- function assertSafeHttpsUrl2(rawUrl, label = "outbound URL") {
6417
- let parsed;
6418
- try {
6419
- parsed = new URL(rawUrl);
6420
- } catch {
6421
- throw new UnsafeOutboundUrl2(`${label} must be a valid URL: ${rawUrl}`);
6422
- }
6423
- if (parsed.protocol !== "https:") {
6424
- throw new UnsafeOutboundUrl2(`${label} must use https: ${rawUrl}`);
6425
- }
6426
- if (parsed.username || parsed.password) {
6427
- throw new UnsafeOutboundUrl2(`${label} must not contain credentials: ${rawUrl}`);
6428
- }
6429
- const hostname = normalizeHostname2(parsed.hostname);
6430
- if (!hostname || isBlockedHostname2(hostname)) {
6431
- throw new UnsafeOutboundUrl2(`${label} targets a local or private host: ${rawUrl}`);
6432
- }
6433
- return rawUrl;
6434
- }
6435
- function normalizeHostname2(hostname) {
6436
- let normalized = hostname.trim().toLowerCase();
6437
- if (normalized.startsWith("[") && normalized.endsWith("]")) {
6438
- normalized = normalized.slice(1, -1);
6439
- }
6440
- while (normalized.endsWith(".")) {
6441
- normalized = normalized.slice(0, -1);
6442
- }
6443
- return normalized;
6444
- }
6445
- function isBlockedHostname2(hostname) {
6446
- if (BLOCKED_HOSTNAMES2.has(hostname) || hostname.endsWith(".localhost")) {
6447
- return true;
6448
- }
6449
- const ipv4 = parseIpv42(hostname);
6450
- if (ipv4) {
6451
- return isBlockedIpv42(ipv4);
6452
- }
6453
- return isBlockedIpv62(hostname);
6454
- }
6455
- function parseIpv42(hostname) {
6456
- const parts = hostname.split(".");
6457
- if (parts.length !== 4) return null;
6458
- const octets = parts.map((part) => {
6459
- if (!/^\d{1,3}$/.test(part)) return Number.NaN;
6460
- const value = Number(part);
6461
- return value >= 0 && value <= 255 ? value : Number.NaN;
6462
- });
6463
- if (octets.some(Number.isNaN)) return null;
6464
- return octets;
6465
- }
6466
- function isBlockedIpv42([a, b]) {
6467
- return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a >= 224;
6468
- }
6469
- function isBlockedIpv62(hostname) {
6470
- if (!hostname.includes(":")) return false;
6471
- const ipv4Mapped = hostname.match(/(?:^|:)ffff:(\d{1,3}(?:\.\d{1,3}){3})$/);
6472
- if (ipv4Mapped) {
6473
- const ipv4 = parseIpv42(ipv4Mapped[1]);
6474
- return ipv4 ? isBlockedIpv42(ipv4) : true;
6475
- }
6476
- if (hostname === "::" || hostname === "::1" || hostname === "0:0:0:0:0:0:0:1") {
6477
- return true;
6478
- }
6479
- const firstSegment = Number.parseInt(hostname.split(":")[0] || "0", 16);
6480
- if (Number.isNaN(firstSegment)) return true;
6481
- return (firstSegment & 65024) === 64512 || // unique local fc00::/7
6482
- (firstSegment & 65472) === 65152 || // link-local fe80::/10
6483
- (firstSegment & 65280) === 65280;
6484
- }
6485
- function base64UrlDecode2(input) {
6486
- const padded = input.replace(/-/g, "+").replace(/_/g, "/");
6487
- const padding = padded.length % 4 === 0 ? "" : "=".repeat(4 - padded.length % 4);
6488
- return new Uint8Array(Buffer.from(padded + padding, "base64"));
6489
- }
6490
- var ED25519_PUBLIC_KEY_LENGTH = 32;
6491
- var MalformedDid = class extends Error {
6492
- kind = "MalformedDid";
6493
- };
6494
- var UnsupportedKeyType = class extends Error {
6495
- kind = "UnsupportedKeyType";
6496
- };
6497
- var DidNotFound = class extends Error {
6498
- kind = "DidNotFound";
6499
- };
6500
- var DidResolverTimeout = class extends Error {
6501
- kind = "DidResolverTimeout";
6502
- };
6503
- var DidResolverError = class extends Error {
6504
- kind = "DidResolverError";
6505
- };
6506
- var UnsupportedDidMethod = class extends Error {
6507
- kind = "UnsupportedDidMethod";
6508
- };
6509
- var ED25519_MULTICODEC_PREFIX = [237, 1];
6510
- var DEFAULT_FETCH_TIMEOUT_MS = 3e3;
6511
- var DEFAULT_TTL_MS = 5 * 6e4;
6512
- function makeDidResolver(opts = {}) {
6513
- const timeoutMs = opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
6514
- const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;
6515
- const fetchImpl = opts.fetch ?? fetch;
6516
- const cache = opts.cache ?? /* @__PURE__ */ new Map();
6517
- const now = opts.now ?? (() => Date.now());
6518
- return {
6519
- async resolve(did) {
6520
- const cached = cache.get(did);
6521
- if (cached && now() - cached.fetchedAt < ttlMs) {
6522
- return cached.value;
6523
- }
6524
- if (did.startsWith("did:key:")) {
6525
- const doc = decodeDidKey(did);
6526
- cache.set(did, { value: doc, fetchedAt: now() });
6527
- return doc;
6528
- }
6529
- if (did.startsWith("did:web:")) {
6530
- const doc = await resolveDidWeb(did, fetchImpl, timeoutMs);
6531
- cache.set(did, { value: doc, fetchedAt: now() });
6532
- return doc;
6533
- }
6534
- throw new UnsupportedDidMethod(`Phase 1 supports did:key and did:web only; got: ${did}`);
6535
- }
6536
- };
6537
- }
6538
- function decodeDidKey(did) {
6539
- if (!did.startsWith("did:key:")) {
6540
- throw new MalformedDid(`expected did:key prefix, got: ${did}`);
6541
- }
6542
- const multibaseValue = did.slice("did:key:".length);
6543
- if (!multibaseValue.startsWith("z")) {
6544
- throw new MalformedDid(
6545
- `did:key expects base58btc (multibase 'z' prefix); got: ${multibaseValue[0] ?? "<empty>"}`
6546
- );
6547
- }
6548
- let decoded;
6549
- try {
6550
- decoded = base58btc.decode(multibaseValue);
6551
- } catch (cause) {
6552
- throw new MalformedDid(`did:key multibase decode failed: ${String(cause)}`);
6553
- }
6554
- if (decoded.length < 2 || decoded[0] !== ED25519_MULTICODEC_PREFIX[0] || decoded[1] !== ED25519_MULTICODEC_PREFIX[1]) {
6555
- const prefixHex = decoded.length >= 2 ? `0x${decoded[0].toString(16).padStart(2, "0")}${decoded[1].toString(16).padStart(2, "0")}` : "<too short>";
6556
- throw new UnsupportedKeyType(
6557
- `did:key expects Ed25519 multicodec 0xed01; got ${prefixHex} (only Ed25519 supported in Phase 1)`
6558
- );
6559
- }
6560
- const publicKey = decoded.slice(2);
6561
- if (publicKey.length !== 32) {
6562
- throw new MalformedDid(`did:key Ed25519 public key must be 32 bytes; got ${publicKey.length}`);
6563
- }
6564
- const vm = {
6565
- id: `${did}#${multibaseValue}`,
6566
- // multibase as fragment — mcp-i-core PR #16
6567
- keyType: "Ed25519",
6568
- publicKeyBytes: Array.from(publicKey)
6569
- };
6570
- return {
6571
- id: did,
6572
- verificationMethods: [vm]
6573
- };
6574
- }
6575
- async function resolveDidWeb(did, fetchImpl, timeoutMs) {
6576
- const transformedUrl = didWebToUrl(did);
6577
- let url;
6578
- try {
6579
- url = assertSafeHttpsUrl2(transformedUrl, "did:web resolution URL");
6580
- } catch (cause) {
6581
- if (cause instanceof UnsafeOutboundUrl2) {
6582
- throw new DidResolverError(cause.message);
6583
- }
6584
- throw cause;
6585
- }
6586
- const controller = new AbortController();
6587
- const timer = setTimeout(() => controller.abort(), timeoutMs);
6588
- let response;
6589
- try {
6590
- response = await fetchImpl(url, { signal: controller.signal });
6591
- } catch (cause) {
6592
- if (cause instanceof Error && cause.name === "AbortError") {
6593
- throw new DidResolverTimeout(`did:web fetch timed out after ${timeoutMs}ms: ${url}`);
6594
- }
6595
- throw new DidResolverError(`did:web fetch failed: ${url}: ${String(cause)}`);
6596
- } finally {
6597
- clearTimeout(timer);
6598
- }
6599
- if (response.status === 404) {
6600
- throw new DidNotFound(`no DID document at ${url}`);
6601
- }
6602
- if (!response.ok) {
6603
- throw new DidResolverError(`did:web HTTP ${response.status} at ${url}`);
6604
- }
6605
- let raw;
6606
- try {
6607
- raw = await response.json();
6608
- } catch (cause) {
6609
- throw new DidResolverError(`did:web response not valid JSON at ${url}: ${String(cause)}`);
6610
- }
6611
- return mapW3CDocToEngineShape(raw, did);
6612
- }
6613
- function didWebToUrl(did) {
6614
- const path = did.slice("did:web:".length);
6615
- if (!path) {
6616
- throw new MalformedDid(`did:web with empty path: ${did}`);
6617
- }
6618
- const parts = path.split(":").map((segment) => {
6619
- try {
6620
- return decodeURIComponent(segment);
6621
- } catch {
6622
- throw new MalformedDid(`did:web segment contains invalid percent-encoding: ${segment}`);
6623
- }
6624
- });
6625
- if (parts.length === 1) {
6626
- return `https://${parts[0]}/.well-known/did.json`;
6627
- }
6628
- return `https://${parts[0]}/${parts.slice(1).join("/")}/did.json`;
6629
- }
6630
- function mapW3CDocToEngineShape(raw, requestedDid) {
6631
- if (raw === null || typeof raw !== "object") {
6632
- throw new DidResolverError(`did:web response must be a JSON object`);
6633
- }
6634
- const doc = raw;
6635
- const id = typeof doc.id === "string" ? doc.id : requestedDid;
6636
- const w3cMethods = Array.isArray(doc.verificationMethod) ? doc.verificationMethod : [];
6637
- const verificationMethods = [];
6638
- for (const entry of w3cMethods) {
6639
- if (entry === null || typeof entry !== "object") continue;
6640
- const vm = entry;
6641
- if (!isEd25519Type(vm.type)) continue;
6642
- const vmId = typeof vm.id === "string" ? vm.id : void 0;
6643
- if (!vmId) continue;
6644
- const pubKey = extractEd25519PublicKey(vm);
6645
- if (!pubKey) continue;
6646
- verificationMethods.push({
6647
- id: vmId,
6648
- keyType: "Ed25519",
6649
- publicKeyBytes: Array.from(pubKey)
6650
- });
6651
- }
6652
- return { id, verificationMethods };
6653
- }
6654
- function isEd25519Type(type) {
6655
- return type === "Ed25519VerificationKey2020" || type === "Ed25519VerificationKey2018";
6656
- }
6657
- function extractEd25519PublicKey(vm) {
6658
- if (typeof vm.publicKeyMultibase === "string") {
6659
- const mb = vm.publicKeyMultibase;
6660
- if (!mb.startsWith("z")) return null;
6661
- try {
6662
- const decoded = base58btc.decode(mb);
6663
- if (decoded.length === 34 && decoded[0] === ED25519_MULTICODEC_PREFIX[0] && decoded[1] === ED25519_MULTICODEC_PREFIX[1]) {
6664
- return decoded.slice(2);
6665
- }
6666
- if (decoded.length === 32) return decoded;
6667
- } catch {
6668
- return null;
6669
- }
6670
- return null;
6671
- }
6672
- if (vm.publicKeyJwk && typeof vm.publicKeyJwk === "object") {
6673
- const jwk = vm.publicKeyJwk;
6674
- if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519") return null;
6675
- if (typeof jwk.x !== "string") return null;
6676
- let decoded;
6677
- try {
6678
- decoded = base64UrlDecode2(jwk.x);
6679
- } catch {
6680
- return null;
6681
- }
6682
- if (decoded.length !== ED25519_PUBLIC_KEY_LENGTH) {
6683
- return null;
6684
- }
6685
- return decoded;
6686
- }
6687
- return null;
6688
- }
6689
- var StatusListUnavailable = class extends Error {
6690
- kind = "StatusListUnavailable";
6691
- };
6692
- var MalformedStatusList = class extends Error {
6693
- kind = "MalformedStatusList";
6694
- };
6695
- var StatusListTimeout = class extends Error {
6696
- kind = "StatusListTimeout";
6697
- };
6698
- var DEFAULT_FETCH_TIMEOUT_MS2 = 3e3;
6699
- var DEFAULT_TTL_MS2 = 3e4;
6700
- function makeStatusListCache(opts = {}) {
6701
- const timeoutMs = opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS2;
6702
- const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS2;
6703
- const fetchImpl = opts.fetch ?? fetch;
6704
- const cache = opts.cache ?? /* @__PURE__ */ new Map();
6705
- const now = opts.now ?? (() => Date.now());
6706
- return {
6707
- async fetch(url) {
6708
- const cached = cache.get(url);
6709
- if (cached && now() - cached.fetchedAt < ttlMs) {
6710
- return cached.indices;
6711
- }
6712
- const indices = await fetchAndDecode(url, fetchImpl, timeoutMs);
6713
- cache.set(url, { indices, fetchedAt: now() });
6714
- return indices;
6715
- }
6716
- };
6717
- }
6718
- async function fetchAndDecode(url, fetchImpl, timeoutMs) {
6719
- let safeUrl;
6720
- try {
6721
- safeUrl = assertSafeHttpsUrl2(url, "status list URL");
6722
- } catch (cause) {
6723
- if (cause instanceof UnsafeOutboundUrl2) {
6724
- throw new StatusListUnavailable(cause.message);
6725
- }
6726
- throw cause;
6727
- }
6728
- const controller = new AbortController();
6729
- const timer = setTimeout(() => controller.abort(), timeoutMs);
6730
- let response;
6731
- try {
6732
- response = await fetchImpl(safeUrl, { signal: controller.signal });
6733
- } catch (cause) {
6734
- if (cause instanceof Error && cause.name === "AbortError") {
6735
- throw new StatusListTimeout(`status list fetch timed out after ${timeoutMs}ms: ${url}`);
6736
- }
6737
- throw new StatusListUnavailable(`status list fetch failed: ${url}: ${String(cause)}`);
6738
- } finally {
6739
- clearTimeout(timer);
6740
- }
6741
- if (!response.ok) {
6742
- throw new StatusListUnavailable(`status list HTTP ${response.status} at ${url}`);
6743
- }
6744
- let vc;
6745
- try {
6746
- vc = await response.json();
6747
- } catch (cause) {
6748
- throw new MalformedStatusList(
6749
- `status list response not valid JSON at ${url}: ${String(cause)}`
6750
- );
6751
- }
6752
- const encoded = extractEncodedList(vc);
6753
- return enumerateRevokedIndices(encoded);
6754
- }
6755
- function extractEncodedList(vc) {
6756
- if (vc === null || typeof vc !== "object") {
6757
- throw new MalformedStatusList("status list VC must be a JSON object");
6758
- }
6759
- const obj = vc;
6760
- const subject = obj.credentialSubject;
6761
- if (subject === null || typeof subject !== "object") {
6762
- throw new MalformedStatusList("status list VC missing credentialSubject");
6763
- }
6764
- const encoded = subject.encodedList;
6765
- if (typeof encoded !== "string") {
6766
- throw new MalformedStatusList("status list VC missing credentialSubject.encodedList string");
6767
- }
6768
- return encoded;
6769
- }
6770
- function enumerateRevokedIndices(encodedList) {
6771
- let bytes;
6772
- try {
6773
- const compressed = base64UrlDecode2(encodedList);
6774
- bytes = new Uint8Array(zlib.gunzipSync(compressed));
6775
- } catch (cause) {
6776
- throw new MalformedStatusList(`status list bitstring decode failed: ${String(cause)}`);
6777
- }
6778
- const indices = [];
6779
- for (let byteIndex = 0; byteIndex < bytes.length; byteIndex += 1) {
6780
- const byte = bytes[byteIndex];
6781
- if (byte === 0) continue;
6782
- for (let bit = 0; bit < 8; bit += 1) {
6783
- const mask = 1 << 7 - bit;
6784
- if ((byte & mask) !== 0) {
6785
- indices.push(byteIndex * 8 + bit);
6786
- }
6787
- }
6788
- }
6789
- return indices;
6790
- }
6791
- var DEFAULT_FETCH_TIMEOUT_MS3 = 1500;
6792
- var DEFAULT_TTL_MS3 = 1e4;
6793
- var DEFAULT_BASELINE = 1;
6794
- function makeReputationOracle(opts = {}) {
6795
- const argusUrl = opts.argusUrl;
6796
- const timeoutMs = opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS3;
6797
- const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS3;
6798
- const fetchImpl = opts.fetch ?? fetch;
6799
- const baseline = opts.baselineWhenUnreachable ?? DEFAULT_BASELINE;
6800
- const cache = opts.cache ?? /* @__PURE__ */ new Map();
6801
- const now = opts.now ?? (() => Date.now());
6802
- const log = opts.logger ?? (() => {
6803
- });
6804
- return {
6805
- async score(agentDid) {
6806
- const cached = cache.get(agentDid);
6807
- if (cached && now() - cached.fetchedAt < ttlMs) {
6808
- return cached.value;
6809
- }
6810
- if (!argusUrl) {
6811
- return baseline;
6812
- }
6813
- const value = await fetchAndValidate(argusUrl, agentDid, fetchImpl, timeoutMs, baseline, log);
6814
- cache.set(agentDid, { value, fetchedAt: now() });
6815
- return value;
6816
- }
6817
- };
6818
- }
6819
- async function fetchAndValidate(argusUrl, agentDid, fetchImpl, timeoutMs, baseline, log) {
6820
- const url = `${argusUrl.replace(/\/$/, "")}/v1/reputation?agent=${encodeURIComponent(agentDid)}`;
6821
- const controller = new AbortController();
6822
- const timer = setTimeout(() => controller.abort(), timeoutMs);
6823
- let response;
6824
- try {
6825
- response = await fetchImpl(url, { signal: controller.signal });
6826
- } catch (cause) {
6827
- if (cause instanceof Error && cause.name === "AbortError") {
6828
- log(
6829
- `[reputation-oracle] Argus timed out after ${timeoutMs}ms (${agentDid}); using baseline ${baseline}`
6830
- );
6831
- } else {
6832
- log(
6833
- `[reputation-oracle] Argus fetch failed (${agentDid}): ${String(cause)}; using baseline ${baseline}`
6834
- );
6835
- }
6836
- return baseline;
6837
- } finally {
6838
- clearTimeout(timer);
6839
- }
6840
- if (!response.ok) {
6841
- log(
6842
- `[reputation-oracle] Argus HTTP ${response.status} (${agentDid}); using baseline ${baseline}`
6843
- );
6844
- return baseline;
6845
- }
6846
- let body;
6847
- try {
6848
- body = await response.json();
6849
- } catch (cause) {
6850
- log(
6851
- `[reputation-oracle] Argus response not JSON (${agentDid}): ${String(cause)}; using baseline ${baseline}`
6852
- );
6853
- return baseline;
6854
- }
6855
- if (body === null || typeof body !== "object") {
6856
- log(
6857
- `[reputation-oracle] Argus response not an object (${agentDid}); using baseline ${baseline}`
6858
- );
6859
- return baseline;
6860
- }
6861
- const score = body.score;
6862
- if (typeof score !== "number" || !Number.isFinite(score)) {
6863
- log(
6864
- `[reputation-oracle] Argus score not a finite number (${agentDid}): ${String(score)}; using baseline ${baseline}`
6865
- );
6866
- return baseline;
6867
- }
6868
- if (score < 0 || score > 1) {
6869
- log(
6870
- `[reputation-oracle] Argus score out of range (${agentDid}): ${score}; using baseline ${baseline}`
6871
- );
6872
- return baseline;
6873
- }
6874
- return score;
6875
- }
6876
- var DEFAULT_FETCH_TIMEOUT_MS4 = 2e3;
6877
- var DEFAULT_TTL_MS4 = 6e4;
6878
- var PERMIT_BY_DEFAULT_POLICY = { reputationThreshold: 0 };
6879
- function makePolicyEvaluator(opts = {}) {
6880
- const dashboardUrl = opts.dashboardUrl;
6881
- const timeoutMs = opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS4;
6882
- const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS4;
6883
- const fetchImpl = opts.fetch ?? fetch;
6884
- const fallbackPolicy = opts.defaultPolicy ?? PERMIT_BY_DEFAULT_POLICY;
6885
- const cache = opts.cache ?? /* @__PURE__ */ new Map();
6886
- const now = opts.now ?? (() => Date.now());
6887
- const log = opts.logger ?? (() => {
6888
- });
6889
- return {
6890
- async evaluate(input) {
6891
- const policy = await getOrFetchPolicy(
6892
- input.tenantHost,
6893
- dashboardUrl,
6894
- fetchImpl,
6895
- timeoutMs,
6896
- fallbackPolicy,
6897
- cache,
6898
- ttlMs,
6899
- now,
6900
- log
6901
- );
6902
- return computeDecision(policy, input);
6903
- }
6904
- };
6905
- }
6906
- function computeDecision(policy, input) {
6907
- if (input.reputation < policy.reputationThreshold) {
6908
- return {
6909
- kind: "Block",
6910
- reason: {
6911
- kind: "LowReputation",
6912
- score: input.reputation,
6913
- threshold: policy.reputationThreshold
6914
- }
6915
- };
6916
- }
6917
- return { kind: "Permit" };
6918
- }
6919
- async function getOrFetchPolicy(tenantHost, dashboardUrl, fetchImpl, timeoutMs, fallbackPolicy, cache, ttlMs, now, log) {
6920
- const cached = cache.get(tenantHost);
6921
- if (cached && now() - cached.fetchedAt < ttlMs) {
6922
- return cached.policy;
6923
- }
6924
- const cacheFallback = () => {
6925
- cache.set(tenantHost, { policy: fallbackPolicy, fetchedAt: now() });
6926
- return fallbackPolicy;
6927
- };
6928
- if (!dashboardUrl) {
6929
- return cacheFallback();
6930
- }
6931
- const url = `${dashboardUrl.replace(/\/$/, "")}/api/policy?tenant=${encodeURIComponent(tenantHost)}`;
6932
- const controller = new AbortController();
6933
- const timer = setTimeout(() => controller.abort(), timeoutMs);
6934
- let response;
6935
- try {
6936
- response = await fetchImpl(url, { signal: controller.signal });
6937
- } catch (cause) {
6938
- log(`[policy-evaluator] fetch failed (${tenantHost}): ${String(cause)}; using fallback`);
6939
- return cacheFallback();
6940
- } finally {
6941
- clearTimeout(timer);
6942
- }
6943
- if (!response.ok) {
6944
- log(`[policy-evaluator] dashboard HTTP ${response.status} (${tenantHost}); using fallback`);
6945
- return cacheFallback();
6946
- }
6947
- let body;
6948
- try {
6949
- body = await response.json();
6950
- } catch (cause) {
6951
- log(
6952
- `[policy-evaluator] dashboard response not JSON (${tenantHost}): ${String(cause)}; using fallback`
6953
- );
6954
- return cacheFallback();
6955
- }
6956
- const parsed = parseTenantPolicy(body);
6957
- if (!parsed) {
6958
- log(`[policy-evaluator] dashboard response malformed (${tenantHost}); using fallback`);
6959
- return cacheFallback();
6960
- }
6961
- cache.set(tenantHost, { policy: parsed, fetchedAt: now() });
6962
- return parsed;
6963
- }
6964
- function parseTenantPolicy(raw) {
6965
- if (raw === null || typeof raw !== "object") return null;
6966
- const threshold = raw.reputationThreshold;
6967
- if (typeof threshold !== "number" || !Number.isFinite(threshold) || threshold < 0 || threshold > 1) {
6968
- return null;
6969
- }
6970
- return { reputationThreshold: threshold };
6971
- }
6972
- function makeSystemClock() {
6973
- return { nowUnix: () => Math.floor(Date.now() / 1e3) };
6974
- }
6975
5200
  function adaptToExpressResponse(rendered, req, res, next) {
6976
5201
  const clientAcceptsHtml = checkpointShared.acceptsHtml(req.headers);
6977
5202
  const verdictCookie = checkpointShared.encodeVerdictCookie(rendered);
@@ -7055,9 +5280,9 @@ function withCheckpoint(config) {
7055
5280
  return async function checkpointMiddleware(req, res, next) {
7056
5281
  try {
7057
5282
  const httpLike = expressRequestToHttpLike(req);
7058
- const result = await verifyRequest(httpLike, opts);
5283
+ const result = await orchestrator.verifyRequest(httpLike, opts);
7059
5284
  await dispatchOnResult(config, result, req);
7060
- const rendered = renderDecisionAsResponse(result);
5285
+ const rendered = orchestrator.renderDecisionAsResponse(result);
7061
5286
  adaptToExpressResponse(rendered, req, res, next);
7062
5287
  } catch (err) {
7063
5288
  next(err);
@@ -7067,11 +5292,11 @@ function withCheckpoint(config) {
7067
5292
  function buildVerifyOpts(config) {
7068
5293
  const overrides = config.adapters ?? {};
7069
5294
  return {
7070
- didResolver: overrides.didResolver ?? makeDidResolver(),
7071
- statusListCache: overrides.statusListCache ?? makeStatusListCache(),
7072
- reputationOracle: overrides.reputationOracle ?? makeReputationOracle({ argusUrl: config.argusUrl }),
7073
- policyEvaluator: overrides.policyEvaluator ?? makePolicyEvaluator({ dashboardUrl: config.dashboardUrl }),
7074
- clock: makeSystemClock(),
5295
+ didResolver: overrides.didResolver ?? adapters.makeDidResolver(),
5296
+ statusListCache: overrides.statusListCache ?? adapters.makeStatusListCache(),
5297
+ reputationOracle: overrides.reputationOracle ?? adapters.makeReputationOracle({ argusUrl: config.argusUrl }),
5298
+ policyEvaluator: overrides.policyEvaluator ?? adapters.makePolicyEvaluator({ dashboardUrl: config.dashboardUrl }),
5299
+ clock: adapters.makeSystemClock(),
7075
5300
  tenantHost: config.tenantHost,
7076
5301
  enforcementMode: config.enforcementMode ?? "enforce",
7077
5302
  reputationBaseline: config.reputationBaseline,