@t402/extensions 2.3.1 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -472,7 +472,7 @@ Use discovery schemas to validate API requests and responses during development.
472
472
  ## Related Resources
473
473
 
474
474
  - [t402 Core Package](../core/README.md) - Core t402 protocol implementation
475
- - [t402 Specification](../../../specs/t402-specification.md) - Full protocol specification
475
+ - [t402 Specification](../../../specs/t402-specification-v2.md) - Full protocol specification
476
476
 
477
477
  ## Version Support
478
478
 
@@ -1,3 +1,3 @@
1
- export { e as BAZAAR, m as BazaarClientExtension, c as BodyDiscoveryExtension, B as BodyDiscoveryInfo, d as DiscoveryExtension, D as DiscoveryInfo, n as DiscoveryResource, o as DiscoveryResourcesResponse, L as ListDiscoveryResourcesParams, a as QueryDiscoveryExtension, Q as QueryDiscoveryInfo, V as ValidationResult, b as bazaarResourceServerExtension, f as declareDiscoveryExtension, g as extractDiscoveryInfo, h as extractDiscoveryInfoFromExtension, j as extractDiscoveryInfoV1, l as extractResourceMetadataV1, k as isDiscoverableV1, i as validateAndExtract, v as validateDiscoveryExtension, w as withBazaar } from '../index-DYNleT-u.js';
1
+ export { B as BAZAAR, a as BazaarClientExtension, b as BodyDiscoveryExtension, c as BodyDiscoveryInfo, D as DiscoveryExtension, d as DiscoveryInfo, e as DiscoveryResource, f as DiscoveryResourcesResponse, L as ListDiscoveryResourcesParams, Q as QueryDiscoveryExtension, g as QueryDiscoveryInfo, V as ValidationResult, h as bazaarResourceServerExtension, i as declareDiscoveryExtension, j as extractDiscoveryInfo, k as extractDiscoveryInfoFromExtension, l as extractDiscoveryInfoV1, m as extractResourceMetadataV1, n as isDiscoverableV1, v as validateAndExtract, o as validateDiscoveryExtension, w as withBazaar } from '../index-Mk5Ypp8M.js';
2
2
  import '@t402/core/http';
3
3
  import '@t402/core/types';
@@ -1,4 +1,4 @@
1
- import { QueryParamMethods, BodyMethods, HTTPFacilitatorClient } from '@t402/core/http';
1
+ import { BodyMethods, QueryParamMethods, HTTPFacilitatorClient } from '@t402/core/http';
2
2
  import { ResourceServerExtension, PaymentPayload, PaymentRequirements, PaymentRequirementsV1 } from '@t402/core/types';
3
3
 
4
4
  /**
@@ -544,4 +544,4 @@ interface BazaarClientExtension {
544
544
  */
545
545
  declare function withBazaar<T extends HTTPFacilitatorClient>(client: T): WithExtensions<T, BazaarClientExtension>;
546
546
 
547
- export { type BodyDiscoveryInfo as B, type DiscoveryInfo as D, type ListDiscoveryResourcesParams as L, type QueryDiscoveryInfo as Q, type ValidationResult as V, type WithExtensions as W, type QueryDiscoveryExtension as a, bazaarResourceServerExtension as b, type BodyDiscoveryExtension as c, type DiscoveryExtension as d, BAZAAR as e, declareDiscoveryExtension as f, extractDiscoveryInfo as g, extractDiscoveryInfoFromExtension as h, validateAndExtract as i, extractDiscoveryInfoV1 as j, isDiscoverableV1 as k, extractResourceMetadataV1 as l, type BazaarClientExtension as m, type DiscoveryResource as n, type DiscoveryResourcesResponse as o, validateDiscoveryExtension as v, withBazaar as w };
547
+ export { BAZAAR as B, type DiscoveryExtension as D, type ListDiscoveryResourcesParams as L, type QueryDiscoveryExtension as Q, type ValidationResult as V, type WithExtensions as W, type BazaarClientExtension as a, type BodyDiscoveryExtension as b, type BodyDiscoveryInfo as c, type DiscoveryInfo as d, type DiscoveryResource as e, type DiscoveryResourcesResponse as f, type QueryDiscoveryInfo as g, bazaarResourceServerExtension as h, declareDiscoveryExtension as i, extractDiscoveryInfo as j, extractDiscoveryInfoFromExtension as k, extractDiscoveryInfoV1 as l, extractResourceMetadataV1 as m, isDiscoverableV1 as n, validateDiscoveryExtension as o, validateAndExtract as v, withBazaar as w };
@@ -1,4 +1,4 @@
1
- export { e as BAZAAR, m as BazaarClientExtension, c as BodyDiscoveryExtension, B as BodyDiscoveryInfo, d as DiscoveryExtension, D as DiscoveryInfo, n as DiscoveryResource, o as DiscoveryResourcesResponse, L as ListDiscoveryResourcesParams, a as QueryDiscoveryExtension, Q as QueryDiscoveryInfo, V as ValidationResult, W as WithExtensions, b as bazaarResourceServerExtension, f as declareDiscoveryExtension, g as extractDiscoveryInfo, h as extractDiscoveryInfoFromExtension, j as extractDiscoveryInfoV1, l as extractResourceMetadataV1, k as isDiscoverableV1, i as validateAndExtract, v as validateDiscoveryExtension, w as withBazaar } from './index-DYNleT-u.js';
1
+ export { B as BAZAAR, a as BazaarClientExtension, b as BodyDiscoveryExtension, c as BodyDiscoveryInfo, D as DiscoveryExtension, d as DiscoveryInfo, e as DiscoveryResource, f as DiscoveryResourcesResponse, L as ListDiscoveryResourcesParams, Q as QueryDiscoveryExtension, g as QueryDiscoveryInfo, V as ValidationResult, W as WithExtensions, h as bazaarResourceServerExtension, i as declareDiscoveryExtension, j as extractDiscoveryInfo, k as extractDiscoveryInfoFromExtension, l as extractDiscoveryInfoV1, m as extractResourceMetadataV1, n as isDiscoverableV1, v as validateAndExtract, o as validateDiscoveryExtension, w as withBazaar } from './index-Mk5Ypp8M.js';
2
2
  export { DeclareSIWxOptions, SIWX_EXTENSION_KEY, SIWX_HEADER_NAME, SIWxExtension, SIWxExtensionInfo, SIWxPayload, SIWxSigner, SIWxValidationResult, SIWxVerificationResult, SignatureScheme, ValidateSIWxOptions, VerifySIWxOptions, constructMessage, createSIWxMessage, createSIWxPayload, createSIWxTypedData, declareSIWxExtension, encodeSIWxHeader, hashMessage, parseSIWxHeader, signSIWxMessage, validateSIWxMessage, verifyEIP6492Signature, verifySIWxSignature } from './sign-in-with-x/index.js';
3
3
  import '@t402/core/http';
4
4
  import '@t402/core/types';
package/dist/cjs/index.js CHANGED
@@ -493,6 +493,7 @@ function withBazaar(client) {
493
493
  var import_crypto = require("crypto");
494
494
  var import_sha3 = require("@noble/hashes/sha3");
495
495
  var import_secp256k1 = require("@noble/curves/secp256k1");
496
+ var import_ed25519 = require("@noble/curves/ed25519");
496
497
  var import_utils = require("@noble/hashes/utils");
497
498
  var SIWX_SCHEMA = {
498
499
  type: "object",
@@ -616,10 +617,89 @@ function validateSIWxMessage(message, expectedResourceUri, options = {}) {
616
617
  }
617
618
  return { valid: true };
618
619
  }
620
+ function detectSignatureScheme(chainId) {
621
+ const namespace = chainId.split(":")[0];
622
+ switch (namespace) {
623
+ case "solana":
624
+ case "stellar":
625
+ return "ed25519";
626
+ case "eip155":
627
+ default:
628
+ return "evm";
629
+ }
630
+ }
631
+ function verifyEd25519Signature(message, signature, publicKey) {
632
+ try {
633
+ const sigHex = signature.startsWith("0x") ? signature.slice(2) : signature;
634
+ const sigBytes = (0, import_utils.hexToBytes)(sigHex);
635
+ if (sigBytes.length !== 64) {
636
+ throw new Error(
637
+ `Invalid Ed25519 signature length: expected 64 bytes, got ${sigBytes.length}`
638
+ );
639
+ }
640
+ let pubKeyBytes;
641
+ const pubKeyHex = publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey;
642
+ if (/^[0-9a-fA-F]{64}$/.test(pubKeyHex)) {
643
+ pubKeyBytes = (0, import_utils.hexToBytes)(pubKeyHex);
644
+ } else {
645
+ pubKeyBytes = decodeBase58(publicKey);
646
+ }
647
+ if (pubKeyBytes.length !== 32) {
648
+ throw new Error(
649
+ `Invalid Ed25519 public key length: expected 32 bytes, got ${pubKeyBytes.length}`
650
+ );
651
+ }
652
+ const messageBytes = new TextEncoder().encode(message);
653
+ return import_ed25519.ed25519.verify(sigBytes, messageBytes, pubKeyBytes);
654
+ } catch {
655
+ return false;
656
+ }
657
+ }
658
+ function decodeBase58(str) {
659
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
660
+ const ALPHABET_MAP = /* @__PURE__ */ new Map();
661
+ for (let i = 0; i < ALPHABET.length; i++) {
662
+ ALPHABET_MAP.set(ALPHABET[i], i);
663
+ }
664
+ if (str.length === 0) return new Uint8Array(0);
665
+ const bytes = [0];
666
+ for (const char of str) {
667
+ const value = ALPHABET_MAP.get(char);
668
+ if (value === void 0) {
669
+ throw new Error(`Invalid base58 character: ${char}`);
670
+ }
671
+ let carry = value;
672
+ for (let j = 0; j < bytes.length; j++) {
673
+ carry += bytes[j] * 58;
674
+ bytes[j] = carry & 255;
675
+ carry >>= 8;
676
+ }
677
+ while (carry > 0) {
678
+ bytes.push(carry & 255);
679
+ carry >>= 8;
680
+ }
681
+ }
682
+ for (const char of str) {
683
+ if (char !== "1") break;
684
+ bytes.push(0);
685
+ }
686
+ return new Uint8Array(bytes.reverse());
687
+ }
619
688
  async function verifySIWxSignature(message, signature, options = {}) {
620
689
  const { checkSmartWallet = false } = options;
621
690
  try {
622
691
  const messageText = constructMessage(message);
692
+ const scheme = detectSignatureScheme(message.chainId);
693
+ if (scheme === "ed25519") {
694
+ const isValid = verifyEd25519Signature(messageText, signature, message.address);
695
+ if (isValid) {
696
+ return { valid: true, address: message.address };
697
+ }
698
+ return {
699
+ valid: false,
700
+ error: "Ed25519 signature verification failed"
701
+ };
702
+ }
623
703
  const messageHash = hashMessage(messageText);
624
704
  const recoveredAddress = recoverAddress(messageHash, signature);
625
705
  if (recoveredAddress.toLowerCase() !== message.address.toLowerCase()) {
@@ -854,7 +934,10 @@ async function signSIWxMessage(message, signer, options) {
854
934
  }
855
935
  return signer.signMessage(message);
856
936
  case "sep10":
857
- throw new Error("Stellar SEP-10 signing not yet implemented");
937
+ if (!signer.signMessage) {
938
+ throw new Error("Signer does not support signing");
939
+ }
940
+ return signer.signMessage(message);
858
941
  default:
859
942
  throw new Error(`Unknown signature scheme: ${scheme}`);
860
943
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts","../../src/bazaar/types.ts","../../src/bazaar/resourceService.ts","../../src/bazaar/server.ts","../../src/bazaar/facilitator.ts","../../src/bazaar/v1/facilitator.ts","../../src/bazaar/facilitatorClient.ts","../../src/sign-in-with-x/server.ts","../../src/sign-in-with-x/client.ts"],"sourcesContent":["// Shared extension utilities\nexport type { WithExtensions } from \"./types\";\n\n// Bazaar extension\nexport * from \"./bazaar\";\nexport { bazaarResourceServerExtension } from \"./bazaar/server\";\n\n// Sign-in-with-x extension\nexport * from \"./sign-in-with-x\";\n","/**\n * Type definitions for the Bazaar Discovery Extension\n */\n\nimport type { BodyMethods, QueryParamMethods } from \"@t402/core/http\";\n\n/**\n * Extension identifier constant for the Bazaar discovery extension\n */\nexport const BAZAAR = \"bazaar\";\n\n/**\n * Discovery info for query parameter methods (GET, HEAD, DELETE)\n */\nexport interface QueryDiscoveryInfo {\n input: {\n type: \"http\";\n method: QueryParamMethods;\n queryParams?: Record<string, unknown>;\n headers?: Record<string, string>;\n };\n output?: {\n type?: string;\n format?: string;\n example?: unknown;\n };\n}\n\n/**\n * Discovery info for body methods (POST, PUT, PATCH)\n */\nexport interface BodyDiscoveryInfo {\n input: {\n type: \"http\";\n method: BodyMethods;\n bodyType: \"json\" | \"form-data\" | \"text\";\n body: Record<string, unknown>;\n queryParams?: Record<string, unknown>;\n headers?: Record<string, string>;\n };\n output?: {\n type?: string;\n format?: string;\n example?: unknown;\n };\n}\n\n/**\n * Combined discovery info type\n */\nexport type DiscoveryInfo = QueryDiscoveryInfo | BodyDiscoveryInfo;\n\n/**\n * Discovery extension for query parameter methods (GET, HEAD, DELETE)\n */\nexport interface QueryDiscoveryExtension {\n info: QueryDiscoveryInfo;\n\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n type: \"object\";\n properties: {\n input: {\n type: \"object\";\n properties: {\n type: {\n type: \"string\";\n const: \"http\";\n };\n method: {\n type: \"string\";\n enum: QueryParamMethods[];\n };\n queryParams?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n };\n headers?: {\n type: \"object\";\n additionalProperties: {\n type: \"string\";\n };\n };\n };\n required: (\"type\" | \"method\")[];\n additionalProperties?: boolean;\n };\n output?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: readonly string[];\n additionalProperties?: boolean;\n };\n };\n required: [\"input\"];\n };\n}\n\n/**\n * Discovery extension for body methods (POST, PUT, PATCH)\n */\nexport interface BodyDiscoveryExtension {\n info: BodyDiscoveryInfo;\n\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n type: \"object\";\n properties: {\n input: {\n type: \"object\";\n properties: {\n type: {\n type: \"string\";\n const: \"http\";\n };\n method: {\n type: \"string\";\n enum: BodyMethods[];\n };\n bodyType: {\n type: \"string\";\n enum: [\"json\", \"form-data\", \"text\"];\n };\n body: Record<string, unknown>;\n queryParams?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n };\n headers?: {\n type: \"object\";\n additionalProperties: {\n type: \"string\";\n };\n };\n };\n required: (\"type\" | \"method\" | \"bodyType\" | \"body\")[];\n additionalProperties?: boolean;\n };\n output?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: readonly string[];\n additionalProperties?: boolean;\n };\n };\n required: [\"input\"];\n };\n}\n\n/**\n * Combined discovery extension type\n */\nexport type DiscoveryExtension = QueryDiscoveryExtension | BodyDiscoveryExtension;\n\nexport interface DeclareQueryDiscoveryExtensionConfig {\n method?: QueryParamMethods;\n input?: Record<string, unknown>;\n inputSchema?: Record<string, unknown>;\n output?: {\n example?: unknown;\n schema?: Record<string, unknown>;\n };\n}\n\nexport interface DeclareBodyDiscoveryExtensionConfig {\n method?: BodyMethods;\n input?: Record<string, unknown>;\n inputSchema?: Record<string, unknown>;\n bodyType?: \"json\" | \"form-data\" | \"text\";\n output?: {\n example?: unknown;\n schema?: Record<string, unknown>;\n };\n}\n\nexport type DeclareDiscoveryExtensionConfig =\n | DeclareQueryDiscoveryExtensionConfig\n | DeclareBodyDiscoveryExtensionConfig;\n\nexport const isQueryExtensionConfig = (\n config: DeclareDiscoveryExtensionConfig,\n): config is DeclareQueryDiscoveryExtensionConfig => {\n return !(\"bodyType\" in config);\n};\n\nexport const isBodyExtensionConfig = (\n config: DeclareDiscoveryExtensionConfig,\n): config is DeclareBodyDiscoveryExtensionConfig => {\n return \"bodyType\" in config;\n};\n","/**\n * Resource Service functions for creating Bazaar discovery extensions\n *\n * These functions help servers declare the shape of their endpoints\n * for facilitator discovery and cataloging in the Bazaar.\n */\n\nimport {\n type DiscoveryExtension,\n type QueryDiscoveryExtension,\n type BodyDiscoveryExtension,\n type DeclareDiscoveryExtensionConfig,\n type DeclareQueryDiscoveryExtensionConfig,\n type DeclareBodyDiscoveryExtensionConfig,\n} from \"./types\";\n\n/**\n * Internal helper to create a query discovery extension\n *\n * @param root0 - Configuration object for query discovery extension\n * @param root0.method - HTTP method (GET, HEAD, DELETE)\n * @param root0.input - Query parameters\n * @param root0.inputSchema - JSON schema for query parameters\n * @param root0.output - Output specification with example\n * @returns QueryDiscoveryExtension with info and schema\n */\nfunction createQueryDiscoveryExtension({\n method,\n input = {},\n inputSchema = { properties: {} },\n output,\n}: DeclareQueryDiscoveryExtensionConfig): QueryDiscoveryExtension {\n return {\n info: {\n input: {\n type: \"http\",\n ...(method ? { method } : {}),\n ...(input ? { queryParams: input } : {}),\n } as QueryDiscoveryExtension[\"info\"][\"input\"],\n ...(output?.example\n ? {\n output: {\n type: \"json\",\n example: output.example,\n },\n }\n : {}),\n },\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n const: \"http\",\n },\n method: {\n type: \"string\",\n enum: [\"GET\", \"HEAD\", \"DELETE\"],\n },\n ...(inputSchema\n ? {\n queryParams: {\n type: \"object\" as const,\n ...(typeof inputSchema === \"object\" ? inputSchema : {}),\n },\n }\n : {}),\n },\n required: [\"type\"] as (\"type\" | \"method\")[],\n additionalProperties: false,\n },\n ...(output?.example\n ? {\n output: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\" as const,\n },\n example: {\n type: \"object\" as const,\n ...(output.schema && typeof output.schema === \"object\" ? output.schema : {}),\n },\n },\n required: [\"type\"] as const,\n },\n }\n : {}),\n },\n required: [\"input\"],\n },\n };\n}\n\n/**\n * Internal helper to create a body discovery extension\n *\n * @param root0 - Configuration object for body discovery extension\n * @param root0.method - HTTP method (POST, PUT, PATCH)\n * @param root0.input - Request body specification\n * @param root0.inputSchema - JSON schema for request body\n * @param root0.bodyType - Content type of body (json, form, multipart)\n * @param root0.output - Output specification with example\n * @returns BodyDiscoveryExtension with info and schema\n */\nfunction createBodyDiscoveryExtension({\n method,\n input = {},\n inputSchema = { properties: {} },\n bodyType = \"json\",\n output,\n}: DeclareBodyDiscoveryExtensionConfig): BodyDiscoveryExtension {\n return {\n info: {\n input: {\n type: \"http\",\n ...(method ? { method } : {}),\n bodyType,\n body: input,\n } as BodyDiscoveryExtension[\"info\"][\"input\"],\n ...(output?.example\n ? {\n output: {\n type: \"json\",\n example: output.example,\n },\n }\n : {}),\n },\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n const: \"http\",\n },\n method: {\n type: \"string\",\n enum: [\"POST\", \"PUT\", \"PATCH\"],\n },\n bodyType: {\n type: \"string\",\n enum: [\"json\", \"form-data\", \"text\"],\n },\n body: inputSchema,\n },\n required: [\"type\", \"bodyType\", \"body\"] as (\"type\" | \"method\" | \"bodyType\" | \"body\")[],\n additionalProperties: false,\n },\n ...(output?.example\n ? {\n output: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\" as const,\n },\n example: {\n type: \"object\" as const,\n ...(output.schema && typeof output.schema === \"object\" ? output.schema : {}),\n },\n },\n required: [\"type\"] as const,\n },\n }\n : {}),\n },\n required: [\"input\"],\n },\n };\n}\n\n/**\n * Create a discovery extension for any HTTP method\n *\n * This function helps servers declare how their endpoint should be called,\n * including the expected input parameters/body and output format.\n *\n * @param config - Configuration object for the discovery extension\n * @returns A discovery extension object with both info and schema\n *\n * @example\n * ```typescript\n * // For a GET endpoint with no input\n * const getExtension = declareDiscoveryExtension({\n * method: \"GET\",\n * output: {\n * example: { message: \"Success\", timestamp: \"2024-01-01T00:00:00Z\" }\n * }\n * });\n *\n * // For a GET endpoint with query params\n * const getWithParams = declareDiscoveryExtension({\n * method: \"GET\",\n * input: { query: \"example\" },\n * inputSchema: {\n * properties: {\n * query: { type: \"string\" }\n * },\n * required: [\"query\"]\n * }\n * });\n *\n * // For a POST endpoint with JSON body\n * const postExtension = declareDiscoveryExtension({\n * method: \"POST\",\n * input: { name: \"John\", age: 30 },\n * inputSchema: {\n * properties: {\n * name: { type: \"string\" },\n * age: { type: \"number\" }\n * },\n * required: [\"name\"]\n * },\n * bodyType: \"json\",\n * output: {\n * example: { success: true, id: \"123\" }\n * }\n * });\n * ```\n */\nexport function declareDiscoveryExtension(\n config: Omit<DeclareDiscoveryExtensionConfig, \"method\">,\n): Record<string, DiscoveryExtension> {\n const bodyType = (config as DeclareBodyDiscoveryExtensionConfig).bodyType;\n const isBodyMethod = bodyType !== undefined;\n\n const extension = isBodyMethod\n ? createBodyDiscoveryExtension(config as DeclareBodyDiscoveryExtensionConfig)\n : createQueryDiscoveryExtension(config as DeclareQueryDiscoveryExtensionConfig);\n\n return { bazaar: extension as DiscoveryExtension };\n}\n","import type { ResourceServerExtension } from \"@t402/core/types\";\nimport type { HTTPRequestContext } from \"@t402/core/http\";\nimport { BAZAAR } from \"./types\";\n\n/**\n * Type guard to check if context is an HTTP request context.\n *\n * @param ctx - The context to check\n * @returns True if context is an HTTPRequestContext\n */\nfunction isHTTPRequestContext(ctx: unknown): ctx is HTTPRequestContext {\n return ctx !== null && typeof ctx === \"object\" && \"method\" in ctx && \"adapter\" in ctx;\n}\n\ninterface ExtensionDeclaration {\n [key: string]: unknown;\n info?: {\n [key: string]: unknown;\n input?: Record<string, unknown>;\n };\n schema?: {\n [key: string]: unknown;\n properties?: {\n [key: string]: unknown;\n input?: {\n [key: string]: unknown;\n required?: string[];\n };\n };\n };\n}\n\nexport const bazaarResourceServerExtension: ResourceServerExtension = {\n key: BAZAAR,\n\n enrichDeclaration: (declaration, transportContext) => {\n if (!isHTTPRequestContext(transportContext)) {\n return declaration;\n }\n\n const extension = declaration as ExtensionDeclaration;\n const method = transportContext.method;\n\n return {\n ...extension,\n info: {\n ...(extension.info || {}),\n input: {\n ...(extension.info?.input || {}),\n method,\n },\n },\n schema: {\n ...(extension.schema || {}),\n properties: {\n ...(extension.schema?.properties || {}),\n input: {\n ...(extension.schema?.properties?.input || {}),\n required: [\n ...(extension.schema?.properties?.input?.required || []),\n ...(!(extension.schema?.properties?.input?.required || []).includes(\"method\")\n ? [\"method\"]\n : []),\n ],\n },\n },\n },\n };\n },\n};\n","/**\n * Facilitator functions for validating and extracting Bazaar discovery extensions\n *\n * These functions help facilitators validate extension data against schemas\n * and extract the discovery information for cataloging in the Bazaar.\n *\n * Supports both v2 (extensions in PaymentRequired) and v1 (outputSchema in PaymentRequirements).\n */\n\nimport Ajv from \"ajv/dist/2020\";\nimport type { PaymentPayload, PaymentRequirements, PaymentRequirementsV1 } from \"@t402/core/types\";\nimport type { DiscoveryExtension, DiscoveryInfo } from \"./types\";\nimport { BAZAAR } from \"./types\";\nimport { extractDiscoveryInfoV1 } from \"./v1/facilitator\";\n\n/**\n * Validation result for discovery extensions\n */\nexport interface ValidationResult {\n valid: boolean;\n errors?: string[];\n}\n\n/**\n * Validates a discovery extension's info against its schema\n *\n * @param extension - The discovery extension containing info and schema\n * @returns Validation result indicating if the info matches the schema\n *\n * @example\n * ```typescript\n * const extension = declareDiscoveryExtension(...);\n * const result = validateDiscoveryExtension(extension);\n *\n * if (result.valid) {\n * console.log(\"Extension is valid\");\n * } else {\n * console.error(\"Validation errors:\", result.errors);\n * }\n * ```\n */\nexport function validateDiscoveryExtension(extension: DiscoveryExtension): ValidationResult {\n try {\n const ajv = new Ajv({ strict: false, allErrors: true });\n const validate = ajv.compile(extension.schema);\n\n // The schema describes the structure of info directly\n // Schema has properties: { input: {...}, output: {...} }\n // So we validate extension.info which has { input: {...}, output: {...} }\n const valid = validate(extension.info);\n\n if (valid) {\n return { valid: true };\n }\n\n const errors = validate.errors?.map(err => {\n const path = err.instancePath || \"(root)\";\n return `${path}: ${err.message}`;\n }) || [\"Unknown validation error\"];\n\n return { valid: false, errors };\n } catch (error) {\n return {\n valid: false,\n errors: [\n `Schema validation failed: ${error instanceof Error ? error.message : String(error)}`,\n ],\n };\n }\n}\n\n/**\n * Extracts the discovery info from payment payload and requirements\n *\n * This function handles both v2 (extensions) and v1 (outputSchema) formats.\n *\n * For v2: Discovery info is in PaymentPayload.extensions (client copied it from PaymentRequired)\n * For v1: Discovery info is in PaymentRequirements.outputSchema\n *\n * V1 data is automatically transformed to v2 DiscoveryInfo format, making smart\n * assumptions about field names (queryParams/query/params for GET, bodyFields/body/data for POST, etc.)\n *\n * @param paymentPayload - The payment payload containing extensions (v2) and version info\n * @param paymentRequirements - The payment requirements (contains outputSchema for v1)\n * @param validate - Whether to validate v2 extensions before extracting (default: true)\n * @returns The discovery info in v2 format if present, or null if not discoverable\n *\n * @example\n * ```typescript\n * // V2 - extensions are in PaymentPayload\n * const info = extractDiscoveryInfo(paymentPayload, paymentRequirements);\n *\n * // V1 - discovery info is in PaymentRequirements.outputSchema\n * const info = extractDiscoveryInfo(paymentPayloadV1, paymentRequirementsV1);\n *\n * if (info) {\n * // Both v1 and v2 return the same DiscoveryInfo structure\n * console.log(\"Method:\", info.input.method);\n * }\n * ```\n */\nexport interface DiscoveredResource {\n resourceUrl: string;\n method: string;\n t402Version: number;\n discoveryInfo: DiscoveryInfo;\n}\n\n/**\n * Extracts discovery information from payment payload and requirements.\n * Combines resource URL, HTTP method, version, and discovery info into a single object.\n *\n * @param paymentPayload - The payment payload containing extensions and resource info\n * @param paymentRequirements - The payment requirements to validate against\n * @param validate - Whether to validate the discovery info against the schema (default: true)\n * @returns Discovered resource info with URL, method, version and discovery data, or null if not found\n */\nexport function extractDiscoveryInfo(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements | PaymentRequirementsV1,\n validate: boolean = true,\n): DiscoveredResource | null {\n let discoveryInfo: DiscoveryInfo | null = null;\n let resourceUrl: string;\n\n if (paymentPayload.t402Version === 2) {\n resourceUrl = paymentPayload.resource?.url ?? \"\";\n\n if (paymentPayload.extensions) {\n const bazaarExtension = paymentPayload.extensions[BAZAAR];\n\n if (bazaarExtension && typeof bazaarExtension === \"object\") {\n try {\n const extension = bazaarExtension as DiscoveryExtension;\n\n if (validate) {\n const result = validateDiscoveryExtension(extension);\n if (!result.valid) {\n console.warn(\n `V2 discovery extension validation failed: ${result.errors?.join(\", \")}`,\n );\n } else {\n discoveryInfo = extension.info;\n }\n } else {\n discoveryInfo = extension.info;\n }\n } catch (error) {\n console.warn(`V2 discovery extension extraction failed: ${error}`);\n }\n }\n }\n } else if (paymentPayload.t402Version === 1) {\n const requirementsV1 = paymentRequirements as PaymentRequirementsV1;\n resourceUrl = requirementsV1.resource;\n discoveryInfo = extractDiscoveryInfoV1(requirementsV1);\n } else {\n return null;\n }\n\n if (!discoveryInfo) {\n return null;\n }\n\n return {\n resourceUrl,\n method: discoveryInfo.input.method,\n t402Version: paymentPayload.t402Version,\n discoveryInfo,\n };\n}\n\n/**\n * Extracts discovery info from a v2 extension directly\n *\n * This is a lower-level function for when you already have the extension object.\n * For general use, prefer the main extractDiscoveryInfo function.\n *\n * @param extension - The discovery extension to extract info from\n * @param validate - Whether to validate before extracting (default: true)\n * @returns The discovery info if valid\n * @throws Error if validation fails and validate is true\n */\nexport function extractDiscoveryInfoFromExtension(\n extension: DiscoveryExtension,\n validate: boolean = true,\n): DiscoveryInfo {\n if (validate) {\n const result = validateDiscoveryExtension(extension);\n if (!result.valid) {\n throw new Error(\n `Invalid discovery extension: ${result.errors?.join(\", \") || \"Unknown error\"}`,\n );\n }\n }\n\n return extension.info;\n}\n\n/**\n * Validates and extracts discovery info in one step\n *\n * This is a convenience function that combines validation and extraction,\n * returning both the validation result and the info if valid.\n *\n * @param extension - The discovery extension to validate and extract\n * @returns Object containing validation result and info (if valid)\n *\n * @example\n * ```typescript\n * const extension = declareDiscoveryExtension(...);\n * const { valid, info, errors } = validateAndExtract(extension);\n *\n * if (valid && info) {\n * // Store info in Bazaar catalog\n * } else {\n * console.error(\"Validation errors:\", errors);\n * }\n * ```\n */\nexport function validateAndExtract(extension: DiscoveryExtension): {\n valid: boolean;\n info?: DiscoveryInfo;\n errors?: string[];\n} {\n const result = validateDiscoveryExtension(extension);\n\n if (result.valid) {\n return {\n valid: true,\n info: extension.info,\n };\n }\n\n return {\n valid: false,\n errors: result.errors,\n };\n}\n","/**\n * V1 Facilitator functions for extracting Bazaar discovery information\n *\n * In v1, discovery information is stored in the `outputSchema` field\n * of PaymentRequirements, which has a different structure than v2.\n *\n * This module transforms v1 data into v2 DiscoveryInfo format.\n */\n\nimport type { PaymentRequirementsV1 } from \"@t402/core/types\";\nimport type { BodyMethods, QueryParamMethods } from \"@t402/core/http\";\nimport type { DiscoveryInfo, QueryDiscoveryInfo, BodyDiscoveryInfo } from \"../types\";\n\n/**\n * Type guard to check if an object has the v1 outputSchema structure\n *\n * @param obj - The object to check\n * @returns True if object has v1 outputSchema structure\n */\nfunction hasV1OutputSchema(\n obj: unknown,\n): obj is { input: Record<string, unknown>; output?: Record<string, unknown> } {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"input\" in obj &&\n obj.input !== null &&\n typeof obj.input === \"object\" &&\n \"type\" in obj.input &&\n obj.input.type === \"http\" &&\n \"method\" in obj.input\n );\n}\n\n/**\n * Checks if a method is a query parameter method\n *\n * @param method - HTTP method string to check\n * @returns True if method is GET, HEAD, or DELETE\n */\nfunction isQueryMethod(method: string): method is QueryParamMethods {\n const upperMethod = method.toUpperCase();\n return upperMethod === \"GET\" || upperMethod === \"HEAD\" || upperMethod === \"DELETE\";\n}\n\n/**\n * Checks if a method is a body method\n *\n * @param method - HTTP method string to check\n * @returns True if method is POST, PUT, or PATCH\n */\nfunction isBodyMethod(method: string): method is BodyMethods {\n const upperMethod = method.toUpperCase();\n return upperMethod === \"POST\" || upperMethod === \"PUT\" || upperMethod === \"PATCH\";\n}\n\n/**\n * Extracts query parameters from v1 input, making smart assumptions\n * about common field names used in v1\n *\n * @param v1Input - V1 input object from payment requirements\n * @returns Extracted query parameters or undefined\n */\nfunction extractQueryParams(v1Input: Record<string, unknown>): Record<string, unknown> | undefined {\n // Check various common field names used in v1 (both camelCase and snake_case)\n if (v1Input.queryParams && typeof v1Input.queryParams === \"object\") {\n return v1Input.queryParams as Record<string, unknown>;\n }\n if (v1Input.query_params && typeof v1Input.query_params === \"object\") {\n return v1Input.query_params as Record<string, unknown>;\n }\n if (v1Input.query && typeof v1Input.query === \"object\") {\n return v1Input.query as Record<string, unknown>;\n }\n if (v1Input.params && typeof v1Input.params === \"object\") {\n return v1Input.params as Record<string, unknown>;\n }\n return undefined;\n}\n\n/**\n * Extracts body information from v1 input, making smart assumptions\n *\n * @param v1Input - V1 input object from payment requirements\n * @returns Object containing body content and bodyType\n */\nfunction extractBodyInfo(v1Input: Record<string, unknown>): {\n body: Record<string, unknown>;\n bodyType: \"json\" | \"form-data\" | \"text\";\n} {\n // Determine body type (check both camelCase and snake_case)\n let bodyType: \"json\" | \"form-data\" | \"text\" = \"json\";\n const bodyTypeField = v1Input.bodyType || v1Input.body_type;\n\n if (bodyTypeField && typeof bodyTypeField === \"string\") {\n const type = bodyTypeField.toLowerCase();\n if (type.includes(\"form\") || type.includes(\"multipart\")) {\n bodyType = \"form-data\";\n } else if (type.includes(\"text\") || type.includes(\"plain\")) {\n bodyType = \"text\";\n } else {\n bodyType = \"json\";\n }\n }\n\n // Extract body content from various possible fields\n // Priority order based on observed patterns in real data\n let body: Record<string, unknown> = {};\n\n if (v1Input.bodyFields && typeof v1Input.bodyFields === \"object\") {\n body = v1Input.bodyFields as Record<string, unknown>;\n } else if (\n v1Input.body_fields &&\n v1Input.body_fields !== null &&\n typeof v1Input.body_fields === \"object\"\n ) {\n body = v1Input.body_fields as Record<string, unknown>;\n } else if (v1Input.bodyParams && typeof v1Input.bodyParams === \"object\") {\n body = v1Input.bodyParams as Record<string, unknown>;\n } else if (v1Input.body && typeof v1Input.body === \"object\") {\n body = v1Input.body as Record<string, unknown>;\n } else if (v1Input.data && typeof v1Input.data === \"object\") {\n body = v1Input.data as Record<string, unknown>;\n } else if (v1Input.properties && typeof v1Input.properties === \"object\") {\n // Some endpoints have properties directly at the input level\n body = v1Input.properties as Record<string, unknown>;\n }\n\n return { body, bodyType };\n}\n\n/**\n * Extracts discovery info from v1 PaymentRequirements and transforms to v2 format\n *\n * In v1, the discovery information is stored in the `outputSchema` field,\n * which contains both input (endpoint shape) and output (response schema) information.\n *\n * This function makes smart assumptions to normalize v1 data into v2 DiscoveryInfo format:\n * - For GET/HEAD/DELETE: Looks for queryParams, query, or params fields\n * - For POST/PUT/PATCH: Looks for bodyFields, body, or data fields and normalizes bodyType\n * - Extracts optional headers if present\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns Discovery info in v2 format if present and valid, or null if not discoverable\n *\n * @example\n * ```typescript\n * const requirements: PaymentRequirementsV1 = {\n * scheme: \"exact\",\n * network: \"eip155:8453\",\n * maxAmountRequired: \"100000\",\n * resource: \"https://api.example.com/data\",\n * description: \"Get data\",\n * mimeType: \"application/json\",\n * outputSchema: {\n * input: {\n * type: \"http\",\n * method: \"GET\",\n * discoverable: true,\n * queryParams: { query: \"string\" }\n * },\n * output: { type: \"object\" }\n * },\n * payTo: \"0x...\",\n * maxTimeoutSeconds: 300,\n * asset: \"0x...\",\n * extra: {}\n * };\n *\n * const info = extractDiscoveryInfoV1(requirements);\n * if (info) {\n * console.log(\"Endpoint method:\", info.input.method);\n * }\n * ```\n */\nexport function extractDiscoveryInfoV1(\n paymentRequirements: PaymentRequirementsV1,\n): DiscoveryInfo | null {\n const { outputSchema } = paymentRequirements;\n\n // Check if outputSchema exists and has the expected structure\n if (!outputSchema || !hasV1OutputSchema(outputSchema)) {\n return null;\n }\n\n const v1Input = outputSchema.input;\n\n // Check if the endpoint is marked as discoverable\n // Default to true if not specified (for backwards compatibility)\n const isDiscoverable = v1Input.discoverable ?? true;\n\n if (!isDiscoverable) {\n return null;\n }\n\n const method = typeof v1Input.method === \"string\" ? v1Input.method.toUpperCase() : \"\";\n\n // Extract headers if present (check both camelCase and snake_case)\n const headersRaw = v1Input.headerFields || v1Input.header_fields || v1Input.headers;\n const headers =\n headersRaw && typeof headersRaw === \"object\"\n ? (headersRaw as Record<string, string>)\n : undefined;\n\n // Extract output example/schema if present\n const output = outputSchema.output\n ? {\n type: \"json\" as const,\n example: outputSchema.output,\n }\n : undefined;\n\n // Transform based on method type\n if (isQueryMethod(method)) {\n // Query parameter method (GET, HEAD, DELETE)\n const queryParams = extractQueryParams(v1Input);\n\n const discoveryInfo: QueryDiscoveryInfo = {\n input: {\n type: \"http\",\n method: method as QueryParamMethods,\n ...(queryParams ? { queryParams } : {}),\n ...(headers ? { headers } : {}),\n },\n ...(output ? { output } : {}),\n };\n\n return discoveryInfo;\n } else if (isBodyMethod(method)) {\n // Body method (POST, PUT, PATCH)\n const { body, bodyType } = extractBodyInfo(v1Input);\n const queryParams = extractQueryParams(v1Input); // Some POST requests also have query params\n\n const discoveryInfo: BodyDiscoveryInfo = {\n input: {\n type: \"http\",\n method: method as BodyMethods,\n bodyType,\n body,\n ...(queryParams ? { queryParams } : {}),\n ...(headers ? { headers } : {}),\n },\n ...(output ? { output } : {}),\n };\n\n return discoveryInfo;\n }\n\n // Unsupported method, return null\n return null;\n}\n\n/**\n * Checks if v1 PaymentRequirements contains discoverable information\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns True if the requirements contain valid discovery info\n *\n * @example\n * ```typescript\n * if (isDiscoverableV1(requirements)) {\n * const info = extractDiscoveryInfoV1(requirements);\n * // Catalog info in Bazaar\n * }\n * ```\n */\nexport function isDiscoverableV1(paymentRequirements: PaymentRequirementsV1): boolean {\n return extractDiscoveryInfoV1(paymentRequirements) !== null;\n}\n\n/**\n * Extracts resource metadata from v1 PaymentRequirements\n *\n * In v1, resource information is embedded directly in the payment requirements\n * rather than in a separate resource object.\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns Resource metadata\n *\n * @example\n * ```typescript\n * const metadata = extractResourceMetadataV1(requirements);\n * console.log(\"Resource URL:\", metadata.url);\n * console.log(\"Description:\", metadata.description);\n * ```\n */\nexport function extractResourceMetadataV1(paymentRequirements: PaymentRequirementsV1): {\n url: string;\n description: string;\n mimeType: string;\n} {\n return {\n url: paymentRequirements.resource,\n description: paymentRequirements.description,\n mimeType: paymentRequirements.mimeType,\n };\n}\n","/**\n * Client extensions for querying Bazaar discovery resources\n */\n\nimport { HTTPFacilitatorClient } from \"@t402/core/http\";\nimport { WithExtensions } from \"../types\";\n\n/**\n * Parameters for listing discovery resources.\n * All parameters are optional and used for filtering/pagination.\n */\nexport interface ListDiscoveryResourcesParams {\n /**\n * Filter by protocol type (e.g., \"http\", \"mcp\").\n * Currently, the only supported protocol type is \"http\".\n */\n type?: string;\n\n /**\n * The number of discovered t402 resources to return per page.\n */\n limit?: number;\n\n /**\n * The offset of the first discovered t402 resource to return.\n */\n offset?: number;\n}\n\n/**\n * A discovered t402 resource from the bazaar.\n */\nexport interface DiscoveryResource {\n /** The URL of the discovered resource */\n url: string;\n /** The protocol type of the resource */\n type: string;\n /** Additional metadata about the resource */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Response from listing discovery resources.\n */\nexport interface DiscoveryResourcesResponse {\n /** The list of discovered resources */\n resources: DiscoveryResource[];\n /** Total count of resources matching the query */\n total?: number;\n /** The limit used for this query */\n limit?: number;\n /** The offset used for this query */\n offset?: number;\n}\n\n/**\n * Bazaar client extension interface providing discovery query functionality.\n */\nexport interface BazaarClientExtension {\n discovery: {\n /**\n * List t402 discovery resources from the bazaar.\n *\n * @param params - Optional filtering and pagination parameters\n * @returns A promise resolving to the discovery resources response\n */\n listResources(params?: ListDiscoveryResourcesParams): Promise<DiscoveryResourcesResponse>;\n };\n}\n\n/**\n * Extends a facilitator client with Bazaar discovery query functionality.\n * Preserves and merges with any existing extensions from prior chaining.\n *\n * @param client - The facilitator client to extend\n * @returns The client extended with bazaar discovery capabilities\n *\n * @example\n * ```ts\n * // Basic usage\n * const client = withBazaar(new HTTPFacilitatorClient());\n * const resources = await client.extensions.discovery.listResources({ type: \"http\" });\n *\n * // Chaining with other extensions\n * const client = withBazaar(withOtherExtension(new HTTPFacilitatorClient()));\n * await client.extensions.other.someMethod();\n * await client.extensions.discovery.listResources();\n * ```\n */\nexport function withBazaar<T extends HTTPFacilitatorClient>(\n client: T,\n): WithExtensions<T, BazaarClientExtension> {\n // Preserve any existing extensions from prior chaining\n const existingExtensions =\n (client as T & { extensions?: Record<string, unknown> }).extensions ?? {};\n\n const extended = client as WithExtensions<T, BazaarClientExtension>;\n\n extended.extensions = {\n ...existingExtensions,\n discovery: {\n async listResources(\n params?: ListDiscoveryResourcesParams,\n ): Promise<DiscoveryResourcesResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n const authHeaders = await client.createAuthHeaders(\"discovery\");\n headers = { ...headers, ...authHeaders.headers };\n\n const queryParams = new URLSearchParams();\n if (params?.type !== undefined) {\n queryParams.set(\"type\", params.type);\n }\n if (params?.limit !== undefined) {\n queryParams.set(\"limit\", params.limit.toString());\n }\n if (params?.offset !== undefined) {\n queryParams.set(\"offset\", params.offset.toString());\n }\n\n const queryString = queryParams.toString();\n const endpoint = `${client.url}/discovery/resources${queryString ? `?${queryString}` : \"\"}`;\n\n const response = await fetch(endpoint, {\n method: \"GET\",\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n throw new Error(\n `Facilitator listDiscoveryResources failed (${response.status}): ${errorText}`,\n );\n }\n\n return (await response.json()) as DiscoveryResourcesResponse;\n },\n },\n } as WithExtensions<T, BazaarClientExtension>[\"extensions\"];\n\n return extended;\n}\n","/**\n * Sign-In-With-X (SIWx) Server-Side Implementation\n *\n * Provides functions for servers to declare SIWx requirements,\n * parse client headers, and verify signatures.\n */\n\nimport { randomBytes } from \"crypto\";\nimport { keccak_256 } from \"@noble/hashes/sha3\";\nimport { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils\";\nimport {\n SIWxExtension,\n SIWxExtensionInfo,\n SIWxPayload,\n DeclareSIWxOptions,\n ValidateSIWxOptions,\n VerifySIWxOptions,\n SIWxValidationResult,\n SIWxVerificationResult,\n} from \"./types.js\";\n\n/**\n * JSON Schema for SIWx payload validation.\n */\nconst SIWX_SCHEMA = {\n type: \"object\",\n required: [\"domain\", \"address\", \"uri\", \"version\", \"chainId\", \"nonce\", \"issuedAt\", \"signature\"],\n properties: {\n domain: { type: \"string\" },\n address: { type: \"string\" },\n statement: { type: \"string\" },\n uri: { type: \"string\" },\n version: { type: \"string\" },\n chainId: { type: \"string\" },\n nonce: { type: \"string\" },\n issuedAt: { type: \"string\", format: \"date-time\" },\n expirationTime: { type: \"string\", format: \"date-time\" },\n notBefore: { type: \"string\", format: \"date-time\" },\n requestId: { type: \"string\" },\n resources: { type: \"array\", items: { type: \"string\" } },\n signature: { type: \"string\" },\n },\n};\n\n/**\n * EIP-1271 magic value for valid signatures.\n */\nconst EIP1271_MAGIC_VALUE = \"0x1626ba7e\";\n\n/**\n * Extracts domain from a resource URI.\n *\n * @param resourceUri - Full resource URI (e.g., \"https://api.example.com/resource\")\n * @returns Domain without protocol (e.g., \"api.example.com\")\n */\nfunction extractDomain(resourceUri: string): string {\n try {\n const url = new URL(resourceUri);\n return url.host;\n } catch {\n // Fallback for non-URL formats\n return resourceUri.replace(/^https?:\\/\\//, \"\").split(\"/\")[0];\n }\n}\n\n/**\n * Generates a cryptographically secure nonce.\n *\n * @returns 32-byte hex-encoded nonce\n */\nfunction generateNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * Declares a SIWx extension for server responses.\n *\n * @param options - Extension declaration options\n * @returns SIWx extension object ready for response\n *\n * @example\n * ```typescript\n * const extension = declareSIWxExtension({\n * resourceUri: \"https://api.example.com/premium\",\n * network: \"eip155:8453\",\n * statement: \"Sign in to access premium content\",\n * });\n * ```\n */\nexport function declareSIWxExtension(options: DeclareSIWxOptions): SIWxExtension {\n const domain = extractDomain(options.resourceUri);\n const now = new Date();\n const expirationTime =\n options.expirationTime || new Date(now.getTime() + 5 * 60 * 1000).toISOString();\n\n const info: SIWxExtensionInfo = {\n domain,\n uri: options.resourceUri,\n statement: options.statement,\n version: options.version || \"1\",\n chainId: options.network,\n nonce: generateNonce(),\n issuedAt: now.toISOString(),\n expirationTime,\n resources: [options.resourceUri],\n signatureScheme: options.signatureScheme,\n };\n\n return {\n info,\n schema: SIWX_SCHEMA,\n };\n}\n\n/**\n * Parses a SIWx header from client request.\n *\n * The header format is base64-encoded JSON.\n *\n * @param header - Base64-encoded SIWx header value\n * @returns Parsed SIWx payload\n * @throws Error if header is invalid\n *\n * @example\n * ```typescript\n * const payload = parseSIWxHeader(request.headers['x-t402-siwx']);\n * ```\n */\nexport function parseSIWxHeader(header: string): SIWxPayload {\n if (!header) {\n throw new Error(\"Missing SIWx header\");\n }\n\n try {\n const decoded = Buffer.from(header, \"base64\").toString(\"utf-8\");\n const payload = JSON.parse(decoded) as SIWxPayload;\n\n // Validate required fields\n const required = [\n \"domain\",\n \"address\",\n \"uri\",\n \"version\",\n \"chainId\",\n \"nonce\",\n \"issuedAt\",\n \"signature\",\n ];\n for (const field of required) {\n if (!(field in payload)) {\n throw new Error(`Missing required field: ${field}`);\n }\n }\n\n return payload;\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new Error(\"Invalid SIWx header: malformed JSON\");\n }\n throw error;\n }\n}\n\n/**\n * Validates a SIWx message against expected values.\n *\n * @param message - The SIWx payload to validate\n * @param expectedResourceUri - Expected resource URI (domain validated from this)\n * @param options - Validation options\n * @returns Validation result\n *\n * @example\n * ```typescript\n * const result = validateSIWxMessage(payload, \"https://api.example.com/premium\", {\n * maxAge: 5 * 60 * 1000, // 5 minutes\n * checkNonce: (nonce) => usedNonces.has(nonce) === false,\n * });\n * ```\n */\nexport function validateSIWxMessage(\n message: SIWxPayload,\n expectedResourceUri: string,\n options: ValidateSIWxOptions = {},\n): SIWxValidationResult {\n const { maxAge = 5 * 60 * 1000, checkNonce } = options;\n\n // Validate domain matches\n const expectedDomain = extractDomain(expectedResourceUri);\n if (message.domain !== expectedDomain) {\n return {\n valid: false,\n error: `Domain mismatch: expected ${expectedDomain}, got ${message.domain}`,\n };\n }\n\n // Validate URI matches\n if (message.uri !== expectedResourceUri) {\n return {\n valid: false,\n error: `URI mismatch: expected ${expectedResourceUri}, got ${message.uri}`,\n };\n }\n\n // Validate version\n if (message.version !== \"1\") {\n return { valid: false, error: `Unsupported version: ${message.version}` };\n }\n\n // Validate issuedAt is not too old\n const issuedAt = new Date(message.issuedAt);\n const now = new Date();\n if (now.getTime() - issuedAt.getTime() > maxAge) {\n return { valid: false, error: \"Message has expired (issuedAt too old)\" };\n }\n\n // Validate expirationTime if present\n if (message.expirationTime) {\n const expiration = new Date(message.expirationTime);\n if (expiration < now) {\n return { valid: false, error: \"Message has expired\" };\n }\n }\n\n // Validate notBefore if present\n if (message.notBefore) {\n const notBefore = new Date(message.notBefore);\n if (notBefore > now) {\n return { valid: false, error: \"Message not yet valid (notBefore in future)\" };\n }\n }\n\n // Custom nonce validation\n if (checkNonce && !checkNonce(message.nonce)) {\n return { valid: false, error: \"Invalid nonce (replay attack detected)\" };\n }\n\n return { valid: true };\n}\n\n/**\n * Verifies a SIWx signature.\n *\n * Supports EIP-191 personal signatures and can optionally verify\n * smart wallet signatures via EIP-1271/6492.\n *\n * @param message - The SIWx payload to verify\n * @param signature - The signature to verify (hex-encoded)\n * @param options - Verification options\n * @returns Verification result with recovered address\n *\n * @example\n * ```typescript\n * const result = await verifySIWxSignature(payload, payload.signature, {\n * checkSmartWallet: true,\n * provider: web3Provider,\n * });\n * ```\n */\nexport async function verifySIWxSignature(\n message: SIWxPayload,\n signature: string,\n options: VerifySIWxOptions = {},\n): Promise<SIWxVerificationResult> {\n const { checkSmartWallet = false } = options;\n\n try {\n // Reconstruct the CAIP-122 message that was signed\n const messageText = constructMessage(message);\n\n // Hash the message with Ethereum prefix\n const messageHash = hashMessage(messageText);\n\n // Try to recover the signer address\n const recoveredAddress = recoverAddress(messageHash, signature);\n\n // Check if recovered address matches claimed address\n if (recoveredAddress.toLowerCase() !== message.address.toLowerCase()) {\n // If smart wallet checking is enabled, try EIP-1271 verification\n if (checkSmartWallet && options.provider) {\n const isValidSmartWallet = await verifySmartWalletSignature(\n message.address,\n messageHash,\n signature,\n options.provider,\n );\n\n if (isValidSmartWallet) {\n return { valid: true, address: message.address };\n }\n }\n\n return {\n valid: false,\n address: recoveredAddress,\n error: `Signature mismatch: expected ${message.address}, recovered ${recoveredAddress}`,\n };\n }\n\n return { valid: true, address: recoveredAddress };\n } catch (error) {\n return {\n valid: false,\n error: `Signature verification failed: ${error instanceof Error ? error.message : \"unknown error\"}`,\n };\n }\n}\n\n/**\n * Constructs the CAIP-122 message string from payload.\n *\n * @param payload - SIWx payload\n * @returns CAIP-122 formatted message string\n */\nexport function constructMessage(payload: SIWxPayload): string {\n const lines: string[] = [];\n\n // Header\n lines.push(`${payload.domain} wants you to sign in with your ${payload.chainId} account:`);\n lines.push(payload.address);\n lines.push(\"\");\n\n // Statement (optional)\n if (payload.statement) {\n lines.push(payload.statement);\n lines.push(\"\");\n }\n\n // Required fields\n lines.push(`URI: ${payload.uri}`);\n lines.push(`Version: ${payload.version}`);\n lines.push(`Chain ID: ${payload.chainId}`);\n lines.push(`Nonce: ${payload.nonce}`);\n lines.push(`Issued At: ${payload.issuedAt}`);\n\n // Optional fields\n if (payload.expirationTime) {\n lines.push(`Expiration Time: ${payload.expirationTime}`);\n }\n if (payload.notBefore) {\n lines.push(`Not Before: ${payload.notBefore}`);\n }\n if (payload.requestId) {\n lines.push(`Request ID: ${payload.requestId}`);\n }\n\n // Resources\n if (payload.resources && payload.resources.length > 0) {\n lines.push(\"Resources:\");\n for (const resource of payload.resources) {\n lines.push(`- ${resource}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Hashes a message with the Ethereum signed message prefix (EIP-191).\n *\n * @param message - Message to hash\n * @returns Hex-encoded keccak256 hash with 0x prefix\n */\nexport function hashMessage(message: string): string {\n const messageBytes = new TextEncoder().encode(message);\n const prefix = `\\x19Ethereum Signed Message:\\n${messageBytes.length}`;\n const prefixBytes = new TextEncoder().encode(prefix);\n\n // Concatenate prefix and message\n const combined = new Uint8Array(prefixBytes.length + messageBytes.length);\n combined.set(prefixBytes, 0);\n combined.set(messageBytes, prefixBytes.length);\n\n // Hash with keccak256\n const hash = keccak_256(combined);\n return \"0x\" + bytesToHex(hash);\n}\n\n/**\n * Recovers the signer address from an EIP-191 signature.\n *\n * @param messageHash - Keccak256 hash of the prefixed message (with 0x prefix)\n * @param signature - Hex-encoded signature (65 bytes: r + s + v)\n * @returns Checksummed Ethereum address\n */\nfunction recoverAddress(messageHash: string, signature: string): string {\n // Remove 0x prefix if present\n const sigHex = signature.startsWith(\"0x\") ? signature.slice(2) : signature;\n const hashHex = messageHash.startsWith(\"0x\") ? messageHash.slice(2) : messageHash;\n\n if (sigHex.length !== 130) {\n throw new Error(`Invalid signature length: expected 130 hex chars, got ${sigHex.length}`);\n }\n\n // Parse signature components\n const r = BigInt(\"0x\" + sigHex.slice(0, 64));\n const s = BigInt(\"0x\" + sigHex.slice(64, 128));\n let v = parseInt(sigHex.slice(128, 130), 16);\n\n // Normalize v to 0 or 1 (EIP-155 compatibility)\n if (v >= 27) {\n v -= 27;\n }\n\n if (v !== 0 && v !== 1) {\n throw new Error(`Invalid recovery id: ${v}`);\n }\n\n // Create signature object\n const sig = new secp256k1.Signature(r, s).addRecoveryBit(v);\n\n // Recover public key\n const hashBytes = hexToBytes(hashHex);\n const publicKey = sig.recoverPublicKey(hashBytes);\n\n // Get uncompressed public key (65 bytes) and remove the 04 prefix\n const pubKeyBytes = publicKey.toRawBytes(false).slice(1);\n\n // Hash public key to get address\n const addressHash = keccak_256(pubKeyBytes);\n\n // Take last 20 bytes\n const addressBytes = addressHash.slice(-20);\n const address = \"0x\" + bytesToHex(addressBytes);\n\n // Return checksummed address\n return toChecksumAddress(address);\n}\n\n/**\n * Converts an Ethereum address to checksummed format (EIP-55).\n *\n * @param address - Ethereum address (with or without 0x prefix)\n * @returns Checksummed address with 0x prefix\n */\nfunction toChecksumAddress(address: string): string {\n const addr = address.toLowerCase().replace(\"0x\", \"\");\n const hash = bytesToHex(keccak_256(new TextEncoder().encode(addr)));\n\n let checksummed = \"0x\";\n for (let i = 0; i < 40; i++) {\n if (parseInt(hash[i], 16) >= 8) {\n checksummed += addr[i].toUpperCase();\n } else {\n checksummed += addr[i];\n }\n }\n\n return checksummed;\n}\n\n/**\n * Verifies a smart wallet signature using EIP-1271.\n *\n * @param walletAddress - Smart wallet contract address\n * @param messageHash - Hash of the message that was signed\n * @param signature - The signature to verify\n * @param provider - Ethereum provider with call capability\n * @returns True if signature is valid according to the smart wallet\n */\nasync function verifySmartWalletSignature(\n walletAddress: string,\n messageHash: string,\n signature: string,\n provider: unknown,\n): Promise<boolean> {\n // Type guard for provider\n interface EthProvider {\n request(args: { method: string; params: unknown[] }): Promise<unknown>;\n }\n\n /**\n * Type guard for Ethereum provider interface\n *\n * @param p - Value to check\n * @returns True if value is an EthProvider\n */\n function isEthProvider(p: unknown): p is EthProvider {\n return typeof p === \"object\" && p !== null && \"request\" in p;\n }\n\n if (!isEthProvider(provider)) {\n return false;\n }\n\n try {\n // EIP-1271 isValidSignature(bytes32 hash, bytes signature) returns bytes4\n const hashHex = messageHash.startsWith(\"0x\") ? messageHash : \"0x\" + messageHash;\n const sigHex = signature.startsWith(\"0x\") ? signature : \"0x\" + signature;\n\n // Encode function call\n // isValidSignature(bytes32,bytes) selector: 0x1626ba7e\n const data =\n \"0x1626ba7e\" +\n hashHex.slice(2).padStart(64, \"0\") + // bytes32 hash\n \"0000000000000000000000000000000000000000000000000000000000000040\" + // offset to bytes\n (sigHex.length / 2 - 1).toString(16).padStart(64, \"0\") + // bytes length\n sigHex.slice(2).padEnd(Math.ceil((sigHex.length - 2) / 64) * 64, \"0\"); // bytes data\n\n const result = (await provider.request({\n method: \"eth_call\",\n params: [{ to: walletAddress, data }, \"latest\"],\n })) as string;\n\n // Check if result matches magic value\n return result.toLowerCase().startsWith(EIP1271_MAGIC_VALUE);\n } catch {\n return false;\n }\n}\n\n/**\n * Verifies a signature using EIP-6492 (universal signature verification).\n *\n * This supports both deployed and undeployed smart wallets.\n *\n * @param walletAddress - Wallet address (may be counterfactual)\n * @param messageHash - Hash of the message that was signed\n * @param signature - The signature (may include deployment data)\n * @param provider - Ethereum provider\n * @returns True if signature is valid\n */\nexport async function verifyEIP6492Signature(\n walletAddress: string,\n messageHash: string,\n signature: string,\n provider: unknown,\n): Promise<boolean> {\n // EIP-6492 signatures end with the magic suffix\n const EIP6492_SUFFIX = \"6492649264926492649264926492649264926492649264926492649264926492\";\n const sigHex = signature.startsWith(\"0x\") ? signature.slice(2) : signature;\n\n if (sigHex.endsWith(EIP6492_SUFFIX)) {\n // This is an EIP-6492 signature with deployment data\n // For full implementation, we would need to:\n // 1. Deploy the wallet contract to a local fork\n // 2. Then call isValidSignature\n // This requires more complex provider interaction\n console.warn(\"EIP-6492 deployment signatures not yet fully implemented\");\n return false;\n }\n\n // Fall back to standard EIP-1271 verification\n return verifySmartWalletSignature(walletAddress, messageHash, signature, provider);\n}\n","/**\n * Sign-In-With-X (SIWx) Client-Side Implementation\n *\n * Provides functions for clients to create and sign SIWx messages.\n */\n\nimport {\n SIWxPayload,\n SIWxExtension,\n SIWxExtensionInfo,\n SIWxSigner,\n SignatureScheme,\n} from \"./types.js\";\nimport { constructMessage } from \"./server.js\";\n\n/**\n * Encodes a SIWx payload for transmission in HTTP header.\n *\n * @param payload - The SIWx payload to encode\n * @returns Base64-encoded JSON string\n *\n * @example\n * ```typescript\n * const header = encodeSIWxHeader(payload);\n * fetch(url, {\n * headers: { 'X-T402-SIWx': header }\n * });\n * ```\n */\nexport function encodeSIWxHeader(payload: SIWxPayload): string {\n const json = JSON.stringify(payload);\n // Use Buffer in Node.js or btoa in browser\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(json, \"utf-8\").toString(\"base64\");\n }\n return btoa(json);\n}\n\n/**\n * Creates a CAIP-122 formatted message string from server info.\n *\n * @param serverInfo - Extension info from server\n * @param address - Wallet address signing the message\n * @returns CAIP-122 formatted message string ready for signing\n *\n * @example\n * ```typescript\n * const message = createSIWxMessage(extension.info, wallet.address);\n * const signature = await wallet.signMessage(message);\n * ```\n */\nexport function createSIWxMessage(serverInfo: SIWxExtensionInfo, address: string): string {\n // Create a temporary payload for message construction\n const payload: SIWxPayload = {\n domain: serverInfo.domain,\n address,\n statement: serverInfo.statement,\n uri: serverInfo.uri,\n version: serverInfo.version,\n chainId: serverInfo.chainId,\n nonce: serverInfo.nonce,\n issuedAt: serverInfo.issuedAt,\n expirationTime: serverInfo.expirationTime,\n notBefore: serverInfo.notBefore,\n requestId: serverInfo.requestId,\n resources: serverInfo.resources,\n signature: \"\", // Will be added after signing\n };\n\n return constructMessage(payload);\n}\n\n/**\n * Creates EIP-712 typed data for SIWx signing.\n *\n * @param serverInfo - Extension info from server\n * @param address - Wallet address signing the message\n * @returns EIP-712 typed data object\n */\nexport function createSIWxTypedData(\n serverInfo: SIWxExtensionInfo,\n address: string,\n): {\n domain: {\n name: string;\n version: string;\n chainId: number;\n };\n types: {\n SIWx: Array<{ name: string; type: string }>;\n };\n primaryType: \"SIWx\";\n message: Record<string, unknown>;\n} {\n // Extract chain ID number from CAIP-2 format (e.g., \"eip155:8453\" -> 8453)\n const chainIdParts = serverInfo.chainId.split(\":\");\n const chainIdNum =\n chainIdParts.length > 1 ? parseInt(chainIdParts[1], 10) : parseInt(chainIdParts[0], 10);\n\n return {\n domain: {\n name: serverInfo.domain,\n version: serverInfo.version,\n chainId: chainIdNum,\n },\n types: {\n SIWx: [\n { name: \"domain\", type: \"string\" },\n { name: \"address\", type: \"address\" },\n { name: \"statement\", type: \"string\" },\n { name: \"uri\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"string\" },\n { name: \"nonce\", type: \"string\" },\n { name: \"issuedAt\", type: \"string\" },\n { name: \"expirationTime\", type: \"string\" },\n { name: \"resources\", type: \"string[]\" },\n ],\n },\n primaryType: \"SIWx\",\n message: {\n domain: serverInfo.domain,\n address,\n statement: serverInfo.statement || \"\",\n uri: serverInfo.uri,\n version: serverInfo.version,\n chainId: serverInfo.chainId,\n nonce: serverInfo.nonce,\n issuedAt: serverInfo.issuedAt,\n expirationTime: serverInfo.expirationTime || \"\",\n resources: serverInfo.resources || [],\n },\n };\n}\n\n/**\n * Signs a SIWx message using the provided signer.\n *\n * @param message - CAIP-122 formatted message to sign\n * @param signer - Wallet/signer interface with signMessage\n * @param options - Signing options\n * @param options.signatureScheme - Signature scheme to use\n * @param options.serverInfo - Server info for verification\n * @returns Hex-encoded signature\n *\n * @example\n * ```typescript\n * const signature = await signSIWxMessage(message, wallet, {\n * signatureScheme: 'eip191'\n * });\n * ```\n */\nexport async function signSIWxMessage(\n message: string,\n signer: SIWxSigner,\n options?: { signatureScheme?: SignatureScheme; serverInfo?: SIWxExtensionInfo },\n): Promise<string> {\n const scheme = options?.signatureScheme || \"eip191\";\n\n switch (scheme) {\n case \"eip191\":\n if (!signer.signMessage) {\n throw new Error(\"Signer does not support personal_sign (EIP-191)\");\n }\n return signer.signMessage(message);\n\n case \"eip712\":\n if (!signer.signTypedData) {\n throw new Error(\"Signer does not support signTypedData (EIP-712)\");\n }\n if (!options?.serverInfo) {\n throw new Error(\"EIP-712 signing requires serverInfo in options\");\n }\n const typedData = createSIWxTypedData(options.serverInfo, signer.address);\n return signer.signTypedData(typedData);\n\n case \"eip1271\":\n case \"eip6492\":\n // Smart wallet signatures go through the same signMessage path\n // but verification happens on-chain\n if (!signer.signMessage) {\n throw new Error(\"Signer does not support signing\");\n }\n return signer.signMessage(message);\n\n case \"siws\":\n // Sign-In With Solana uses Ed25519 signatures\n if (!signer.signMessage) {\n throw new Error(\"Signer does not support signing\");\n }\n // Solana wallets typically implement signMessage that handles the encoding\n return signer.signMessage(message);\n\n case \"sep10\":\n throw new Error(\"Stellar SEP-10 signing not yet implemented\");\n\n default:\n throw new Error(`Unknown signature scheme: ${scheme}`);\n }\n}\n\n/**\n * Creates a complete SIWx payload from server extension and signer.\n *\n * This is the main entry point for clients - it handles message construction,\n * signing, and payload assembly.\n *\n * @param serverExtension - Extension from server's 402 response\n * @param signer - Wallet/signer interface\n * @returns Complete signed SIWx payload ready for header encoding\n *\n * @example\n * ```typescript\n * // Get extension from server 402 response\n * const extension = paymentRequirements.extensions?.siwx;\n *\n * // Create signed payload\n * const payload = await createSIWxPayload(extension, wallet);\n *\n * // Encode and send with retry\n * const header = encodeSIWxHeader(payload);\n * fetch(url, {\n * headers: { 'X-T402-SIWx': header }\n * });\n * ```\n */\nexport async function createSIWxPayload(\n serverExtension: SIWxExtension,\n signer: SIWxSigner,\n): Promise<SIWxPayload> {\n const { info } = serverExtension;\n\n // Create the message to sign\n const message = createSIWxMessage(info, signer.address);\n\n // Sign the message\n const signature = await signSIWxMessage(message, signer, {\n signatureScheme: info.signatureScheme,\n serverInfo: info,\n });\n\n // Assemble the complete payload\n return {\n domain: info.domain,\n address: signer.address,\n statement: info.statement,\n uri: info.uri,\n version: info.version,\n chainId: info.chainId,\n nonce: info.nonce,\n issuedAt: info.issuedAt,\n expirationTime: info.expirationTime,\n notBefore: info.notBefore,\n requestId: info.requestId,\n resources: info.resources,\n signature,\n };\n}\n\n/**\n * Extension key for SIWx in payment requirements.\n */\nexport const SIWX_EXTENSION_KEY = \"siwx\";\n\n/**\n * HTTP header name for SIWx payload.\n */\nexport const SIWX_HEADER_NAME = \"X-T402-SIWx\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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,IAChB;AAAA,EACF;AACF;AAKO,IAAM,qBAAqB;AAK3B,IAAM,mBAAmB;","names":["isBodyMethod","Ajv"]}
1
+ {"version":3,"sources":["../../src/index.ts","../../src/bazaar/types.ts","../../src/bazaar/resourceService.ts","../../src/bazaar/server.ts","../../src/bazaar/facilitator.ts","../../src/bazaar/v1/facilitator.ts","../../src/bazaar/facilitatorClient.ts","../../src/sign-in-with-x/server.ts","../../src/sign-in-with-x/client.ts"],"sourcesContent":["// Shared extension utilities\nexport type { WithExtensions } from \"./types\";\n\n// Bazaar extension\nexport * from \"./bazaar\";\nexport { bazaarResourceServerExtension } from \"./bazaar/server\";\n\n// Sign-in-with-x extension\nexport * from \"./sign-in-with-x\";\n","/**\n * Type definitions for the Bazaar Discovery Extension\n */\n\nimport type { BodyMethods, QueryParamMethods } from \"@t402/core/http\";\n\n/**\n * Extension identifier constant for the Bazaar discovery extension\n */\nexport const BAZAAR = \"bazaar\";\n\n/**\n * Discovery info for query parameter methods (GET, HEAD, DELETE)\n */\nexport interface QueryDiscoveryInfo {\n input: {\n type: \"http\";\n method: QueryParamMethods;\n queryParams?: Record<string, unknown>;\n headers?: Record<string, string>;\n };\n output?: {\n type?: string;\n format?: string;\n example?: unknown;\n };\n}\n\n/**\n * Discovery info for body methods (POST, PUT, PATCH)\n */\nexport interface BodyDiscoveryInfo {\n input: {\n type: \"http\";\n method: BodyMethods;\n bodyType: \"json\" | \"form-data\" | \"text\";\n body: Record<string, unknown>;\n queryParams?: Record<string, unknown>;\n headers?: Record<string, string>;\n };\n output?: {\n type?: string;\n format?: string;\n example?: unknown;\n };\n}\n\n/**\n * Combined discovery info type\n */\nexport type DiscoveryInfo = QueryDiscoveryInfo | BodyDiscoveryInfo;\n\n/**\n * Discovery extension for query parameter methods (GET, HEAD, DELETE)\n */\nexport interface QueryDiscoveryExtension {\n info: QueryDiscoveryInfo;\n\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n type: \"object\";\n properties: {\n input: {\n type: \"object\";\n properties: {\n type: {\n type: \"string\";\n const: \"http\";\n };\n method: {\n type: \"string\";\n enum: QueryParamMethods[];\n };\n queryParams?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n };\n headers?: {\n type: \"object\";\n additionalProperties: {\n type: \"string\";\n };\n };\n };\n required: (\"type\" | \"method\")[];\n additionalProperties?: boolean;\n };\n output?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: readonly string[];\n additionalProperties?: boolean;\n };\n };\n required: [\"input\"];\n };\n}\n\n/**\n * Discovery extension for body methods (POST, PUT, PATCH)\n */\nexport interface BodyDiscoveryExtension {\n info: BodyDiscoveryInfo;\n\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n type: \"object\";\n properties: {\n input: {\n type: \"object\";\n properties: {\n type: {\n type: \"string\";\n const: \"http\";\n };\n method: {\n type: \"string\";\n enum: BodyMethods[];\n };\n bodyType: {\n type: \"string\";\n enum: [\"json\", \"form-data\", \"text\"];\n };\n body: Record<string, unknown>;\n queryParams?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n };\n headers?: {\n type: \"object\";\n additionalProperties: {\n type: \"string\";\n };\n };\n };\n required: (\"type\" | \"method\" | \"bodyType\" | \"body\")[];\n additionalProperties?: boolean;\n };\n output?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: readonly string[];\n additionalProperties?: boolean;\n };\n };\n required: [\"input\"];\n };\n}\n\n/**\n * Combined discovery extension type\n */\nexport type DiscoveryExtension = QueryDiscoveryExtension | BodyDiscoveryExtension;\n\nexport interface DeclareQueryDiscoveryExtensionConfig {\n method?: QueryParamMethods;\n input?: Record<string, unknown>;\n inputSchema?: Record<string, unknown>;\n output?: {\n example?: unknown;\n schema?: Record<string, unknown>;\n };\n}\n\nexport interface DeclareBodyDiscoveryExtensionConfig {\n method?: BodyMethods;\n input?: Record<string, unknown>;\n inputSchema?: Record<string, unknown>;\n bodyType?: \"json\" | \"form-data\" | \"text\";\n output?: {\n example?: unknown;\n schema?: Record<string, unknown>;\n };\n}\n\nexport type DeclareDiscoveryExtensionConfig =\n | DeclareQueryDiscoveryExtensionConfig\n | DeclareBodyDiscoveryExtensionConfig;\n\nexport const isQueryExtensionConfig = (\n config: DeclareDiscoveryExtensionConfig,\n): config is DeclareQueryDiscoveryExtensionConfig => {\n return !(\"bodyType\" in config);\n};\n\nexport const isBodyExtensionConfig = (\n config: DeclareDiscoveryExtensionConfig,\n): config is DeclareBodyDiscoveryExtensionConfig => {\n return \"bodyType\" in config;\n};\n","/**\n * Resource Service functions for creating Bazaar discovery extensions\n *\n * These functions help servers declare the shape of their endpoints\n * for facilitator discovery and cataloging in the Bazaar.\n */\n\nimport {\n type DiscoveryExtension,\n type QueryDiscoveryExtension,\n type BodyDiscoveryExtension,\n type DeclareDiscoveryExtensionConfig,\n type DeclareQueryDiscoveryExtensionConfig,\n type DeclareBodyDiscoveryExtensionConfig,\n} from \"./types\";\n\n/**\n * Internal helper to create a query discovery extension\n *\n * @param root0 - Configuration object for query discovery extension\n * @param root0.method - HTTP method (GET, HEAD, DELETE)\n * @param root0.input - Query parameters\n * @param root0.inputSchema - JSON schema for query parameters\n * @param root0.output - Output specification with example\n * @returns QueryDiscoveryExtension with info and schema\n */\nfunction createQueryDiscoveryExtension({\n method,\n input = {},\n inputSchema = { properties: {} },\n output,\n}: DeclareQueryDiscoveryExtensionConfig): QueryDiscoveryExtension {\n return {\n info: {\n input: {\n type: \"http\",\n ...(method ? { method } : {}),\n ...(input ? { queryParams: input } : {}),\n } as QueryDiscoveryExtension[\"info\"][\"input\"],\n ...(output?.example\n ? {\n output: {\n type: \"json\",\n example: output.example,\n },\n }\n : {}),\n },\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n const: \"http\",\n },\n method: {\n type: \"string\",\n enum: [\"GET\", \"HEAD\", \"DELETE\"],\n },\n ...(inputSchema\n ? {\n queryParams: {\n type: \"object\" as const,\n ...(typeof inputSchema === \"object\" ? inputSchema : {}),\n },\n }\n : {}),\n },\n required: [\"type\"] as (\"type\" | \"method\")[],\n additionalProperties: false,\n },\n ...(output?.example\n ? {\n output: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\" as const,\n },\n example: {\n type: \"object\" as const,\n ...(output.schema && typeof output.schema === \"object\" ? output.schema : {}),\n },\n },\n required: [\"type\"] as const,\n },\n }\n : {}),\n },\n required: [\"input\"],\n },\n };\n}\n\n/**\n * Internal helper to create a body discovery extension\n *\n * @param root0 - Configuration object for body discovery extension\n * @param root0.method - HTTP method (POST, PUT, PATCH)\n * @param root0.input - Request body specification\n * @param root0.inputSchema - JSON schema for request body\n * @param root0.bodyType - Content type of body (json, form, multipart)\n * @param root0.output - Output specification with example\n * @returns BodyDiscoveryExtension with info and schema\n */\nfunction createBodyDiscoveryExtension({\n method,\n input = {},\n inputSchema = { properties: {} },\n bodyType = \"json\",\n output,\n}: DeclareBodyDiscoveryExtensionConfig): BodyDiscoveryExtension {\n return {\n info: {\n input: {\n type: \"http\",\n ...(method ? { method } : {}),\n bodyType,\n body: input,\n } as BodyDiscoveryExtension[\"info\"][\"input\"],\n ...(output?.example\n ? {\n output: {\n type: \"json\",\n example: output.example,\n },\n }\n : {}),\n },\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n const: \"http\",\n },\n method: {\n type: \"string\",\n enum: [\"POST\", \"PUT\", \"PATCH\"],\n },\n bodyType: {\n type: \"string\",\n enum: [\"json\", \"form-data\", \"text\"],\n },\n body: inputSchema,\n },\n required: [\"type\", \"bodyType\", \"body\"] as (\"type\" | \"method\" | \"bodyType\" | \"body\")[],\n additionalProperties: false,\n },\n ...(output?.example\n ? {\n output: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\" as const,\n },\n example: {\n type: \"object\" as const,\n ...(output.schema && typeof output.schema === \"object\" ? output.schema : {}),\n },\n },\n required: [\"type\"] as const,\n },\n }\n : {}),\n },\n required: [\"input\"],\n },\n };\n}\n\n/**\n * Create a discovery extension for any HTTP method\n *\n * This function helps servers declare how their endpoint should be called,\n * including the expected input parameters/body and output format.\n *\n * @param config - Configuration object for the discovery extension\n * @returns A discovery extension object with both info and schema\n *\n * @example\n * ```typescript\n * // For a GET endpoint with no input\n * const getExtension = declareDiscoveryExtension({\n * method: \"GET\",\n * output: {\n * example: { message: \"Success\", timestamp: \"2024-01-01T00:00:00Z\" }\n * }\n * });\n *\n * // For a GET endpoint with query params\n * const getWithParams = declareDiscoveryExtension({\n * method: \"GET\",\n * input: { query: \"example\" },\n * inputSchema: {\n * properties: {\n * query: { type: \"string\" }\n * },\n * required: [\"query\"]\n * }\n * });\n *\n * // For a POST endpoint with JSON body\n * const postExtension = declareDiscoveryExtension({\n * method: \"POST\",\n * input: { name: \"John\", age: 30 },\n * inputSchema: {\n * properties: {\n * name: { type: \"string\" },\n * age: { type: \"number\" }\n * },\n * required: [\"name\"]\n * },\n * bodyType: \"json\",\n * output: {\n * example: { success: true, id: \"123\" }\n * }\n * });\n * ```\n */\nexport function declareDiscoveryExtension(\n config: Omit<DeclareDiscoveryExtensionConfig, \"method\">,\n): Record<string, DiscoveryExtension> {\n const bodyType = (config as DeclareBodyDiscoveryExtensionConfig).bodyType;\n const isBodyMethod = bodyType !== undefined;\n\n const extension = isBodyMethod\n ? createBodyDiscoveryExtension(config as DeclareBodyDiscoveryExtensionConfig)\n : createQueryDiscoveryExtension(config as DeclareQueryDiscoveryExtensionConfig);\n\n return { bazaar: extension as DiscoveryExtension };\n}\n","import type { ResourceServerExtension } from \"@t402/core/types\";\nimport type { HTTPRequestContext } from \"@t402/core/http\";\nimport { BAZAAR } from \"./types\";\n\n/**\n * Type guard to check if context is an HTTP request context.\n *\n * @param ctx - The context to check\n * @returns True if context is an HTTPRequestContext\n */\nfunction isHTTPRequestContext(ctx: unknown): ctx is HTTPRequestContext {\n return ctx !== null && typeof ctx === \"object\" && \"method\" in ctx && \"adapter\" in ctx;\n}\n\ninterface ExtensionDeclaration {\n [key: string]: unknown;\n info?: {\n [key: string]: unknown;\n input?: Record<string, unknown>;\n };\n schema?: {\n [key: string]: unknown;\n properties?: {\n [key: string]: unknown;\n input?: {\n [key: string]: unknown;\n required?: string[];\n };\n };\n };\n}\n\nexport const bazaarResourceServerExtension: ResourceServerExtension = {\n key: BAZAAR,\n\n enrichDeclaration: (declaration, transportContext) => {\n if (!isHTTPRequestContext(transportContext)) {\n return declaration;\n }\n\n const extension = declaration as ExtensionDeclaration;\n const method = transportContext.method;\n\n return {\n ...extension,\n info: {\n ...(extension.info || {}),\n input: {\n ...(extension.info?.input || {}),\n method,\n },\n },\n schema: {\n ...(extension.schema || {}),\n properties: {\n ...(extension.schema?.properties || {}),\n input: {\n ...(extension.schema?.properties?.input || {}),\n required: [\n ...(extension.schema?.properties?.input?.required || []),\n ...(!(extension.schema?.properties?.input?.required || []).includes(\"method\")\n ? [\"method\"]\n : []),\n ],\n },\n },\n },\n };\n },\n};\n","/**\n * Facilitator functions for validating and extracting Bazaar discovery extensions\n *\n * These functions help facilitators validate extension data against schemas\n * and extract the discovery information for cataloging in the Bazaar.\n *\n * Supports both v2 (extensions in PaymentRequired) and v1 (outputSchema in PaymentRequirements).\n */\n\nimport Ajv from \"ajv/dist/2020\";\nimport type { PaymentPayload, PaymentRequirements, PaymentRequirementsV1 } from \"@t402/core/types\";\nimport type { DiscoveryExtension, DiscoveryInfo } from \"./types\";\nimport { BAZAAR } from \"./types\";\nimport { extractDiscoveryInfoV1 } from \"./v1/facilitator\";\n\n/**\n * Validation result for discovery extensions\n */\nexport interface ValidationResult {\n valid: boolean;\n errors?: string[];\n}\n\n/**\n * Validates a discovery extension's info against its schema\n *\n * @param extension - The discovery extension containing info and schema\n * @returns Validation result indicating if the info matches the schema\n *\n * @example\n * ```typescript\n * const extension = declareDiscoveryExtension(...);\n * const result = validateDiscoveryExtension(extension);\n *\n * if (result.valid) {\n * console.log(\"Extension is valid\");\n * } else {\n * console.error(\"Validation errors:\", result.errors);\n * }\n * ```\n */\nexport function validateDiscoveryExtension(extension: DiscoveryExtension): ValidationResult {\n try {\n const ajv = new Ajv({ strict: false, allErrors: true });\n const validate = ajv.compile(extension.schema);\n\n // The schema describes the structure of info directly\n // Schema has properties: { input: {...}, output: {...} }\n // So we validate extension.info which has { input: {...}, output: {...} }\n const valid = validate(extension.info);\n\n if (valid) {\n return { valid: true };\n }\n\n const errors = validate.errors?.map(err => {\n const path = err.instancePath || \"(root)\";\n return `${path}: ${err.message}`;\n }) || [\"Unknown validation error\"];\n\n return { valid: false, errors };\n } catch (error) {\n return {\n valid: false,\n errors: [\n `Schema validation failed: ${error instanceof Error ? error.message : String(error)}`,\n ],\n };\n }\n}\n\n/**\n * Extracts the discovery info from payment payload and requirements\n *\n * This function handles both v2 (extensions) and v1 (outputSchema) formats.\n *\n * For v2: Discovery info is in PaymentPayload.extensions (client copied it from PaymentRequired)\n * For v1: Discovery info is in PaymentRequirements.outputSchema\n *\n * V1 data is automatically transformed to v2 DiscoveryInfo format, making smart\n * assumptions about field names (queryParams/query/params for GET, bodyFields/body/data for POST, etc.)\n *\n * @param paymentPayload - The payment payload containing extensions (v2) and version info\n * @param paymentRequirements - The payment requirements (contains outputSchema for v1)\n * @param validate - Whether to validate v2 extensions before extracting (default: true)\n * @returns The discovery info in v2 format if present, or null if not discoverable\n *\n * @example\n * ```typescript\n * // V2 - extensions are in PaymentPayload\n * const info = extractDiscoveryInfo(paymentPayload, paymentRequirements);\n *\n * // V1 - discovery info is in PaymentRequirements.outputSchema\n * const info = extractDiscoveryInfo(paymentPayloadV1, paymentRequirementsV1);\n *\n * if (info) {\n * // Both v1 and v2 return the same DiscoveryInfo structure\n * console.log(\"Method:\", info.input.method);\n * }\n * ```\n */\nexport interface DiscoveredResource {\n resourceUrl: string;\n method: string;\n t402Version: number;\n discoveryInfo: DiscoveryInfo;\n}\n\n/**\n * Extracts discovery information from payment payload and requirements.\n * Combines resource URL, HTTP method, version, and discovery info into a single object.\n *\n * @param paymentPayload - The payment payload containing extensions and resource info\n * @param paymentRequirements - The payment requirements to validate against\n * @param validate - Whether to validate the discovery info against the schema (default: true)\n * @returns Discovered resource info with URL, method, version and discovery data, or null if not found\n */\nexport function extractDiscoveryInfo(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements | PaymentRequirementsV1,\n validate: boolean = true,\n): DiscoveredResource | null {\n let discoveryInfo: DiscoveryInfo | null = null;\n let resourceUrl: string;\n\n if (paymentPayload.t402Version === 2) {\n resourceUrl = paymentPayload.resource?.url ?? \"\";\n\n if (paymentPayload.extensions) {\n const bazaarExtension = paymentPayload.extensions[BAZAAR];\n\n if (bazaarExtension && typeof bazaarExtension === \"object\") {\n try {\n const extension = bazaarExtension as DiscoveryExtension;\n\n if (validate) {\n const result = validateDiscoveryExtension(extension);\n if (!result.valid) {\n console.warn(\n `V2 discovery extension validation failed: ${result.errors?.join(\", \")}`,\n );\n } else {\n discoveryInfo = extension.info;\n }\n } else {\n discoveryInfo = extension.info;\n }\n } catch (error) {\n console.warn(`V2 discovery extension extraction failed: ${error}`);\n }\n }\n }\n } else if (paymentPayload.t402Version === 1) {\n const requirementsV1 = paymentRequirements as PaymentRequirementsV1;\n resourceUrl = requirementsV1.resource;\n discoveryInfo = extractDiscoveryInfoV1(requirementsV1);\n } else {\n return null;\n }\n\n if (!discoveryInfo) {\n return null;\n }\n\n return {\n resourceUrl,\n method: discoveryInfo.input.method,\n t402Version: paymentPayload.t402Version,\n discoveryInfo,\n };\n}\n\n/**\n * Extracts discovery info from a v2 extension directly\n *\n * This is a lower-level function for when you already have the extension object.\n * For general use, prefer the main extractDiscoveryInfo function.\n *\n * @param extension - The discovery extension to extract info from\n * @param validate - Whether to validate before extracting (default: true)\n * @returns The discovery info if valid\n * @throws Error if validation fails and validate is true\n */\nexport function extractDiscoveryInfoFromExtension(\n extension: DiscoveryExtension,\n validate: boolean = true,\n): DiscoveryInfo {\n if (validate) {\n const result = validateDiscoveryExtension(extension);\n if (!result.valid) {\n throw new Error(\n `Invalid discovery extension: ${result.errors?.join(\", \") || \"Unknown error\"}`,\n );\n }\n }\n\n return extension.info;\n}\n\n/**\n * Validates and extracts discovery info in one step\n *\n * This is a convenience function that combines validation and extraction,\n * returning both the validation result and the info if valid.\n *\n * @param extension - The discovery extension to validate and extract\n * @returns Object containing validation result and info (if valid)\n *\n * @example\n * ```typescript\n * const extension = declareDiscoveryExtension(...);\n * const { valid, info, errors } = validateAndExtract(extension);\n *\n * if (valid && info) {\n * // Store info in Bazaar catalog\n * } else {\n * console.error(\"Validation errors:\", errors);\n * }\n * ```\n */\nexport function validateAndExtract(extension: DiscoveryExtension): {\n valid: boolean;\n info?: DiscoveryInfo;\n errors?: string[];\n} {\n const result = validateDiscoveryExtension(extension);\n\n if (result.valid) {\n return {\n valid: true,\n info: extension.info,\n };\n }\n\n return {\n valid: false,\n errors: result.errors,\n };\n}\n","/**\n * V1 Facilitator functions for extracting Bazaar discovery information\n *\n * In v1, discovery information is stored in the `outputSchema` field\n * of PaymentRequirements, which has a different structure than v2.\n *\n * This module transforms v1 data into v2 DiscoveryInfo format.\n */\n\nimport type { PaymentRequirementsV1 } from \"@t402/core/types\";\nimport type { BodyMethods, QueryParamMethods } from \"@t402/core/http\";\nimport type { DiscoveryInfo, QueryDiscoveryInfo, BodyDiscoveryInfo } from \"../types\";\n\n/**\n * Type guard to check if an object has the v1 outputSchema structure\n *\n * @param obj - The object to check\n * @returns True if object has v1 outputSchema structure\n */\nfunction hasV1OutputSchema(\n obj: unknown,\n): obj is { input: Record<string, unknown>; output?: Record<string, unknown> } {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"input\" in obj &&\n obj.input !== null &&\n typeof obj.input === \"object\" &&\n \"type\" in obj.input &&\n obj.input.type === \"http\" &&\n \"method\" in obj.input\n );\n}\n\n/**\n * Checks if a method is a query parameter method\n *\n * @param method - HTTP method string to check\n * @returns True if method is GET, HEAD, or DELETE\n */\nfunction isQueryMethod(method: string): method is QueryParamMethods {\n const upperMethod = method.toUpperCase();\n return upperMethod === \"GET\" || upperMethod === \"HEAD\" || upperMethod === \"DELETE\";\n}\n\n/**\n * Checks if a method is a body method\n *\n * @param method - HTTP method string to check\n * @returns True if method is POST, PUT, or PATCH\n */\nfunction isBodyMethod(method: string): method is BodyMethods {\n const upperMethod = method.toUpperCase();\n return upperMethod === \"POST\" || upperMethod === \"PUT\" || upperMethod === \"PATCH\";\n}\n\n/**\n * Extracts query parameters from v1 input, making smart assumptions\n * about common field names used in v1\n *\n * @param v1Input - V1 input object from payment requirements\n * @returns Extracted query parameters or undefined\n */\nfunction extractQueryParams(v1Input: Record<string, unknown>): Record<string, unknown> | undefined {\n // Check various common field names used in v1 (both camelCase and snake_case)\n if (v1Input.queryParams && typeof v1Input.queryParams === \"object\") {\n return v1Input.queryParams as Record<string, unknown>;\n }\n if (v1Input.query_params && typeof v1Input.query_params === \"object\") {\n return v1Input.query_params as Record<string, unknown>;\n }\n if (v1Input.query && typeof v1Input.query === \"object\") {\n return v1Input.query as Record<string, unknown>;\n }\n if (v1Input.params && typeof v1Input.params === \"object\") {\n return v1Input.params as Record<string, unknown>;\n }\n return undefined;\n}\n\n/**\n * Extracts body information from v1 input, making smart assumptions\n *\n * @param v1Input - V1 input object from payment requirements\n * @returns Object containing body content and bodyType\n */\nfunction extractBodyInfo(v1Input: Record<string, unknown>): {\n body: Record<string, unknown>;\n bodyType: \"json\" | \"form-data\" | \"text\";\n} {\n // Determine body type (check both camelCase and snake_case)\n let bodyType: \"json\" | \"form-data\" | \"text\" = \"json\";\n const bodyTypeField = v1Input.bodyType || v1Input.body_type;\n\n if (bodyTypeField && typeof bodyTypeField === \"string\") {\n const type = bodyTypeField.toLowerCase();\n if (type.includes(\"form\") || type.includes(\"multipart\")) {\n bodyType = \"form-data\";\n } else if (type.includes(\"text\") || type.includes(\"plain\")) {\n bodyType = \"text\";\n } else {\n bodyType = \"json\";\n }\n }\n\n // Extract body content from various possible fields\n // Priority order based on observed patterns in real data\n let body: Record<string, unknown> = {};\n\n if (v1Input.bodyFields && typeof v1Input.bodyFields === \"object\") {\n body = v1Input.bodyFields as Record<string, unknown>;\n } else if (\n v1Input.body_fields &&\n v1Input.body_fields !== null &&\n typeof v1Input.body_fields === \"object\"\n ) {\n body = v1Input.body_fields as Record<string, unknown>;\n } else if (v1Input.bodyParams && typeof v1Input.bodyParams === \"object\") {\n body = v1Input.bodyParams as Record<string, unknown>;\n } else if (v1Input.body && typeof v1Input.body === \"object\") {\n body = v1Input.body as Record<string, unknown>;\n } else if (v1Input.data && typeof v1Input.data === \"object\") {\n body = v1Input.data as Record<string, unknown>;\n } else if (v1Input.properties && typeof v1Input.properties === \"object\") {\n // Some endpoints have properties directly at the input level\n body = v1Input.properties as Record<string, unknown>;\n }\n\n return { body, bodyType };\n}\n\n/**\n * Extracts discovery info from v1 PaymentRequirements and transforms to v2 format\n *\n * In v1, the discovery information is stored in the `outputSchema` field,\n * which contains both input (endpoint shape) and output (response schema) information.\n *\n * This function makes smart assumptions to normalize v1 data into v2 DiscoveryInfo format:\n * - For GET/HEAD/DELETE: Looks for queryParams, query, or params fields\n * - For POST/PUT/PATCH: Looks for bodyFields, body, or data fields and normalizes bodyType\n * - Extracts optional headers if present\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns Discovery info in v2 format if present and valid, or null if not discoverable\n *\n * @example\n * ```typescript\n * const requirements: PaymentRequirementsV1 = {\n * scheme: \"exact\",\n * network: \"eip155:8453\",\n * maxAmountRequired: \"100000\",\n * resource: \"https://api.example.com/data\",\n * description: \"Get data\",\n * mimeType: \"application/json\",\n * outputSchema: {\n * input: {\n * type: \"http\",\n * method: \"GET\",\n * discoverable: true,\n * queryParams: { query: \"string\" }\n * },\n * output: { type: \"object\" }\n * },\n * payTo: \"0x...\",\n * maxTimeoutSeconds: 300,\n * asset: \"0x...\",\n * extra: {}\n * };\n *\n * const info = extractDiscoveryInfoV1(requirements);\n * if (info) {\n * console.log(\"Endpoint method:\", info.input.method);\n * }\n * ```\n */\nexport function extractDiscoveryInfoV1(\n paymentRequirements: PaymentRequirementsV1,\n): DiscoveryInfo | null {\n const { outputSchema } = paymentRequirements;\n\n // Check if outputSchema exists and has the expected structure\n if (!outputSchema || !hasV1OutputSchema(outputSchema)) {\n return null;\n }\n\n const v1Input = outputSchema.input;\n\n // Check if the endpoint is marked as discoverable\n // Default to true if not specified (for backwards compatibility)\n const isDiscoverable = v1Input.discoverable ?? true;\n\n if (!isDiscoverable) {\n return null;\n }\n\n const method = typeof v1Input.method === \"string\" ? v1Input.method.toUpperCase() : \"\";\n\n // Extract headers if present (check both camelCase and snake_case)\n const headersRaw = v1Input.headerFields || v1Input.header_fields || v1Input.headers;\n const headers =\n headersRaw && typeof headersRaw === \"object\"\n ? (headersRaw as Record<string, string>)\n : undefined;\n\n // Extract output example/schema if present\n const output = outputSchema.output\n ? {\n type: \"json\" as const,\n example: outputSchema.output,\n }\n : undefined;\n\n // Transform based on method type\n if (isQueryMethod(method)) {\n // Query parameter method (GET, HEAD, DELETE)\n const queryParams = extractQueryParams(v1Input);\n\n const discoveryInfo: QueryDiscoveryInfo = {\n input: {\n type: \"http\",\n method: method as QueryParamMethods,\n ...(queryParams ? { queryParams } : {}),\n ...(headers ? { headers } : {}),\n },\n ...(output ? { output } : {}),\n };\n\n return discoveryInfo;\n } else if (isBodyMethod(method)) {\n // Body method (POST, PUT, PATCH)\n const { body, bodyType } = extractBodyInfo(v1Input);\n const queryParams = extractQueryParams(v1Input); // Some POST requests also have query params\n\n const discoveryInfo: BodyDiscoveryInfo = {\n input: {\n type: \"http\",\n method: method as BodyMethods,\n bodyType,\n body,\n ...(queryParams ? { queryParams } : {}),\n ...(headers ? { headers } : {}),\n },\n ...(output ? { output } : {}),\n };\n\n return discoveryInfo;\n }\n\n // Unsupported method, return null\n return null;\n}\n\n/**\n * Checks if v1 PaymentRequirements contains discoverable information\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns True if the requirements contain valid discovery info\n *\n * @example\n * ```typescript\n * if (isDiscoverableV1(requirements)) {\n * const info = extractDiscoveryInfoV1(requirements);\n * // Catalog info in Bazaar\n * }\n * ```\n */\nexport function isDiscoverableV1(paymentRequirements: PaymentRequirementsV1): boolean {\n return extractDiscoveryInfoV1(paymentRequirements) !== null;\n}\n\n/**\n * Extracts resource metadata from v1 PaymentRequirements\n *\n * In v1, resource information is embedded directly in the payment requirements\n * rather than in a separate resource object.\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns Resource metadata\n *\n * @example\n * ```typescript\n * const metadata = extractResourceMetadataV1(requirements);\n * console.log(\"Resource URL:\", metadata.url);\n * console.log(\"Description:\", metadata.description);\n * ```\n */\nexport function extractResourceMetadataV1(paymentRequirements: PaymentRequirementsV1): {\n url: string;\n description: string;\n mimeType: string;\n} {\n return {\n url: paymentRequirements.resource,\n description: paymentRequirements.description,\n mimeType: paymentRequirements.mimeType,\n };\n}\n","/**\n * Client extensions for querying Bazaar discovery resources\n */\n\nimport { HTTPFacilitatorClient } from \"@t402/core/http\";\nimport { WithExtensions } from \"../types\";\n\n/**\n * Parameters for listing discovery resources.\n * All parameters are optional and used for filtering/pagination.\n */\nexport interface ListDiscoveryResourcesParams {\n /**\n * Filter by protocol type (e.g., \"http\", \"mcp\").\n * Currently, the only supported protocol type is \"http\".\n */\n type?: string;\n\n /**\n * The number of discovered t402 resources to return per page.\n */\n limit?: number;\n\n /**\n * The offset of the first discovered t402 resource to return.\n */\n offset?: number;\n}\n\n/**\n * A discovered t402 resource from the bazaar.\n */\nexport interface DiscoveryResource {\n /** The URL of the discovered resource */\n url: string;\n /** The protocol type of the resource */\n type: string;\n /** Additional metadata about the resource */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Response from listing discovery resources.\n */\nexport interface DiscoveryResourcesResponse {\n /** The list of discovered resources */\n resources: DiscoveryResource[];\n /** Total count of resources matching the query */\n total?: number;\n /** The limit used for this query */\n limit?: number;\n /** The offset used for this query */\n offset?: number;\n}\n\n/**\n * Bazaar client extension interface providing discovery query functionality.\n */\nexport interface BazaarClientExtension {\n discovery: {\n /**\n * List t402 discovery resources from the bazaar.\n *\n * @param params - Optional filtering and pagination parameters\n * @returns A promise resolving to the discovery resources response\n */\n listResources(params?: ListDiscoveryResourcesParams): Promise<DiscoveryResourcesResponse>;\n };\n}\n\n/**\n * Extends a facilitator client with Bazaar discovery query functionality.\n * Preserves and merges with any existing extensions from prior chaining.\n *\n * @param client - The facilitator client to extend\n * @returns The client extended with bazaar discovery capabilities\n *\n * @example\n * ```ts\n * // Basic usage\n * const client = withBazaar(new HTTPFacilitatorClient());\n * const resources = await client.extensions.discovery.listResources({ type: \"http\" });\n *\n * // Chaining with other extensions\n * const client = withBazaar(withOtherExtension(new HTTPFacilitatorClient()));\n * await client.extensions.other.someMethod();\n * await client.extensions.discovery.listResources();\n * ```\n */\nexport function withBazaar<T extends HTTPFacilitatorClient>(\n client: T,\n): WithExtensions<T, BazaarClientExtension> {\n // Preserve any existing extensions from prior chaining\n const existingExtensions =\n (client as T & { extensions?: Record<string, unknown> }).extensions ?? {};\n\n const extended = client as WithExtensions<T, BazaarClientExtension>;\n\n extended.extensions = {\n ...existingExtensions,\n discovery: {\n async listResources(\n params?: ListDiscoveryResourcesParams,\n ): Promise<DiscoveryResourcesResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n const authHeaders = await client.createAuthHeaders(\"discovery\");\n headers = { ...headers, ...authHeaders.headers };\n\n const queryParams = new URLSearchParams();\n if (params?.type !== undefined) {\n queryParams.set(\"type\", params.type);\n }\n if (params?.limit !== undefined) {\n queryParams.set(\"limit\", params.limit.toString());\n }\n if (params?.offset !== undefined) {\n queryParams.set(\"offset\", params.offset.toString());\n }\n\n const queryString = queryParams.toString();\n const endpoint = `${client.url}/discovery/resources${queryString ? `?${queryString}` : \"\"}`;\n\n const response = await fetch(endpoint, {\n method: \"GET\",\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n throw new Error(\n `Facilitator listDiscoveryResources failed (${response.status}): ${errorText}`,\n );\n }\n\n return (await response.json()) as DiscoveryResourcesResponse;\n },\n },\n } as WithExtensions<T, BazaarClientExtension>[\"extensions\"];\n\n return extended;\n}\n","/**\n * Sign-In-With-X (SIWx) Server-Side Implementation\n *\n * Provides functions for servers to declare SIWx requirements,\n * parse client headers, and verify signatures.\n */\n\nimport { randomBytes } from \"crypto\";\nimport { keccak_256 } from \"@noble/hashes/sha3\";\nimport { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { ed25519 } from \"@noble/curves/ed25519\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils\";\nimport {\n SIWxExtension,\n SIWxExtensionInfo,\n SIWxPayload,\n DeclareSIWxOptions,\n ValidateSIWxOptions,\n VerifySIWxOptions,\n SIWxValidationResult,\n SIWxVerificationResult,\n} from \"./types.js\";\n\n/**\n * JSON Schema for SIWx payload validation.\n */\nconst SIWX_SCHEMA = {\n type: \"object\",\n required: [\"domain\", \"address\", \"uri\", \"version\", \"chainId\", \"nonce\", \"issuedAt\", \"signature\"],\n properties: {\n domain: { type: \"string\" },\n address: { type: \"string\" },\n statement: { type: \"string\" },\n uri: { type: \"string\" },\n version: { type: \"string\" },\n chainId: { type: \"string\" },\n nonce: { type: \"string\" },\n issuedAt: { type: \"string\", format: \"date-time\" },\n expirationTime: { type: \"string\", format: \"date-time\" },\n notBefore: { type: \"string\", format: \"date-time\" },\n requestId: { type: \"string\" },\n resources: { type: \"array\", items: { type: \"string\" } },\n signature: { type: \"string\" },\n },\n};\n\n/**\n * EIP-1271 magic value for valid signatures.\n */\nconst EIP1271_MAGIC_VALUE = \"0x1626ba7e\";\n\n/**\n * Extracts domain from a resource URI.\n *\n * @param resourceUri - Full resource URI (e.g., \"https://api.example.com/resource\")\n * @returns Domain without protocol (e.g., \"api.example.com\")\n */\nfunction extractDomain(resourceUri: string): string {\n try {\n const url = new URL(resourceUri);\n return url.host;\n } catch {\n // Fallback for non-URL formats\n return resourceUri.replace(/^https?:\\/\\//, \"\").split(\"/\")[0];\n }\n}\n\n/**\n * Generates a cryptographically secure nonce.\n *\n * @returns 32-byte hex-encoded nonce\n */\nfunction generateNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * Declares a SIWx extension for server responses.\n *\n * @param options - Extension declaration options\n * @returns SIWx extension object ready for response\n *\n * @example\n * ```typescript\n * const extension = declareSIWxExtension({\n * resourceUri: \"https://api.example.com/premium\",\n * network: \"eip155:8453\",\n * statement: \"Sign in to access premium content\",\n * });\n * ```\n */\nexport function declareSIWxExtension(options: DeclareSIWxOptions): SIWxExtension {\n const domain = extractDomain(options.resourceUri);\n const now = new Date();\n const expirationTime =\n options.expirationTime || new Date(now.getTime() + 5 * 60 * 1000).toISOString();\n\n const info: SIWxExtensionInfo = {\n domain,\n uri: options.resourceUri,\n statement: options.statement,\n version: options.version || \"1\",\n chainId: options.network,\n nonce: generateNonce(),\n issuedAt: now.toISOString(),\n expirationTime,\n resources: [options.resourceUri],\n signatureScheme: options.signatureScheme,\n };\n\n return {\n info,\n schema: SIWX_SCHEMA,\n };\n}\n\n/**\n * Parses a SIWx header from client request.\n *\n * The header format is base64-encoded JSON.\n *\n * @param header - Base64-encoded SIWx header value\n * @returns Parsed SIWx payload\n * @throws Error if header is invalid\n *\n * @example\n * ```typescript\n * const payload = parseSIWxHeader(request.headers['x-t402-siwx']);\n * ```\n */\nexport function parseSIWxHeader(header: string): SIWxPayload {\n if (!header) {\n throw new Error(\"Missing SIWx header\");\n }\n\n try {\n const decoded = Buffer.from(header, \"base64\").toString(\"utf-8\");\n const payload = JSON.parse(decoded) as SIWxPayload;\n\n // Validate required fields\n const required = [\n \"domain\",\n \"address\",\n \"uri\",\n \"version\",\n \"chainId\",\n \"nonce\",\n \"issuedAt\",\n \"signature\",\n ];\n for (const field of required) {\n if (!(field in payload)) {\n throw new Error(`Missing required field: ${field}`);\n }\n }\n\n return payload;\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new Error(\"Invalid SIWx header: malformed JSON\");\n }\n throw error;\n }\n}\n\n/**\n * Validates a SIWx message against expected values.\n *\n * @param message - The SIWx payload to validate\n * @param expectedResourceUri - Expected resource URI (domain validated from this)\n * @param options - Validation options\n * @returns Validation result\n *\n * @example\n * ```typescript\n * const result = validateSIWxMessage(payload, \"https://api.example.com/premium\", {\n * maxAge: 5 * 60 * 1000, // 5 minutes\n * checkNonce: (nonce) => usedNonces.has(nonce) === false,\n * });\n * ```\n */\nexport function validateSIWxMessage(\n message: SIWxPayload,\n expectedResourceUri: string,\n options: ValidateSIWxOptions = {},\n): SIWxValidationResult {\n const { maxAge = 5 * 60 * 1000, checkNonce } = options;\n\n // Validate domain matches\n const expectedDomain = extractDomain(expectedResourceUri);\n if (message.domain !== expectedDomain) {\n return {\n valid: false,\n error: `Domain mismatch: expected ${expectedDomain}, got ${message.domain}`,\n };\n }\n\n // Validate URI matches\n if (message.uri !== expectedResourceUri) {\n return {\n valid: false,\n error: `URI mismatch: expected ${expectedResourceUri}, got ${message.uri}`,\n };\n }\n\n // Validate version\n if (message.version !== \"1\") {\n return { valid: false, error: `Unsupported version: ${message.version}` };\n }\n\n // Validate issuedAt is not too old\n const issuedAt = new Date(message.issuedAt);\n const now = new Date();\n if (now.getTime() - issuedAt.getTime() > maxAge) {\n return { valid: false, error: \"Message has expired (issuedAt too old)\" };\n }\n\n // Validate expirationTime if present\n if (message.expirationTime) {\n const expiration = new Date(message.expirationTime);\n if (expiration < now) {\n return { valid: false, error: \"Message has expired\" };\n }\n }\n\n // Validate notBefore if present\n if (message.notBefore) {\n const notBefore = new Date(message.notBefore);\n if (notBefore > now) {\n return { valid: false, error: \"Message not yet valid (notBefore in future)\" };\n }\n }\n\n // Custom nonce validation\n if (checkNonce && !checkNonce(message.nonce)) {\n return { valid: false, error: \"Invalid nonce (replay attack detected)\" };\n }\n\n return { valid: true };\n}\n\n/**\n * Detects the signature scheme from chain ID.\n *\n * @param chainId - CAIP-2 chain ID (e.g., \"eip155:1\", \"solana:mainnet\", \"stellar:pubnet\")\n * @returns The signature scheme to use for verification\n */\nfunction detectSignatureScheme(chainId: string): \"evm\" | \"ed25519\" {\n const namespace = chainId.split(\":\")[0];\n\n switch (namespace) {\n case \"solana\":\n case \"stellar\":\n return \"ed25519\";\n case \"eip155\":\n default:\n return \"evm\";\n }\n}\n\n/**\n * Verifies an Ed25519 signature (used by Solana and Stellar).\n *\n * @param message - The message that was signed\n * @param signature - Hex-encoded Ed25519 signature (64 bytes)\n * @param publicKey - The public key to verify against (hex or base58)\n * @returns True if signature is valid\n */\nfunction verifyEd25519Signature(message: string, signature: string, publicKey: string): boolean {\n try {\n // Remove 0x prefix if present\n const sigHex = signature.startsWith(\"0x\") ? signature.slice(2) : signature;\n const sigBytes = hexToBytes(sigHex);\n\n if (sigBytes.length !== 64) {\n throw new Error(\n `Invalid Ed25519 signature length: expected 64 bytes, got ${sigBytes.length}`,\n );\n }\n\n // Get public key bytes\n let pubKeyBytes: Uint8Array;\n const pubKeyHex = publicKey.startsWith(\"0x\") ? publicKey.slice(2) : publicKey;\n\n // Check if it's a hex string (64 chars = 32 bytes)\n if (/^[0-9a-fA-F]{64}$/.test(pubKeyHex)) {\n pubKeyBytes = hexToBytes(pubKeyHex);\n } else {\n // Try to decode as base58 (Solana format)\n pubKeyBytes = decodeBase58(publicKey);\n }\n\n if (pubKeyBytes.length !== 32) {\n throw new Error(\n `Invalid Ed25519 public key length: expected 32 bytes, got ${pubKeyBytes.length}`,\n );\n }\n\n // Hash the message (Ed25519 signs the raw message or its hash depending on implementation)\n const messageBytes = new TextEncoder().encode(message);\n\n // Verify the signature\n return ed25519.verify(sigBytes, messageBytes, pubKeyBytes);\n } catch {\n return false;\n }\n}\n\n/**\n * Decodes a base58 string to bytes (for Solana addresses).\n *\n * @param str - Base58 encoded string\n * @returns Decoded bytes\n */\nfunction decodeBase58(str: string): Uint8Array {\n const ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n const ALPHABET_MAP = new Map<string, number>();\n for (let i = 0; i < ALPHABET.length; i++) {\n ALPHABET_MAP.set(ALPHABET[i], i);\n }\n\n if (str.length === 0) return new Uint8Array(0);\n\n const bytes: number[] = [0];\n for (const char of str) {\n const value = ALPHABET_MAP.get(char);\n if (value === undefined) {\n throw new Error(`Invalid base58 character: ${char}`);\n }\n\n let carry = value;\n for (let j = 0; j < bytes.length; j++) {\n carry += bytes[j] * 58;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // Add leading zeros\n for (const char of str) {\n if (char !== \"1\") break;\n bytes.push(0);\n }\n\n return new Uint8Array(bytes.reverse());\n}\n\n/**\n * Verifies a SIWx signature.\n *\n * Supports EIP-191 personal signatures for EVM chains, Ed25519 for Solana/Stellar,\n * and can optionally verify smart wallet signatures via EIP-1271/6492.\n *\n * @param message - The SIWx payload to verify\n * @param signature - The signature to verify (hex-encoded)\n * @param options - Verification options\n * @returns Verification result with recovered address\n *\n * @example\n * ```typescript\n * const result = await verifySIWxSignature(payload, payload.signature, {\n * checkSmartWallet: true,\n * provider: web3Provider,\n * });\n * ```\n */\nexport async function verifySIWxSignature(\n message: SIWxPayload,\n signature: string,\n options: VerifySIWxOptions = {},\n): Promise<SIWxVerificationResult> {\n const { checkSmartWallet = false } = options;\n\n try {\n // Reconstruct the CAIP-122 message that was signed\n const messageText = constructMessage(message);\n\n // Detect signature scheme based on chain ID\n const scheme = detectSignatureScheme(message.chainId);\n\n if (scheme === \"ed25519\") {\n // Ed25519 verification for Solana and Stellar\n // For Ed25519, the address IS the public key, so we verify directly\n const isValid = verifyEd25519Signature(messageText, signature, message.address);\n\n if (isValid) {\n return { valid: true, address: message.address };\n }\n\n return {\n valid: false,\n error: \"Ed25519 signature verification failed\",\n };\n }\n\n // EVM verification (secp256k1)\n // Hash the message with Ethereum prefix\n const messageHash = hashMessage(messageText);\n\n // Try to recover the signer address\n const recoveredAddress = recoverAddress(messageHash, signature);\n\n // Check if recovered address matches claimed address\n if (recoveredAddress.toLowerCase() !== message.address.toLowerCase()) {\n // If smart wallet checking is enabled, try EIP-1271 verification\n if (checkSmartWallet && options.provider) {\n const isValidSmartWallet = await verifySmartWalletSignature(\n message.address,\n messageHash,\n signature,\n options.provider,\n );\n\n if (isValidSmartWallet) {\n return { valid: true, address: message.address };\n }\n }\n\n return {\n valid: false,\n address: recoveredAddress,\n error: `Signature mismatch: expected ${message.address}, recovered ${recoveredAddress}`,\n };\n }\n\n return { valid: true, address: recoveredAddress };\n } catch (error) {\n return {\n valid: false,\n error: `Signature verification failed: ${error instanceof Error ? error.message : \"unknown error\"}`,\n };\n }\n}\n\n/**\n * Constructs the CAIP-122 message string from payload.\n *\n * @param payload - SIWx payload\n * @returns CAIP-122 formatted message string\n */\nexport function constructMessage(payload: SIWxPayload): string {\n const lines: string[] = [];\n\n // Header\n lines.push(`${payload.domain} wants you to sign in with your ${payload.chainId} account:`);\n lines.push(payload.address);\n lines.push(\"\");\n\n // Statement (optional)\n if (payload.statement) {\n lines.push(payload.statement);\n lines.push(\"\");\n }\n\n // Required fields\n lines.push(`URI: ${payload.uri}`);\n lines.push(`Version: ${payload.version}`);\n lines.push(`Chain ID: ${payload.chainId}`);\n lines.push(`Nonce: ${payload.nonce}`);\n lines.push(`Issued At: ${payload.issuedAt}`);\n\n // Optional fields\n if (payload.expirationTime) {\n lines.push(`Expiration Time: ${payload.expirationTime}`);\n }\n if (payload.notBefore) {\n lines.push(`Not Before: ${payload.notBefore}`);\n }\n if (payload.requestId) {\n lines.push(`Request ID: ${payload.requestId}`);\n }\n\n // Resources\n if (payload.resources && payload.resources.length > 0) {\n lines.push(\"Resources:\");\n for (const resource of payload.resources) {\n lines.push(`- ${resource}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Hashes a message with the Ethereum signed message prefix (EIP-191).\n *\n * @param message - Message to hash\n * @returns Hex-encoded keccak256 hash with 0x prefix\n */\nexport function hashMessage(message: string): string {\n const messageBytes = new TextEncoder().encode(message);\n const prefix = `\\x19Ethereum Signed Message:\\n${messageBytes.length}`;\n const prefixBytes = new TextEncoder().encode(prefix);\n\n // Concatenate prefix and message\n const combined = new Uint8Array(prefixBytes.length + messageBytes.length);\n combined.set(prefixBytes, 0);\n combined.set(messageBytes, prefixBytes.length);\n\n // Hash with keccak256\n const hash = keccak_256(combined);\n return \"0x\" + bytesToHex(hash);\n}\n\n/**\n * Recovers the signer address from an EIP-191 signature.\n *\n * @param messageHash - Keccak256 hash of the prefixed message (with 0x prefix)\n * @param signature - Hex-encoded signature (65 bytes: r + s + v)\n * @returns Checksummed Ethereum address\n */\nfunction recoverAddress(messageHash: string, signature: string): string {\n // Remove 0x prefix if present\n const sigHex = signature.startsWith(\"0x\") ? signature.slice(2) : signature;\n const hashHex = messageHash.startsWith(\"0x\") ? messageHash.slice(2) : messageHash;\n\n if (sigHex.length !== 130) {\n throw new Error(`Invalid signature length: expected 130 hex chars, got ${sigHex.length}`);\n }\n\n // Parse signature components\n const r = BigInt(\"0x\" + sigHex.slice(0, 64));\n const s = BigInt(\"0x\" + sigHex.slice(64, 128));\n let v = parseInt(sigHex.slice(128, 130), 16);\n\n // Normalize v to 0 or 1 (EIP-155 compatibility)\n if (v >= 27) {\n v -= 27;\n }\n\n if (v !== 0 && v !== 1) {\n throw new Error(`Invalid recovery id: ${v}`);\n }\n\n // Create signature object\n const sig = new secp256k1.Signature(r, s).addRecoveryBit(v);\n\n // Recover public key\n const hashBytes = hexToBytes(hashHex);\n const publicKey = sig.recoverPublicKey(hashBytes);\n\n // Get uncompressed public key (65 bytes) and remove the 04 prefix\n const pubKeyBytes = publicKey.toRawBytes(false).slice(1);\n\n // Hash public key to get address\n const addressHash = keccak_256(pubKeyBytes);\n\n // Take last 20 bytes\n const addressBytes = addressHash.slice(-20);\n const address = \"0x\" + bytesToHex(addressBytes);\n\n // Return checksummed address\n return toChecksumAddress(address);\n}\n\n/**\n * Converts an Ethereum address to checksummed format (EIP-55).\n *\n * @param address - Ethereum address (with or without 0x prefix)\n * @returns Checksummed address with 0x prefix\n */\nfunction toChecksumAddress(address: string): string {\n const addr = address.toLowerCase().replace(\"0x\", \"\");\n const hash = bytesToHex(keccak_256(new TextEncoder().encode(addr)));\n\n let checksummed = \"0x\";\n for (let i = 0; i < 40; i++) {\n if (parseInt(hash[i], 16) >= 8) {\n checksummed += addr[i].toUpperCase();\n } else {\n checksummed += addr[i];\n }\n }\n\n return checksummed;\n}\n\n/**\n * Verifies a smart wallet signature using EIP-1271.\n *\n * @param walletAddress - Smart wallet contract address\n * @param messageHash - Hash of the message that was signed\n * @param signature - The signature to verify\n * @param provider - Ethereum provider with call capability\n * @returns True if signature is valid according to the smart wallet\n */\nasync function verifySmartWalletSignature(\n walletAddress: string,\n messageHash: string,\n signature: string,\n provider: unknown,\n): Promise<boolean> {\n // Type guard for provider\n interface EthProvider {\n request(args: { method: string; params: unknown[] }): Promise<unknown>;\n }\n\n /**\n * Type guard for Ethereum provider interface\n *\n * @param p - Value to check\n * @returns True if value is an EthProvider\n */\n function isEthProvider(p: unknown): p is EthProvider {\n return typeof p === \"object\" && p !== null && \"request\" in p;\n }\n\n if (!isEthProvider(provider)) {\n return false;\n }\n\n try {\n // EIP-1271 isValidSignature(bytes32 hash, bytes signature) returns bytes4\n const hashHex = messageHash.startsWith(\"0x\") ? messageHash : \"0x\" + messageHash;\n const sigHex = signature.startsWith(\"0x\") ? signature : \"0x\" + signature;\n\n // Encode function call\n // isValidSignature(bytes32,bytes) selector: 0x1626ba7e\n const data =\n \"0x1626ba7e\" +\n hashHex.slice(2).padStart(64, \"0\") + // bytes32 hash\n \"0000000000000000000000000000000000000000000000000000000000000040\" + // offset to bytes\n (sigHex.length / 2 - 1).toString(16).padStart(64, \"0\") + // bytes length\n sigHex.slice(2).padEnd(Math.ceil((sigHex.length - 2) / 64) * 64, \"0\"); // bytes data\n\n const result = (await provider.request({\n method: \"eth_call\",\n params: [{ to: walletAddress, data }, \"latest\"],\n })) as string;\n\n // Check if result matches magic value\n return result.toLowerCase().startsWith(EIP1271_MAGIC_VALUE);\n } catch {\n return false;\n }\n}\n\n/**\n * Verifies a signature using EIP-6492 (universal signature verification).\n *\n * This supports both deployed and undeployed smart wallets.\n *\n * @param walletAddress - Wallet address (may be counterfactual)\n * @param messageHash - Hash of the message that was signed\n * @param signature - The signature (may include deployment data)\n * @param provider - Ethereum provider\n * @returns True if signature is valid\n */\nexport async function verifyEIP6492Signature(\n walletAddress: string,\n messageHash: string,\n signature: string,\n provider: unknown,\n): Promise<boolean> {\n // EIP-6492 signatures end with the magic suffix\n const EIP6492_SUFFIX = \"6492649264926492649264926492649264926492649264926492649264926492\";\n const sigHex = signature.startsWith(\"0x\") ? signature.slice(2) : signature;\n\n if (sigHex.endsWith(EIP6492_SUFFIX)) {\n // This is an EIP-6492 signature with deployment data\n // For full implementation, we would need to:\n // 1. Deploy the wallet contract to a local fork\n // 2. Then call isValidSignature\n // This requires more complex provider interaction\n console.warn(\"EIP-6492 deployment signatures not yet fully implemented\");\n return false;\n }\n\n // Fall back to standard EIP-1271 verification\n return verifySmartWalletSignature(walletAddress, messageHash, signature, provider);\n}\n","/**\n * Sign-In-With-X (SIWx) Client-Side Implementation\n *\n * Provides functions for clients to create and sign SIWx messages.\n */\n\nimport {\n SIWxPayload,\n SIWxExtension,\n SIWxExtensionInfo,\n SIWxSigner,\n SignatureScheme,\n} from \"./types.js\";\nimport { constructMessage } from \"./server.js\";\n\n/**\n * Encodes a SIWx payload for transmission in HTTP header.\n *\n * @param payload - The SIWx payload to encode\n * @returns Base64-encoded JSON string\n *\n * @example\n * ```typescript\n * const header = encodeSIWxHeader(payload);\n * fetch(url, {\n * headers: { 'X-T402-SIWx': header }\n * });\n * ```\n */\nexport function encodeSIWxHeader(payload: SIWxPayload): string {\n const json = JSON.stringify(payload);\n // Use Buffer in Node.js or btoa in browser\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(json, \"utf-8\").toString(\"base64\");\n }\n return btoa(json);\n}\n\n/**\n * Creates a CAIP-122 formatted message string from server info.\n *\n * @param serverInfo - Extension info from server\n * @param address - Wallet address signing the message\n * @returns CAIP-122 formatted message string ready for signing\n *\n * @example\n * ```typescript\n * const message = createSIWxMessage(extension.info, wallet.address);\n * const signature = await wallet.signMessage(message);\n * ```\n */\nexport function createSIWxMessage(serverInfo: SIWxExtensionInfo, address: string): string {\n // Create a temporary payload for message construction\n const payload: SIWxPayload = {\n domain: serverInfo.domain,\n address,\n statement: serverInfo.statement,\n uri: serverInfo.uri,\n version: serverInfo.version,\n chainId: serverInfo.chainId,\n nonce: serverInfo.nonce,\n issuedAt: serverInfo.issuedAt,\n expirationTime: serverInfo.expirationTime,\n notBefore: serverInfo.notBefore,\n requestId: serverInfo.requestId,\n resources: serverInfo.resources,\n signature: \"\", // Will be added after signing\n };\n\n return constructMessage(payload);\n}\n\n/**\n * Creates EIP-712 typed data for SIWx signing.\n *\n * @param serverInfo - Extension info from server\n * @param address - Wallet address signing the message\n * @returns EIP-712 typed data object\n */\nexport function createSIWxTypedData(\n serverInfo: SIWxExtensionInfo,\n address: string,\n): {\n domain: {\n name: string;\n version: string;\n chainId: number;\n };\n types: {\n SIWx: Array<{ name: string; type: string }>;\n };\n primaryType: \"SIWx\";\n message: Record<string, unknown>;\n} {\n // Extract chain ID number from CAIP-2 format (e.g., \"eip155:8453\" -> 8453)\n const chainIdParts = serverInfo.chainId.split(\":\");\n const chainIdNum =\n chainIdParts.length > 1 ? parseInt(chainIdParts[1], 10) : parseInt(chainIdParts[0], 10);\n\n return {\n domain: {\n name: serverInfo.domain,\n version: serverInfo.version,\n chainId: chainIdNum,\n },\n types: {\n SIWx: [\n { name: \"domain\", type: \"string\" },\n { name: \"address\", type: \"address\" },\n { name: \"statement\", type: \"string\" },\n { name: \"uri\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"string\" },\n { name: \"nonce\", type: \"string\" },\n { name: \"issuedAt\", type: \"string\" },\n { name: \"expirationTime\", type: \"string\" },\n { name: \"resources\", type: \"string[]\" },\n ],\n },\n primaryType: \"SIWx\",\n message: {\n domain: serverInfo.domain,\n address,\n statement: serverInfo.statement || \"\",\n uri: serverInfo.uri,\n version: serverInfo.version,\n chainId: serverInfo.chainId,\n nonce: serverInfo.nonce,\n issuedAt: serverInfo.issuedAt,\n expirationTime: serverInfo.expirationTime || \"\",\n resources: serverInfo.resources || [],\n },\n };\n}\n\n/**\n * Signs a SIWx message using the provided signer.\n *\n * @param message - CAIP-122 formatted message to sign\n * @param signer - Wallet/signer interface with signMessage\n * @param options - Signing options\n * @param options.signatureScheme - Signature scheme to use\n * @param options.serverInfo - Server info for verification\n * @returns Hex-encoded signature\n *\n * @example\n * ```typescript\n * const signature = await signSIWxMessage(message, wallet, {\n * signatureScheme: 'eip191'\n * });\n * ```\n */\nexport async function signSIWxMessage(\n message: string,\n signer: SIWxSigner,\n options?: { signatureScheme?: SignatureScheme; serverInfo?: SIWxExtensionInfo },\n): Promise<string> {\n const scheme = options?.signatureScheme || \"eip191\";\n\n switch (scheme) {\n case \"eip191\":\n if (!signer.signMessage) {\n throw new Error(\"Signer does not support personal_sign (EIP-191)\");\n }\n return signer.signMessage(message);\n\n case \"eip712\":\n if (!signer.signTypedData) {\n throw new Error(\"Signer does not support signTypedData (EIP-712)\");\n }\n if (!options?.serverInfo) {\n throw new Error(\"EIP-712 signing requires serverInfo in options\");\n }\n const typedData = createSIWxTypedData(options.serverInfo, signer.address);\n return signer.signTypedData(typedData);\n\n case \"eip1271\":\n case \"eip6492\":\n // Smart wallet signatures go through the same signMessage path\n // but verification happens on-chain\n if (!signer.signMessage) {\n throw new Error(\"Signer does not support signing\");\n }\n return signer.signMessage(message);\n\n case \"siws\":\n // Sign-In With Solana uses Ed25519 signatures\n if (!signer.signMessage) {\n throw new Error(\"Signer does not support signing\");\n }\n // Solana wallets typically implement signMessage that handles the encoding\n return signer.signMessage(message);\n\n case \"sep10\":\n // Stellar SEP-10 uses Ed25519 signatures (same as Solana)\n if (!signer.signMessage) {\n throw new Error(\"Signer does not support signing\");\n }\n // Stellar wallets implement signMessage for Ed25519 signing\n // The wallet handles proper message encoding and returns hex signature\n return signer.signMessage(message);\n\n default:\n throw new Error(`Unknown signature scheme: ${scheme}`);\n }\n}\n\n/**\n * Creates a complete SIWx payload from server extension and signer.\n *\n * This is the main entry point for clients - it handles message construction,\n * signing, and payload assembly.\n *\n * @param serverExtension - Extension from server's 402 response\n * @param signer - Wallet/signer interface\n * @returns Complete signed SIWx payload ready for header encoding\n *\n * @example\n * ```typescript\n * // Get extension from server 402 response\n * const extension = paymentRequirements.extensions?.siwx;\n *\n * // Create signed payload\n * const payload = await createSIWxPayload(extension, wallet);\n *\n * // Encode and send with retry\n * const header = encodeSIWxHeader(payload);\n * fetch(url, {\n * headers: { 'X-T402-SIWx': header }\n * });\n * ```\n */\nexport async function createSIWxPayload(\n serverExtension: SIWxExtension,\n signer: SIWxSigner,\n): Promise<SIWxPayload> {\n const { info } = serverExtension;\n\n // Create the message to sign\n const message = createSIWxMessage(info, signer.address);\n\n // Sign the message\n const signature = await signSIWxMessage(message, signer, {\n signatureScheme: info.signatureScheme,\n serverInfo: info,\n });\n\n // Assemble the complete payload\n return {\n domain: info.domain,\n address: signer.address,\n statement: info.statement,\n uri: info.uri,\n version: info.version,\n chainId: info.chainId,\n nonce: info.nonce,\n issuedAt: info.issuedAt,\n expirationTime: info.expirationTime,\n notBefore: info.notBefore,\n requestId: info.requestId,\n resources: info.resources,\n signature,\n };\n}\n\n/**\n * Extension key for SIWx in payment requirements.\n */\nexport const SIWX_EXTENSION_KEY = \"siwx\";\n\n/**\n * HTTP header name for SIWx payload.\n */\nexport const SIWX_HEADER_NAME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AC,OAAO,aAAa;AACvB,cAAM,IAAI,MAAM,iCAAiC;AAAA,MACnD;AACA,aAAO,OAAO,YAAY,OAAO;AAAA,IAEnC,KAAK;AAEH,UAAI,CAAC,OAAO,aAAa;AACvB,cAAM,IAAI,MAAM,iCAAiC;AAAA,MACnD;AAEA,aAAO,OAAO,YAAY,OAAO;AAAA,IAEnC,KAAK;AAEH,UAAI,CAAC,OAAO,aAAa;AACvB,cAAM,IAAI,MAAM,iCAAiC;AAAA,MACnD;AAGA,aAAO,OAAO,YAAY,OAAO;AAAA,IAEnC;AACE,YAAM,IAAI,MAAM,6BAA6B,MAAM,EAAE;AAAA,EACzD;AACF;AA2BA,eAAsB,kBACpB,iBACA,QACsB;AACtB,QAAM,EAAE,KAAK,IAAI;AAGjB,QAAM,UAAU,kBAAkB,MAAM,OAAO,OAAO;AAGtD,QAAM,YAAY,MAAM,gBAAgB,SAAS,QAAQ;AAAA,IACvD,iBAAiB,KAAK;AAAA,IACtB,YAAY;AAAA,EACd,CAAC;AAGD,SAAO;AAAA,IACL,QAAQ,KAAK;AAAA,IACb,SAAS,OAAO;AAAA,IAChB,WAAW,KAAK;AAAA,IAChB,KAAK,KAAK;AAAA,IACV,SAAS,KAAK;AAAA,IACd,SAAS,KAAK;AAAA,IACd,OAAO,KAAK;AAAA,IACZ,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,WAAW,KAAK;AAAA,IAChB,WAAW,KAAK;AAAA,IAChB,WAAW,KAAK;AAAA,IAChB;AAAA,EACF;AACF;AAKO,IAAM,qBAAqB;AAK3B,IAAM,mBAAmB;","names":["isBodyMethod","Ajv"]}
@@ -201,8 +201,8 @@ declare function validateSIWxMessage(message: SIWxPayload, expectedResourceUri:
201
201
  /**
202
202
  * Verifies a SIWx signature.
203
203
  *
204
- * Supports EIP-191 personal signatures and can optionally verify
205
- * smart wallet signatures via EIP-1271/6492.
204
+ * Supports EIP-191 personal signatures for EVM chains, Ed25519 for Solana/Stellar,
205
+ * and can optionally verify smart wallet signatures via EIP-1271/6492.
206
206
  *
207
207
  * @param message - The SIWx payload to verify
208
208
  * @param signature - The signature to verify (hex-encoded)