@kya-os/checkpoint-shared 1.4.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/beacon-types/index.d.mts +448 -432
  3. package/dist/beacon-types/index.d.mts.map +1 -0
  4. package/dist/beacon-types/index.d.ts +448 -432
  5. package/dist/beacon-types/index.d.ts.map +1 -0
  6. package/dist/beacon-types/index.js +286 -182
  7. package/dist/beacon-types/index.mjs +284 -180
  8. package/dist/beacon-types/index.mjs.map +1 -0
  9. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts +5 -0
  10. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts.map +1 -0
  11. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts +5 -0
  12. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts.map +1 -0
  13. package/dist/browser-posture-cookie.d.mts +2 -0
  14. package/dist/browser-posture-cookie.d.ts +2 -0
  15. package/dist/browser-posture-cookie.js +1 -0
  16. package/dist/browser-posture-cookie.mjs +2 -0
  17. package/dist/browser-posture-cookie.mjs.map +1 -0
  18. package/dist/browser-posture-report.d.mts +48 -44
  19. package/dist/browser-posture-report.d.mts.map +1 -0
  20. package/dist/browser-posture-report.d.ts +48 -44
  21. package/dist/browser-posture-report.d.ts.map +1 -0
  22. package/dist/browser-posture-report.js +1 -1
  23. package/dist/browser-posture-report.mjs +2 -1
  24. package/dist/browser-posture-report.mjs.map +1 -0
  25. package/dist/browser-posture.d.mts +82 -75
  26. package/dist/browser-posture.d.mts.map +1 -0
  27. package/dist/browser-posture.d.ts +82 -75
  28. package/dist/browser-posture.d.ts.map +1 -0
  29. package/dist/browser-posture.js +167 -18993
  30. package/dist/browser-posture.mjs +166 -18990
  31. package/dist/browser-posture.mjs.map +1 -0
  32. package/dist/browser.d.mts +323 -316
  33. package/dist/browser.d.mts.map +1 -0
  34. package/dist/browser.d.ts +323 -316
  35. package/dist/browser.d.ts.map +1 -0
  36. package/dist/browser.js +1 -1
  37. package/dist/browser.mjs +2 -1
  38. package/dist/browser.mjs.map +1 -0
  39. package/dist/canonical-signer/index.d.mts +38 -33
  40. package/dist/canonical-signer/index.d.mts.map +1 -0
  41. package/dist/canonical-signer/index.d.ts +38 -33
  42. package/dist/canonical-signer/index.d.ts.map +1 -0
  43. package/dist/canonical-signer/index.js +411 -181
  44. package/dist/canonical-signer/index.mjs +383 -175
  45. package/dist/canonical-signer/index.mjs.map +1 -0
  46. package/dist/clearance.d.mts +30 -0
  47. package/dist/clearance.d.mts.map +1 -0
  48. package/dist/clearance.d.ts +30 -0
  49. package/dist/clearance.d.ts.map +1 -0
  50. package/dist/clearance.js +120 -0
  51. package/dist/clearance.mjs +112 -0
  52. package/dist/clearance.mjs.map +1 -0
  53. package/dist/client-ip-1y2iXAYW.js +237 -0
  54. package/dist/client-ip-HOfe6ucV.mjs +215 -0
  55. package/dist/client-ip-HOfe6ucV.mjs.map +1 -0
  56. package/dist/deploy/index.d.mts +339 -339
  57. package/dist/deploy/index.d.mts.map +1 -0
  58. package/dist/deploy/index.d.ts +339 -339
  59. package/dist/deploy/index.d.ts.map +1 -0
  60. package/dist/deploy/index.js +505 -413
  61. package/dist/deploy/index.mjs +504 -410
  62. package/dist/deploy/index.mjs.map +1 -0
  63. package/dist/errors/index.d.mts +101 -101
  64. package/dist/errors/index.d.mts.map +1 -0
  65. package/dist/errors/index.d.ts +101 -101
  66. package/dist/errors/index.d.ts.map +1 -0
  67. package/dist/errors/index.js +341 -314
  68. package/dist/errors/index.mjs +340 -311
  69. package/dist/errors/index.mjs.map +1 -0
  70. package/dist/external-jr_S4iSS.d.mts +4187 -0
  71. package/dist/external-jr_S4iSS.d.mts.map +1 -0
  72. package/dist/external-jr_S4iSS.d.ts +4187 -0
  73. package/dist/external-jr_S4iSS.d.ts.map +1 -0
  74. package/dist/gateway/index.d.mts +138 -132
  75. package/dist/gateway/index.d.mts.map +1 -0
  76. package/dist/gateway/index.d.ts +138 -132
  77. package/dist/gateway/index.d.ts.map +1 -0
  78. package/dist/gateway/index.js +117 -81
  79. package/dist/gateway/index.mjs +116 -78
  80. package/dist/gateway/index.mjs.map +1 -0
  81. package/dist/gateway-client-ip.d.mts +59 -0
  82. package/dist/gateway-client-ip.d.mts.map +1 -0
  83. package/dist/gateway-client-ip.d.ts +59 -0
  84. package/dist/gateway-client-ip.d.ts.map +1 -0
  85. package/dist/gateway-client-ip.js +149 -0
  86. package/dist/gateway-client-ip.mjs +139 -0
  87. package/dist/gateway-client-ip.mjs.map +1 -0
  88. package/dist/index.d.mts +14901 -14246
  89. package/dist/index.d.mts.map +1 -0
  90. package/dist/index.d.ts +14901 -14246
  91. package/dist/index.d.ts.map +1 -0
  92. package/dist/index.js +15180 -31025
  93. package/dist/index.mjs +15065 -30942
  94. package/dist/index.mjs.map +1 -0
  95. package/dist/mcpi/agentshield-api/index.d.mts +45 -44
  96. package/dist/mcpi/agentshield-api/index.d.mts.map +1 -0
  97. package/dist/mcpi/agentshield-api/index.d.ts +45 -44
  98. package/dist/mcpi/agentshield-api/index.d.ts.map +1 -0
  99. package/dist/mcpi/agentshield-api/index.js +0 -2
  100. package/dist/mcpi/agentshield-api/index.mjs +1 -1
  101. package/dist/mcpi/approval-grant/index.d.mts +63 -61
  102. package/dist/mcpi/approval-grant/index.d.mts.map +1 -0
  103. package/dist/mcpi/approval-grant/index.d.ts +63 -61
  104. package/dist/mcpi/approval-grant/index.d.ts.map +1 -0
  105. package/dist/mcpi/approval-grant/index.js +220 -140
  106. package/dist/mcpi/approval-grant/index.mjs +219 -137
  107. package/dist/mcpi/approval-grant/index.mjs.map +1 -0
  108. package/dist/mcpi/dashboard-config/index.d.mts +2323 -2318
  109. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -0
  110. package/dist/mcpi/dashboard-config/index.d.ts +2323 -2318
  111. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -0
  112. package/dist/mcpi/dashboard-config/index.js +605 -458
  113. package/dist/mcpi/dashboard-config/index.mjs +604 -455
  114. package/dist/mcpi/dashboard-config/index.mjs.map +1 -0
  115. package/dist/mcpi/multibase-ed25519.d.mts +10 -8
  116. package/dist/mcpi/multibase-ed25519.d.mts.map +1 -0
  117. package/dist/mcpi/multibase-ed25519.d.ts +10 -8
  118. package/dist/mcpi/multibase-ed25519.d.ts.map +1 -0
  119. package/dist/mcpi/multibase-ed25519.js +182 -106
  120. package/dist/mcpi/multibase-ed25519.mjs +181 -103
  121. package/dist/mcpi/multibase-ed25519.mjs.map +1 -0
  122. package/dist/patterns-CkRVOdtV.js +243 -0
  123. package/dist/patterns-DzkGy_qk.mjs +173 -0
  124. package/dist/patterns-DzkGy_qk.mjs.map +1 -0
  125. package/dist/project-verification-key-C3L5rd8a.js +41 -0
  126. package/dist/project-verification-key-CgSVX9_m.mjs +37 -0
  127. package/dist/project-verification-key-CgSVX9_m.mjs.map +1 -0
  128. package/dist/rolldown-runtime-iY2fYEqi.mjs +19 -0
  129. package/dist/schemas-BmjNLAE7.js +5677 -0
  130. package/dist/schemas-DxY-dk9y.mjs +5511 -0
  131. package/dist/schemas-DxY-dk9y.mjs.map +1 -0
  132. package/dist/signals/index.d.mts +125 -115
  133. package/dist/signals/index.d.mts.map +1 -0
  134. package/dist/signals/index.d.ts +125 -115
  135. package/dist/signals/index.d.ts.map +1 -0
  136. package/dist/signals/index.js +1693 -1536
  137. package/dist/signals/index.mjs +1692 -1533
  138. package/dist/signals/index.mjs.map +1 -0
  139. package/dist/test-fixtures/index.d.mts +124 -119
  140. package/dist/test-fixtures/index.d.mts.map +1 -0
  141. package/dist/test-fixtures/index.d.ts +124 -119
  142. package/dist/test-fixtures/index.d.ts.map +1 -0
  143. package/dist/test-fixtures/index.js +460 -228
  144. package/dist/test-fixtures/index.mjs +459 -225
  145. package/dist/test-fixtures/index.mjs.map +1 -0
  146. package/dist/tool-protection/index.d.mts +343 -343
  147. package/dist/tool-protection/index.d.mts.map +1 -0
  148. package/dist/tool-protection/index.d.ts +343 -343
  149. package/dist/tool-protection/index.d.ts.map +1 -0
  150. package/dist/tool-protection/index.js +366 -285
  151. package/dist/tool-protection/index.mjs +365 -282
  152. package/dist/tool-protection/index.mjs.map +1 -0
  153. package/fixtures/bot-signal-resolution.json +142 -0
  154. package/fixtures/browser-posture-claims.json +421 -0
  155. package/fixtures/browser-posture-headers.json +46 -0
  156. package/fixtures/detection/reason-codes.json +10 -1
  157. package/fixtures/kya-http/challenge.delegation.fetcher-200.json +9 -3
  158. package/fixtures/kya-http/challenge.delegation.full.json +9 -3
  159. package/fixtures/kya-http/challenge.delegation.minimal.json +9 -3
  160. package/fixtures/kya-http/error-codes.json +7 -2
  161. package/package.json +20 -6
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/tool-protection/index.ts","../../../src/mcpi/dashboard-config/schemas.ts","../../../src/mcpi/dashboard-config/default-config.ts"],"sourcesContent":["/**\n * KYA-OS Tool Protection Specification\n *\n * Core types for tool protection with delegation requirements.\n *\n * Consent Flow: type='none' → 2 screens, others → 3 screens (Auth→Consent→Success).\n * DelegationCredential (VC) is created when user confirms on Consent Screen.\n *\n * Ported into checkpoint-shared from `@kya-os/contracts/tool-protection` as part\n * of the E6 / C-series decommission (#2914 / #2917): checkpoint owns its product\n * types now that the DIF `@kya-os/mcp` core is protocol-only. The single external\n * dependency (`envVarNameSchema` from the contracts `vault` module) is inlined\n * below so this module pulls nothing from `@kya-os/contracts`.\n *\n * @module @kya-os/checkpoint-shared/tool-protection\n */\n\nimport { z } from 'zod';\n\n/**\n * Pattern for valid environment variable names (e.g., X_API_KEY, OPENAI_KEY).\n * Inlined from the former `@kya-os/contracts/vault` `ENV_VAR_PATTERN`.\n */\nconst ENV_VAR_PATTERN = /^[A-Z][A-Z0-9_]*$/;\n\n/**\n * Validates an env var name used by the `apikey` authorization requirement.\n * Inlined from the former `@kya-os/contracts/vault` `envVarNameSchema`.\n */\nconst envVarNameSchema = z\n .string()\n .regex(ENV_VAR_PATTERN, 'Must be a valid env var name (e.g., X_API_KEY)')\n .max(255);\n\n/**\n * Authorization Requirement - what auth is needed BEFORE consent screen.\n *\n * Types: none (2 screens), oauth/password/mdl/idv (3 screens), verifiable_credential (future).\n * The VC output is always a DelegationCredential created on consent confirmation.\n */\nexport type AuthorizationRequirement =\n | {\n /**\n * @deprecated Use 'oauth2' instead. Will be removed in v2.0.0.\n */\n type: 'oauth';\n provider: string; // \"github\", \"google\", etc.\n requiredScopes?: string[]; // Provider-specific scopes\n }\n | {\n /** OAuth 2.0 provider authentication (canonical) */\n type: 'oauth2';\n provider: string; // \"github\", \"google\", etc.\n requiredScopes?: string[]; // Provider-specific scopes\n }\n | {\n type: 'password';\n provider: string; // Credential provider ID (e.g., \"hardwareworld\", \"custom\")\n }\n | {\n type: 'mdl';\n issuer: string; // MDL issuer DID or identifier\n credentialType?: string; // Specific MDL credential type\n }\n | {\n type: 'idv';\n provider: string; // IDV provider name\n verificationLevel?: 'basic' | 'enhanced' | 'loa3';\n }\n | {\n /** Require user to present an existing VC */\n type: 'verifiable_credential';\n credentialType: string;\n issuer?: string;\n }\n | {\n /**\n * @deprecated Use 'verifiable_credential' instead. Will be removed in v2.0.0.\n * This is an alias for 'verifiable_credential' for backward compatibility.\n */\n type: 'credential';\n credentialType: string;\n issuer?: string;\n }\n | {\n /** WebAuthn/Passkey authentication */\n type: 'webauthn';\n rpId?: string; // Relying Party ID\n userVerification?: 'required' | 'preferred' | 'discouraged';\n }\n | {\n /** Sign-In with Ethereum (EIP-4361) */\n type: 'siwe';\n chainId?: number; // Ethereum chain ID (1 = mainnet, 137 = polygon, etc.)\n domain?: string; // Domain for SIWE message\n }\n | {\n /** API Key from per-user vault */\n type: 'apikey';\n envVarNames: string[]; // Env var names to resolve from vault (e.g., ['X_API_KEY'])\n headerMapping: Record<string, string>; // Map env var → HTTP header (e.g., { X_API_KEY: 'X-API-Key' })\n }\n | {\n type: 'none'; // Just consent checkbox, no external auth\n };\n\n/** Canonical authorization type values for type safety */\nexport const AUTHORIZATION_TYPES = {\n /** @deprecated Use OAUTH2 instead. Will be removed in v2.0.0. */\n OAUTH: 'oauth',\n /** OAuth 2.0 provider authentication (canonical) */\n OAUTH2: 'oauth2',\n PASSWORD: 'password',\n MDL: 'mdl',\n IDV: 'idv',\n VERIFIABLE_CREDENTIAL: 'verifiable_credential',\n /** WebAuthn/Passkey authentication */\n WEBAUTHN: 'webauthn',\n /** Sign-In with Ethereum (EIP-4361) */\n SIWE: 'siwe',\n /** API Key from per-user vault */\n APIKEY: 'apikey',\n NONE: 'none',\n} as const;\n\nexport type AuthorizationType = (typeof AUTHORIZATION_TYPES)[keyof typeof AUTHORIZATION_TYPES];\n\n/**\n * Tool Protection Definition\n *\n * Defines the protection requirements for a tool as per KYA-OS spec.\n * This is the canonical definition that all implementations must follow.\n */\nexport interface ToolProtection {\n /**\n * Whether this tool requires explicit delegation from the user\n */\n requiresDelegation: boolean;\n\n /**\n * The scopes required to execute this tool\n * Format: \"resource:action\" (e.g., \"files:read\", \"payment:send\")\n */\n requiredScopes: string[];\n\n /**\n * Risk level classification for the tool\n * Used to determine appropriate authorization flows\n */\n riskLevel?: 'low' | 'medium' | 'high' | 'critical';\n\n /**\n * OAuth provider name for this tool (Phase 2+)\n * If specified, this tool will use the specified OAuth provider.\n * If not specified, provider will be resolved via fallback strategies.\n * @example \"github\", \"google\", \"microsoft\"\n * @deprecated Use `authorization` field instead. Will be removed in Phase 3.\n */\n oauthProvider?: string;\n\n /**\n * Authorization requirement for this tool\n * If requiresDelegation=true, authorization must be specified (or inferred from legacy fields)\n */\n authorization?: AuthorizationRequirement;\n}\n\n/**\n * Tool Protection Map\n *\n * A mapping of tool names to their protection configurations.\n * This is how tool protections are typically stored and transmitted.\n */\nexport type ToolProtectionMap = Record<string, ToolProtection>;\n\n/**\n * Partial tool protection for updates (all fields optional)\n * Use this when accepting partial updates to tool protection settings\n */\nexport type PartialToolProtection = Partial<ToolProtection>;\n\n/**\n * Tool protection with explicit optional fields\n * Useful when TypeScript's Partial<T> doesn't preserve optional property access\n * Supports explicit null values to clear fields\n */\nexport type ToolProtectionUpdate = {\n requiresDelegation?: boolean;\n requiredScopes?: string[];\n riskLevel?: 'low' | 'medium' | 'high' | 'critical';\n oauthProvider?: string | null; // null explicitly clears the field\n authorization?: AuthorizationRequirement | null; // null explicitly clears the field\n};\n\n/**\n * Tool Protection Response\n *\n * The response format when querying for tool protections.\n * Used by tool protection services and APIs.\n */\nexport interface ToolProtectionResponse {\n /**\n * The tool protections keyed by tool name\n */\n toolProtections: ToolProtectionMap;\n\n /**\n * Optional metadata about the response\n */\n metadata?: {\n /**\n * When this configuration was last updated\n */\n lastUpdated?: string;\n\n /**\n * Version of the configuration\n */\n version?: string;\n\n /**\n * Source of the configuration\n */\n source?: string;\n };\n}\n\n/**\n * Delegation Required Error Data\n *\n * The standardized error data returned when a tool requires delegation\n * but none was provided. This is part of the KYA-OS error protocol.\n */\nexport interface DelegationRequiredErrorData {\n /**\n * The name of the tool that requires delegation\n */\n toolName: string;\n\n /**\n * The scopes required for this tool\n */\n requiredScopes: string[];\n\n /**\n * URL where the user can provide consent/delegation\n */\n consentUrl?: string;\n\n /**\n * Alternative field for consent URL (for compatibility)\n */\n authorizationUrl?: string;\n\n /**\n * Additional context about why delegation is required\n */\n reason?: string;\n}\n\n/**\n * Auth Required Error Data\n *\n * Machine-readable error returned when a tool requires per-user auth\n * (vault secret, OAuth, credential) but none is configured and no\n * static env fallback exists. MCP clients use this to present\n * actionable guidance (e.g., \"Add your PulseMCP API key\" with a link).\n *\n * Closes VAULT-11\n */\nexport interface AuthRequiredErrorData {\n /** Discriminator — always \"auth_required\" */\n error: 'auth_required';\n\n /** Which auth mechanism is missing */\n type: 'apikey' | 'oauth' | 'credential';\n\n /** For apikey: which env vars are missing */\n envVarNames?: string[];\n\n /** Dashboard URL where the user can configure the missing auth */\n configUrl: string;\n\n /** Human-readable fallback message */\n message: string;\n}\n\nexport const AuthRequiredErrorDataSchema = z.object({\n error: z.literal('auth_required'),\n type: z.enum(['apikey', 'oauth', 'credential']),\n envVarNames: z.array(z.string()).optional(),\n configUrl: z.string(),\n message: z.string(),\n});\n\n/**\n * Error class thrown when required auth is missing and no fallback exists.\n *\n * Caught by the tool-call handler in agent.ts and serialized as a\n * machine-readable MCP tool result so clients can present actionable UI.\n */\nexport class AuthRequiredError extends Error {\n public readonly type: AuthRequiredErrorData['type'];\n public readonly envVarNames?: string[];\n public readonly configUrl: string;\n\n constructor(opts: {\n type: AuthRequiredErrorData['type'];\n envVarNames?: string[];\n configUrl: string;\n message?: string;\n }) {\n const message =\n opts.message ??\n (opts.type === 'apikey' && opts.envVarNames?.length\n ? `API key required: configure ${opts.envVarNames.join(', ')} in your project settings.`\n : 'Authentication required to use this tool.');\n super(message);\n this.name = 'AuthRequiredError';\n this.type = opts.type;\n this.envVarNames = opts.envVarNames;\n this.configUrl = opts.configUrl;\n }\n\n /** Serialize to the wire format MCP clients expect */\n toJSON(): AuthRequiredErrorData {\n return {\n error: 'auth_required',\n type: this.type,\n ...(this.envVarNames && { envVarNames: this.envVarNames }),\n configUrl: this.configUrl,\n message: this.message,\n };\n }\n}\n\n/**\n * Legacy tool protection format (pre-authorization field)\n * Used during migration period to support both old and new formats\n */\nexport type LegacyToolProtection = Omit<ToolProtection, 'authorization'> & {\n oauthProvider?: string;\n};\n\n/**\n * Union type for both legacy and new formats\n * Useful during migration period when accepting tool protection input\n */\nexport type ToolProtectionInput = ToolProtection | LegacyToolProtection;\n\n/**\n * Zod Schemas for Validation\n */\n\nexport const AuthorizationRequirementSchema = z.discriminatedUnion('type', [\n // Deprecated: 'oauth' is an alias for 'oauth2'\n // Will be removed in v2.0.0. Use 'oauth2' instead.\n z.object({\n type: z.literal('oauth'),\n provider: z.string(),\n requiredScopes: z.array(z.string()).optional(),\n }),\n // OAuth 2.0 provider authentication (canonical)\n z.object({\n type: z.literal('oauth2'),\n provider: z.string(),\n requiredScopes: z.array(z.string()).optional(),\n }),\n z.object({\n type: z.literal('password'),\n provider: z.string(),\n }),\n z.object({\n type: z.literal('mdl'),\n issuer: z.string(),\n credentialType: z.string().optional(),\n }),\n z.object({\n type: z.literal('idv'),\n provider: z.string(),\n verificationLevel: z.enum(['basic', 'enhanced', 'loa3']).optional(),\n }),\n z.object({\n type: z.literal('verifiable_credential'),\n credentialType: z.string(),\n issuer: z.string().optional(),\n }),\n // Deprecated: 'credential' is an alias for 'verifiable_credential'\n // Will be removed in v2.0.0. Use 'verifiable_credential' instead.\n z.object({\n type: z.literal('credential'),\n credentialType: z.string(),\n issuer: z.string().optional(),\n }),\n // WebAuthn/Passkey authentication\n z.object({\n type: z.literal('webauthn'),\n rpId: z.string().optional(),\n userVerification: z.enum(['required', 'preferred', 'discouraged']).optional(),\n }),\n // Sign-In with Ethereum (EIP-4361)\n z.object({\n type: z.literal('siwe'),\n chainId: z.number().optional(),\n domain: z.string().optional(),\n }),\n // API Key from per-user vault\n z.object({\n type: z.literal('apikey'),\n envVarNames: z.array(envVarNameSchema).min(1),\n headerMapping: z.record(z.string(), z.string()),\n }),\n z.object({\n type: z.literal('none'),\n }),\n]);\n\nexport const ToolProtectionSchema = z.object({\n requiresDelegation: z.boolean(),\n requiredScopes: z.array(z.string()),\n riskLevel: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n oauthProvider: z.string().optional(), // Phase 2: Tool-specific OAuth provider\n authorization: AuthorizationRequirementSchema.optional(),\n});\n\nexport const ToolProtectionMapSchema = z.record(z.string(), ToolProtectionSchema);\n\nexport const ToolProtectionResponseSchema = z.object({\n toolProtections: ToolProtectionMapSchema,\n metadata: z\n .object({\n lastUpdated: z.string().optional(),\n version: z.string().optional(),\n source: z.string().optional(),\n })\n .optional(),\n});\n\nexport const DelegationRequiredErrorDataSchema = z.object({\n toolName: z.string(),\n requiredScopes: z.array(z.string()),\n consentUrl: z.string().optional(),\n authorizationUrl: z.string().optional(),\n reason: z.string().optional(),\n});\n\n/**\n * Type Guards\n */\n\nexport function isToolProtection(obj: unknown): obj is ToolProtection {\n return ToolProtectionSchema.safeParse(obj).success;\n}\n\nexport function isToolProtectionMap(obj: unknown): obj is ToolProtectionMap {\n return ToolProtectionMapSchema.safeParse(obj).success;\n}\n\nexport function isToolProtectionResponse(obj: unknown): obj is ToolProtectionResponse {\n return ToolProtectionResponseSchema.safeParse(obj).success;\n}\n\nexport function isDelegationRequiredErrorData(obj: unknown): obj is DelegationRequiredErrorData {\n return DelegationRequiredErrorDataSchema.safeParse(obj).success;\n}\n\n/**\n * Type guard to check if an object is a valid AuthorizationRequirement\n */\nexport function isAuthorizationRequirement(obj: unknown): obj is AuthorizationRequirement {\n return AuthorizationRequirementSchema.safeParse(obj).success;\n}\n\n/**\n * Type guard to check if a ToolProtection has OAuth authorization\n * Checks for both 'oauth' (deprecated) and 'oauth2' (canonical)\n */\nexport function hasOAuthAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & { authorization: { type: 'oauth' | 'oauth2' } } {\n return protection.authorization?.type === 'oauth' || protection.authorization?.type === 'oauth2';\n}\n\n/**\n * Type guard to check if a ToolProtection has password authorization\n */\nexport function hasPasswordAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & { authorization: { type: 'password' } } {\n return protection.authorization?.type === 'password';\n}\n\n/**\n * Type guard to check if a ToolProtection requires a Verifiable Credential\n *\n * Note: Also returns true for deprecated 'credential' type (normalized to verifiable_credential)\n */\nexport function hasVerifiableCredentialAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & {\n authorization: { type: 'verifiable_credential' | 'credential' };\n} {\n return (\n protection.authorization?.type === 'verifiable_credential' ||\n protection.authorization?.type === 'credential'\n );\n}\n\n/**\n * Type guard to check if a ToolProtection has API Key (vault) authorization\n */\nexport function hasApiKeyAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & { authorization: { type: 'apikey' } } {\n return protection.authorization?.type === 'apikey';\n}\n\n/**\n * Validation Functions\n */\n\nexport function validateToolProtection(obj: unknown): ToolProtection {\n return ToolProtectionSchema.parse(obj);\n}\n\nexport function validateToolProtectionMap(obj: unknown): ToolProtectionMap {\n return ToolProtectionMapSchema.parse(obj);\n}\n\nexport function validateToolProtectionResponse(obj: unknown): ToolProtectionResponse {\n return ToolProtectionResponseSchema.parse(obj);\n}\n\nexport function validateDelegationRequiredErrorData(obj: unknown): DelegationRequiredErrorData {\n return DelegationRequiredErrorDataSchema.parse(obj);\n}\n\n/**\n * Utility Functions\n */\n\n/**\n * Check if a tool requires delegation\n */\nexport function toolRequiresDelegation(toolName: string, protections: ToolProtectionMap): boolean {\n const protection = protections[toolName];\n return protection?.requiresDelegation ?? false;\n}\n\n/**\n * Get required scopes for a tool\n */\nexport function getToolRequiredScopes(toolName: string, protections: ToolProtectionMap): string[] {\n const protection = protections[toolName];\n return protection?.requiredScopes ?? [];\n}\n\n/**\n * Get risk level for a tool\n */\nexport function getToolRiskLevel(\n toolName: string,\n protections: ToolProtectionMap\n): ToolProtection['riskLevel'] | undefined {\n return protections[toolName]?.riskLevel;\n}\n\n/**\n * Create a delegation required error\n */\nexport function createDelegationRequiredError(\n toolName: string,\n requiredScopes: string[],\n consentUrl?: string\n): DelegationRequiredErrorData {\n return {\n toolName,\n requiredScopes,\n consentUrl,\n authorizationUrl: consentUrl, // Include both for compatibility\n };\n}\n\n/**\n * Normalize tool protection configuration\n * Migrates legacy oauthProvider field to authorization object\n *\n * - Migrates `oauthProvider` → `authorization: { type: 'oauth', provider: ... }`\n * - Ensures `authorization` field is present when `requiresDelegation=true`\n * - Returns fully normalized ToolProtection object\n *\n * @param raw - Raw tool protection data (may have legacy fields or be partial)\n * @returns Normalized ToolProtection object\n *\n * // TODO: Remove normalizeToolProtection() when all tools migrated\n */\nexport function normalizeToolProtection(\n raw: ToolProtection | PartialToolProtection\n): ToolProtection {\n // Ensure we have required fields (provide defaults for partial input)\n const normalized: ToolProtection = {\n requiresDelegation: raw.requiresDelegation ?? false,\n requiredScopes: raw.requiredScopes ?? [],\n ...(raw.riskLevel && { riskLevel: raw.riskLevel }),\n ...(raw.oauthProvider && { oauthProvider: raw.oauthProvider }),\n };\n\n // If authorization is already present, use it\n if (raw.authorization) {\n normalized.authorization = raw.authorization;\n return normalized;\n }\n\n // Migrate oauthProvider to authorization\n if (raw.oauthProvider) {\n normalized.authorization = {\n type: 'oauth',\n provider: raw.oauthProvider,\n };\n // Keep oauthProvider for backward compatibility\n return normalized;\n }\n\n // Default for requiresDelegation=true without specific auth: type='none' (consent only)\n // But ONLY if authorization is missing entirely\n if (normalized.requiresDelegation && !normalized.authorization && !normalized.oauthProvider) {\n // We don't automatically set type='none' here to allow\n // ProviderResolver to do its scope inference fallback logic.\n // The fallback logic will eventually be moved into an AuthorizationService.\n return normalized;\n }\n\n return normalized;\n}\n\n// =============================================================================\n// CONSENT PROVIDER TYPES - Records what auth method was USED (not required)\n// =============================================================================\n\n/** Consent provider types - stored in delegation metadata to track auth method used */\nexport const CONSENT_PROVIDER_TYPES = {\n /** Consent-only mode - no authentication, just clickwrap agreement */\n NONE: 'none',\n /** OAuth2 provider authentication */\n OAUTH2: 'oauth2',\n /** Password-based authentication (email/password, username/password) */\n PASSWORD: 'password',\n /** @deprecated Use PASSWORD instead. Alias for backward compatibility */\n CREDENTIAL: 'credential',\n /** Email magic link authentication */\n MAGIC_LINK: 'magic_link',\n /** One-time password (SMS/email code) */\n OTP: 'otp',\n} as const;\n\nexport type ConsentProviderType =\n (typeof CONSENT_PROVIDER_TYPES)[keyof typeof CONSENT_PROVIDER_TYPES];\n\n/**\n * Determine consent provider type based on available identity information\n *\n * This is the single source of truth for consent provider type determination.\n *\n * @param hasOAuthIdentity - Whether OAuth identity is available\n * @param isPasswordFlow - Whether this is a password/credential flow\n * @param isMagicLinkFlow - Whether this is a magic link flow\n * @param isOtpFlow - Whether this is an OTP flow\n * @returns The consent provider type\n */\nexport function determineConsentProviderType(\n hasOAuthIdentity: boolean,\n isPasswordFlow: boolean = false,\n isMagicLinkFlow: boolean = false,\n isOtpFlow: boolean = false\n): ConsentProviderType {\n if (isPasswordFlow) {\n return CONSENT_PROVIDER_TYPES.PASSWORD;\n }\n if (isMagicLinkFlow) {\n return CONSENT_PROVIDER_TYPES.MAGIC_LINK;\n }\n if (isOtpFlow) {\n return CONSENT_PROVIDER_TYPES.OTP;\n }\n if (hasOAuthIdentity) {\n return CONSENT_PROVIDER_TYPES.OAUTH2;\n }\n return CONSENT_PROVIDER_TYPES.NONE;\n}\n\n/**\n * Get a human-readable label for an authorization requirement type\n */\nexport function getAuthorizationTypeLabel(auth: AuthorizationRequirement): string {\n switch (auth.type) {\n case 'oauth':\n case 'oauth2':\n return auth.provider\n ? auth.provider.charAt(0).toUpperCase() + auth.provider.slice(1)\n : 'OAuth Provider';\n case 'password':\n return 'Password Authentication';\n case 'mdl':\n return \"Mobile Driver's License\";\n case 'idv':\n return 'Identity Verification';\n case 'verifiable_credential':\n return auth.credentialType || 'Verifiable Credential';\n case 'credential':\n // Deprecated: treat as verifiable_credential\n return auth.credentialType || 'Verifiable Credential';\n case 'webauthn':\n return 'Passkey / WebAuthn';\n case 'siwe':\n return 'Sign-In with Ethereum';\n case 'apikey':\n return 'API Key (Vault)';\n case 'none':\n return 'Consent Only';\n default: {\n // Closed union — this default is unreachable for well-typed input.\n return 'Unknown';\n }\n }\n}\n\n/**\n * Get a unique key for an authorization requirement (for React keys, caching, etc.)\n */\nexport function getAuthorizationTypeKey(auth: AuthorizationRequirement): string {\n switch (auth.type) {\n case 'oauth':\n // Keep original key format for backward compatibility with existing cache entries\n // Handle undefined provider gracefully (may come from loose API response types)\n return auth.provider ? `oauth:${auth.provider}` : 'oauth';\n case 'oauth2':\n return auth.provider ? `oauth2:${auth.provider}` : 'oauth2';\n case 'password':\n return auth.provider ? `password:${auth.provider}` : 'password';\n case 'mdl':\n // Keep trailing colon for backward compatibility with existing cache entries\n return `mdl:${auth.issuer || 'unknown'}:${auth.credentialType || ''}`;\n case 'idv':\n // Keep trailing colon for backward compatibility with existing cache entries\n return `idv:${auth.provider || 'unknown'}:${auth.verificationLevel || ''}`;\n case 'verifiable_credential':\n return `vc:${auth.issuer || 'any'}:${auth.credentialType || 'unknown'}`;\n case 'credential':\n // Deprecated: treat as verifiable_credential\n return `vc:${auth.issuer || 'any'}:${auth.credentialType || 'unknown'}`;\n case 'webauthn':\n return `webauthn:${auth.rpId || 'default'}`;\n case 'siwe':\n return `siwe:${auth.chainId || 1}:${auth.domain || 'any'}`;\n case 'apikey':\n return `apikey:${[...auth.envVarNames].sort().join(',')}`;\n case 'none':\n return 'none';\n default: {\n // Closed union — this default is unreachable for well-typed input.\n return 'unknown';\n }\n }\n}\n\n/**\n * Normalize authorization requirement type\n *\n * Normalizes deprecated types to their canonical equivalents:\n * - 'oauth' → 'oauth2'\n * - 'credential' → 'verifiable_credential'\n *\n * This function should be called at runtime boundaries when processing\n * authorization requirements.\n *\n * @param auth - Authorization requirement (may contain deprecated types)\n * @param options - Normalization options\n * @returns Normalized authorization requirement\n *\n * @example\n * ```typescript\n * const normalized = normalizeAuthorizationType(\n * { type: 'oauth', provider: 'github' },\n * { warn: true }\n * );\n * // Returns: { type: 'oauth2', provider: 'github' }\n * // Logs: DEPRECATION warning\n * ```\n */\nexport function normalizeAuthorizationType(\n auth: AuthorizationRequirement,\n options: { warn?: boolean; logger?: (message: string) => void } = {}\n): AuthorizationRequirement {\n const { warn = true, logger = console.warn } = options;\n\n // Normalize 'oauth' to 'oauth2'\n if (auth.type === 'oauth') {\n if (warn) {\n logger(\n `DEPRECATION: Authorization type 'oauth' is deprecated and will be removed in v2.0.0. ` +\n `Please update to 'oauth2'. ` +\n `See https://github.com/modelcontextprotocol-identity/xmcp-i/blob/main/docs/migrations/oauth-to-oauth2.md`\n );\n }\n\n // Normalize to oauth2\n const normalized = {\n type: 'oauth2' as const,\n provider: auth.provider,\n ...(auth.requiredScopes !== undefined && { requiredScopes: auth.requiredScopes }),\n };\n\n return normalized;\n }\n\n // Normalize 'credential' to 'verifiable_credential'\n if (auth.type === 'credential') {\n if (warn) {\n logger(\n `DEPRECATION: Authorization type 'credential' is deprecated and will be removed in v2.0.0. ` +\n `Please update to 'verifiable_credential'. ` +\n `See https://github.com/modelcontextprotocol-identity/xmcp-i/blob/main/docs/migrations/credential-to-verifiable_credential.md`\n );\n }\n\n // Normalize to verifiable_credential\n const normalized = {\n type: 'verifiable_credential' as const,\n credentialType: auth.credentialType,\n ...(auth.issuer !== undefined && { issuer: auth.issuer }),\n };\n\n return normalized;\n }\n\n // No normalization needed\n return auth;\n}\n","/**\n * Dashboard Configuration Zod Schemas\n *\n * Runtime validation schemas for dashboard configuration types.\n * Used for validating API requests and responses.\n *\n * Ported into checkpoint-shared from `@kya-os/contracts/dashboard-config` as part\n * of the E6 / C-series decommission (#2914 / #2917). The only cross-module\n * dependency (`ToolProtectionSchema`/`ToolProtectionMapSchema`) now resolves to\n * the local `../../tool-protection` module.\n *\n * @module @kya-os/checkpoint-shared/dashboard-config\n */\n\nimport { z } from 'zod';\nimport { ToolProtectionMapSchema } from '../../tool-protection';\n\n/**\n * Identity configuration schema\n */\nexport const identityConfigSchema = z.object({\n /**\n * @deprecated Use serverDid instead. Will be removed in v2.0\n */\n agentDid: z.string().min(1).optional(),\n serverDid: z.string().min(1),\n environment: z.enum(['development', 'production']),\n storageLocation: z.enum(['cloudflare-kv', 'file-system', 'env-vars']),\n});\n\n/**\n * Proofing configuration schema\n */\nexport const proofingConfigSchema = z.object({\n enabled: z.boolean(),\n destinations: z.array(\n z.object({\n type: z.enum(['agentshield', 'kta', 'custom']),\n apiUrl: z.string().url(),\n apiKey: z.string().optional(),\n })\n ),\n batchQueue: z.object({\n maxBatchSize: z.number().int().positive().default(10),\n flushIntervalMs: z.number().int().positive().default(5000),\n maxRetries: z.number().int().nonnegative().default(3),\n }),\n});\n\n/**\n * Delegation verifier type schema\n */\nconst delegationVerifierTypeSchema = z.enum([\n 'agentshield',\n 'kta',\n 'memory',\n 'cloudflare-kv',\n 'redis',\n 'dynamodb',\n 'custom',\n]);\n\n/**\n * Delegation configuration schema\n */\nexport const delegationConfigSchema = z.object({\n enabled: z.boolean(),\n enforceStrictly: z.boolean(),\n verifier: z.object({\n type: delegationVerifierTypeSchema,\n apiUrl: z.string().url().optional(),\n cacheTtl: z.number().int().positive().optional(),\n }),\n authorization: z.object({\n authorizationUrl: z.string().url().optional(),\n minReputationScore: z.number().int().min(0).max(100).optional(),\n resumeTokenTtl: z.number().int().positive().optional(),\n requireAuthForUnknown: z.boolean().optional(),\n }),\n});\n\n/**\n * Tool protection configuration schema\n */\nexport const toolProtectionConfigSchema = z.object({\n source: z.enum(['agentshield', 'inline', 'file']),\n agentShield: z\n .object({\n apiUrl: z.string().url(),\n cacheTtl: z.number().int().positive(),\n })\n .optional(),\n fallback: ToolProtectionMapSchema.optional(),\n});\n\n/** Merged tool protection config with embedded tools */\nexport const mergedToolProtectionConfigSchema = toolProtectionConfigSchema.extend({\n tools: ToolProtectionMapSchema,\n});\n\n/**\n * Audit configuration schema\n */\nexport const auditConfigSchema = z.object({\n enabled: z.boolean(),\n includeProofHashes: z.boolean(),\n includePayloads: z.boolean(),\n});\n\n/**\n * Session configuration schema\n */\nexport const sessionConfigSchema = z.object({\n timestampSkewSeconds: z.number().int().positive().default(120),\n ttlMinutes: z.number().int().positive().default(30),\n absoluteLifetime: z.number().int().positive().optional(),\n});\n\n/**\n * Cloudflare platform configuration schema\n */\nexport const cloudflarePlatformConfigSchema = z.object({\n workers: z.object({\n cpuMs: z.number().int().positive().default(50),\n memoryMb: z.number().int().positive().default(128),\n }),\n kvNamespaces: z.array(\n z.object({\n name: z.string().min(1),\n purpose: z.enum(['sessions', 'delegations', 'cache', 'general']),\n })\n ),\n environmentVariables: z.array(\n z.object({\n name: z.string().min(1),\n value: z.string(),\n source: z.enum(['wrangler.toml', 'secrets', '.dev.vars']),\n })\n ),\n});\n\n/**\n * Node.js platform configuration schema\n */\nexport const nodePlatformConfigSchema = z.object({\n server: z.object({\n port: z.number().int().positive().default(3000),\n host: z.string().default('0.0.0.0'),\n cors: z.boolean().default(true),\n timeout: z.number().int().positive().default(30000),\n }),\n storage: z.object({\n type: z.enum(['memory', 'redis', 'postgres', 'mongodb']),\n connection: z\n .object({\n host: z.string().optional(),\n port: z.number().int().positive().optional(),\n database: z.string().optional(),\n })\n .optional(),\n }),\n});\n\n/**\n * Vercel platform configuration schema\n */\nexport const vercelPlatformConfigSchema = z.object({\n environmentVariables: z.array(\n z.object({\n name: z.string().min(1),\n value: z.string(),\n source: z.enum(['vercel-dashboard', '.env.local']),\n })\n ),\n edgeRuntime: z\n .object({\n maxDuration: z.number().int().positive().optional(),\n regions: z.array(z.string()).optional(),\n })\n .optional(),\n});\n\n/**\n * Platform configuration schema\n */\nexport const platformConfigSchema = z.object({\n type: z.enum(['cloudflare', 'node', 'vercel']),\n cloudflare: cloudflarePlatformConfigSchema.optional(),\n node: nodePlatformConfigSchema.optional(),\n vercel: vercelPlatformConfigSchema.optional(),\n});\n\n/**\n * Metadata schema\n */\nexport const configMetadataSchema = z.object({\n version: z.string(),\n lastUpdated: z.string(),\n source: z.enum(['dashboard', 'code', 'mixed']),\n serverUrl: z.string().url().optional(),\n deploymentStatus: z.enum(['active', 'inactive', 'error']).optional(),\n});\n\n/**\n * Complete KYA-OS Server Configuration schema\n */\nexport const mcpIServerConfigSchema = z.object({\n identity: identityConfigSchema,\n proofing: proofingConfigSchema,\n delegation: delegationConfigSchema,\n toolProtection: toolProtectionConfigSchema,\n audit: auditConfigSchema,\n session: sessionConfigSchema,\n platform: platformConfigSchema,\n metadata: configMetadataSchema,\n});\n\n/** Merged KYA-OS Server Configuration schema @since 1.6.0 */\nexport const mergedMcpIServerConfigSchema = mcpIServerConfigSchema.extend({\n toolProtection: mergedToolProtectionConfigSchema,\n});\n\n/**\n * Get server config request schema\n */\nexport const getServerConfigRequestSchema = z.object({\n projectId: z.string().min(1),\n});\n\n/**\n * Get server config response schema\n */\nexport const getServerConfigResponseSchema = z.object({\n success: z.boolean(),\n data: z.object({\n config: mcpIServerConfigSchema,\n }),\n metadata: z\n .object({\n requestId: z.string().optional(),\n timestamp: z.string().optional(),\n })\n .optional(),\n});\n\n/** Get merged server config response schema @since 1.6.0 */\nexport const getMergedServerConfigResponseSchema = z.object({\n success: z.boolean(),\n data: z.object({\n config: mergedMcpIServerConfigSchema,\n /** @deprecated Use config.toolProtection.tools instead */\n toolProtections: ToolProtectionMapSchema.optional(),\n }),\n metadata: z\n .object({\n requestId: z.string().optional(),\n timestamp: z.string().optional(),\n cachedUntil: z.string().optional(),\n })\n .optional(),\n});\n\n/**\n * Update server config request schema\n */\nexport const updateServerConfigRequestSchema = z.object({\n projectId: z.string().min(1),\n config: mcpIServerConfigSchema.partial(),\n});\n\n/**\n * Update server config response schema\n */\nexport const updateServerConfigResponseSchema = z.object({\n success: z.boolean(),\n data: z.object({\n config: mcpIServerConfigSchema,\n changes: z.array(\n z.object({\n path: z.string(),\n oldValue: z.unknown(),\n newValue: z.unknown(),\n })\n ),\n }),\n metadata: z\n .object({\n requestId: z.string().optional(),\n timestamp: z.string().optional(),\n })\n .optional(),\n});\n\n/**\n * Validate server config request schema\n */\nexport const validateServerConfigRequestSchema = z.object({\n projectId: z.string().min(1),\n config: mcpIServerConfigSchema.partial(),\n});\n\n/**\n * Validate server config response schema\n */\nexport const validateServerConfigResponseSchema = z.object({\n success: z.boolean(),\n data: z.object({\n valid: z.boolean(),\n errors: z\n .array(\n z.object({\n path: z.string(),\n message: z.string(),\n code: z.string(),\n })\n )\n .optional(),\n warnings: z\n .array(\n z.object({\n path: z.string(),\n message: z.string(),\n })\n )\n .optional(),\n }),\n metadata: z\n .object({\n requestId: z.string().optional(),\n timestamp: z.string().optional(),\n })\n .optional(),\n});\n","/**\n * Default Configuration for KYA-OS Servers\n *\n * Provides safe, production-ready defaults for new user configurations.\n * Used by the Checkpoint Dashboard, Scaffolder, and Runtime fallbacks.\n *\n * Ported into checkpoint-shared from the former contracts dashboard-config module\n * as part of the E6 / C-series decommission (#2914 / #2917). Replaces the runtime\n * default-config fallback previously used by\n * `apps/web/lib/services/kyaos-config.service.ts`.\n *\n * @module @kya-os/checkpoint-shared/dashboard-config\n */\n\nimport type { MCPIServerConfig } from './types';\nimport { mcpIServerConfigSchema } from './schemas';\nimport { z } from 'zod';\n\n/**\n * Default configuration JSON content\n * Embedded here to avoid TypeScript JSON import issues in build\n */\nconst defaultConfigJson = {\n identity: {\n // agentDid removed - deprecated, use serverDid instead\n serverDid: '', // New field - will be populated when identity is generated\n environment: 'development' as const,\n storageLocation: 'env-vars' as const,\n },\n proofing: {\n enabled: true,\n destinations: [\n {\n type: 'agentshield' as const,\n apiUrl: 'https://kya.vouched.id',\n },\n ],\n batchQueue: {\n maxBatchSize: 10,\n flushIntervalMs: 5000,\n maxRetries: 3,\n },\n },\n delegation: {\n enabled: true,\n enforceStrictly: false,\n verifier: {\n type: 'agentshield' as const,\n apiUrl: 'https://kya.vouched.id/api/v1/bouncer/delegations/verify',\n cacheTtl: 300000,\n },\n authorization: {\n authorizationUrl: 'https://kya.vouched.id/api/v1/bouncer/delegations/authorize',\n minReputationScore: 80,\n resumeTokenTtl: 3600000,\n requireAuthForUnknown: false,\n },\n },\n toolProtection: {\n source: 'agentshield' as const,\n agentShield: {\n apiUrl: 'https://kya.vouched.id',\n cacheTtl: 300000,\n },\n fallback: {},\n },\n audit: {\n enabled: true,\n includeProofHashes: false,\n includePayloads: false,\n },\n session: {\n timestampSkewSeconds: 120,\n ttlMinutes: 30,\n },\n platform: {\n type: 'node' as const,\n node: {\n server: {\n port: 3000,\n host: '0.0.0.0',\n cors: true,\n timeout: 30000,\n },\n storage: {\n type: 'memory' as const,\n },\n },\n cloudflare: {\n workers: {\n cpuMs: 50,\n memoryMb: 128,\n },\n kvNamespaces: [],\n environmentVariables: [],\n },\n vercel: {\n environmentVariables: [],\n edgeRuntime: {},\n },\n },\n metadata: {\n version: '1.0.0',\n lastUpdated: '',\n source: 'dashboard' as const,\n deploymentStatus: 'inactive' as const,\n },\n};\n\n/**\n * Relaxed schema for default config validation\n * Allows empty strings for fields that will be populated later\n *\n * Note: Empty `agentDid` is valid for new/incomplete configurations.\n * This allows users to create configs before registering their agent DID.\n * The base schema (mcpIServerConfigSchema) requires non-empty agentDid for\n * complete configurations, but defaults allow empty to support progressive\n * configuration.\n */\nconst defaultConfigSchema = mcpIServerConfigSchema.extend({\n identity: mcpIServerConfigSchema.shape.identity.extend({\n agentDid: z.string().optional(), // Allow empty string or undefined for defaults (deprecated)\n serverDid: z.string(), // Allow empty string for defaults (will be populated later)\n }),\n metadata: mcpIServerConfigSchema.shape.metadata.extend({\n lastUpdated: z.string(), // Allow empty string (will be set dynamically)\n }),\n});\n\n/**\n * Default configuration object\n *\n * This is the base default configuration used when creating new user configs.\n * Platform-specific defaults are available via getDefaultConfigForPlatform().\n */\nexport const defaultConfig: MCPIServerConfig = defaultConfigSchema.parse(\n defaultConfigJson\n) as MCPIServerConfig;\n\n/**\n * Platform-specific default configurations\n */\nconst platformDefaults = {\n node: {\n platform: {\n type: 'node' as const,\n node: {\n server: {\n port: 3000,\n host: '0.0.0.0',\n cors: true,\n timeout: 30000,\n },\n storage: {\n type: 'memory' as const,\n },\n },\n },\n },\n cloudflare: {\n platform: {\n type: 'cloudflare' as const,\n cloudflare: {\n workers: {\n cpuMs: 50,\n memoryMb: 128,\n },\n kvNamespaces: [],\n environmentVariables: [],\n },\n },\n },\n vercel: {\n platform: {\n type: 'vercel' as const,\n vercel: {\n environmentVariables: [],\n edgeRuntime: {},\n },\n },\n },\n};\n\n/**\n * Get default configuration for a specific platform\n *\n * Returns the base default config merged with platform-specific defaults.\n *\n * @param platform - Platform type ('node', 'cloudflare', or 'vercel')\n * @returns Platform-specific default configuration\n *\n * @example\n * ```typescript\n * const nodeConfig = getDefaultConfigForPlatform('node');\n * const cloudflareConfig = getDefaultConfigForPlatform('cloudflare');\n * ```\n */\nexport function getDefaultConfigForPlatform(\n platform: 'node' | 'cloudflare' | 'vercel'\n): MCPIServerConfig {\n const platformDefault = platformDefaults[platform];\n\n return {\n ...defaultConfig,\n platform: platformDefault.platform,\n } as MCPIServerConfig;\n}\n\n/**\n * Deep merge utility for objects\n */\nfunction deepMerge<T extends Record<string, unknown>>(target: T, source: Partial<T>): T {\n const result = { ...target } as T;\n\n for (const key in source) {\n const sourceValue = source[key];\n // The leading truthy check already excludes null, so an explicit\n // `!== null` here is redundant (and flagged as such by static analysis).\n if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) {\n const targetValue = target[key];\n if (targetValue && typeof targetValue === 'object' && !Array.isArray(targetValue)) {\n result[key] = deepMerge(\n targetValue as Record<string, unknown>,\n sourceValue as Record<string, unknown>\n ) as T[Extract<keyof T, string>];\n }\n } else if (sourceValue !== undefined) {\n result[key] = sourceValue as T[Extract<keyof T, string>];\n }\n }\n\n return result;\n}\n\n/**\n * Merge partial configuration with defaults\n *\n * Deep merges a partial configuration object with the base defaults,\n * ensuring all required fields are present.\n *\n * @param partial - Partial configuration to merge with defaults\n * @returns Complete configuration with defaults applied\n *\n * @example\n * ```typescript\n * const config = mergeWithDefaults({\n * proofing: { enabled: false },\n * identity: { environment: 'production' }\n * });\n * ```\n */\nexport function mergeWithDefaults(partial: Partial<MCPIServerConfig>): MCPIServerConfig {\n return deepMerge(\n defaultConfig as unknown as Record<string, unknown>,\n partial as unknown as Record<string, unknown>\n ) as unknown as MCPIServerConfig;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,mBAAmB,EACtB,OAAO,CAAC,CACR,MAAM,qBAAiB,gDAAgD,CAAC,CACxE,IAAI,GAAG;AA+PV,MAAa,8BAA8B,EAAE,OAAO;CAClD,OAAO,EAAE,QAAQ,eAAe;CAChC,MAAM,EAAE,KAAK;EAAC;EAAU;EAAS;CAAY,CAAC;CAC9C,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;CAC1C,WAAW,EAAE,OAAO;CACpB,SAAS,EAAE,OAAO;AACpB,CAAC;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eACA,OACF;AACF"}
@@ -1,8 +1,10 @@
1
- declare function base58btcDecode(str: string): Uint8Array | null;
2
- declare function base58btcEncode(bytes: Uint8Array): string;
3
-
4
- declare const MAX_ED25519_KEY_BODY_LENGTH = 64;
5
- declare function decodeEd25519PublicKeyMultibaseTolerant(mb: string): Uint8Array | null;
6
- declare function encodeEd25519PublicKeyMultibase(rawPubKey: Uint8Array): string;
7
-
8
- export { MAX_ED25519_KEY_BODY_LENGTH, base58btcDecode, base58btcEncode, decodeEd25519PublicKeyMultibaseTolerant, encodeEd25519PublicKeyMultibase };
1
+ //#region src/mcpi/did-key.d.ts
2
+ export declare function base58btcDecode(str: string): Uint8Array | null;
3
+ export declare function base58btcEncode(bytes: Uint8Array): string;
4
+ //#endregion
5
+ //#region src/mcpi/multibase-ed25519.d.ts
6
+ export declare const MAX_ED25519_KEY_BODY_LENGTH = 64;
7
+ export declare function decodeEd25519PublicKeyMultibaseTolerant(mb: string): Uint8Array | null;
8
+ export declare function encodeEd25519PublicKeyMultibase(rawPubKey: Uint8Array): string;
9
+ //#endregion
10
+ //# sourceMappingURL=multibase-ed25519.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multibase-ed25519.d.mts","names":[],"sources":["../../src/mcpi/did-key.ts","../../src/mcpi/multibase-ed25519.ts"],"mappings":";wBAoCgB,gBAAgB,cAAc;wBAyC9B,gBAAgB,OAAO;;;qBCnC1B;wBAgDG,wCAAwC,aAAa;wBA0BrD,gCAAgC,WAAW"}
@@ -1,8 +1,10 @@
1
- declare function base58btcDecode(str: string): Uint8Array | null;
2
- declare function base58btcEncode(bytes: Uint8Array): string;
3
-
4
- declare const MAX_ED25519_KEY_BODY_LENGTH = 64;
5
- declare function decodeEd25519PublicKeyMultibaseTolerant(mb: string): Uint8Array | null;
6
- declare function encodeEd25519PublicKeyMultibase(rawPubKey: Uint8Array): string;
7
-
8
- export { MAX_ED25519_KEY_BODY_LENGTH, base58btcDecode, base58btcEncode, decodeEd25519PublicKeyMultibaseTolerant, encodeEd25519PublicKeyMultibase };
1
+ //#region src/mcpi/did-key.d.ts
2
+ export declare function base58btcDecode(str: string): Uint8Array | null;
3
+ export declare function base58btcEncode(bytes: Uint8Array): string;
4
+ //#endregion
5
+ //#region src/mcpi/multibase-ed25519.d.ts
6
+ export declare const MAX_ED25519_KEY_BODY_LENGTH = 64;
7
+ export declare function decodeEd25519PublicKeyMultibaseTolerant(mb: string): Uint8Array | null;
8
+ export declare function encodeEd25519PublicKeyMultibase(rawPubKey: Uint8Array): string;
9
+ //#endregion
10
+ //# sourceMappingURL=multibase-ed25519.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multibase-ed25519.d.ts","names":[],"sources":["../../src/mcpi/did-key.ts","../../src/mcpi/multibase-ed25519.ts"],"mappings":";wBAoCgB,gBAAgB,cAAc;wBAyC9B,gBAAgB,OAAO;;;qBCnC1B;wBAgDG,wCAAwC,aAAa;wBA0BrD,gCAAgC,WAAW"}
@@ -1,125 +1,201 @@
1
- 'use strict';
2
-
3
- // src/mcpi/did-key.ts
4
- var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
5
- var BASE58_INDEX = (() => {
6
- const idx = {};
7
- for (let i = 0; i < BASE58_ALPHABET.length; i++) idx[BASE58_ALPHABET[i]] = i;
8
- return idx;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ //#region src/mcpi/did-key.ts
3
+ /**
4
+ * did:key (Ed25519 multikey) codec — draft-kya-http-02 / H1.2 (#3245).
5
+ *
6
+ * Format: `did:key:z<base58btc(0xed 0x01 || pubkey32)>`
7
+ * The multicodec prefix `0xed 0x01` identifies `ed25519-pub`; the multibase
8
+ * prefix `z` identifies base58btc. An Ed25519 public key is always 32 bytes,
9
+ * so the decoded multikey is always 34 bytes and the did:key always begins
10
+ * `z6Mk` (a fixed consequence of the `0xed01` prefix).
11
+ *
12
+ * This is a PURE-JS port of the base58btc decoder in
13
+ * `apps/web/workers/gateway/src/detection/did-verifier.ts` (repeated-division
14
+ * algorithm), lifted here so the H1.2 pickup endpoint — and future H2.x TS
15
+ * PEPs — can recover the raw key for `node:crypto` Ed25519 verification with
16
+ * zero crypto/runtime dependencies (it runs identically in Node, Cloudflare
17
+ * Workers, and the browser). The encoder is the inverse, for tests and any
18
+ * caller that emits a `did:key` from raw key bytes.
19
+ */
20
+ const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
21
+ const BASE58_INDEX = (() => {
22
+ const idx = {};
23
+ for (let i = 0; i < 58; i++) idx[BASE58_ALPHABET[i]] = i;
24
+ return idx;
9
25
  })();
26
+ const ED25519_MULTICODEC = [237, 1];
27
+ const ED25519_PUBKEY_LENGTH$1 = 32;
28
+ const ED25519_MULTIKEY_LENGTH$1 = ED25519_MULTICODEC.length + ED25519_PUBKEY_LENGTH$1;
29
+ /**
30
+ * Decode a base58btc string to bytes using the repeated-division algorithm.
31
+ * Returns null if the string contains a character outside the base58btc
32
+ * alphabet. Ported verbatim from the gateway worker's `did-verifier.ts`
33
+ * (kept algorithm-identical to avoid cross-runtime drift).
34
+ */
10
35
  function base58btcDecode(str) {
11
- if (str.length === 0) return new Uint8Array(0);
12
- let zeros = 0;
13
- while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;
14
- const bytes = [0];
15
- for (let i = 0; i < str.length; i++) {
16
- const value = BASE58_INDEX[str[i]];
17
- if (value === void 0) return null;
18
- let carry = value;
19
- for (let j = 0; j < bytes.length; j++) {
20
- carry += bytes[j] * 58;
21
- bytes[j] = carry & 255;
22
- carry >>= 8;
23
- }
24
- while (carry > 0) {
25
- bytes.push(carry & 255);
26
- carry >>= 8;
27
- }
28
- }
29
- let high = bytes.length;
30
- while (high > 0 && bytes[high - 1] === 0) high--;
31
- const out = new Uint8Array(zeros + high);
32
- for (let i = 0; i < high; i++) {
33
- out[zeros + high - 1 - i] = bytes[i];
34
- }
35
- return out;
36
+ if (str.length === 0) return /* @__PURE__ */ new Uint8Array(0);
37
+ let zeros = 0;
38
+ while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;
39
+ const bytes = [0];
40
+ for (let i = 0; i < str.length; i++) {
41
+ const value = BASE58_INDEX[str[i]];
42
+ if (value === void 0) return null;
43
+ let carry = value;
44
+ for (let j = 0; j < bytes.length; j++) {
45
+ carry += bytes[j] * 58;
46
+ bytes[j] = carry & 255;
47
+ carry >>= 8;
48
+ }
49
+ while (carry > 0) {
50
+ bytes.push(carry & 255);
51
+ carry >>= 8;
52
+ }
53
+ }
54
+ let high = bytes.length;
55
+ while (high > 0 && bytes[high - 1] === 0) high--;
56
+ const out = new Uint8Array(zeros + high);
57
+ for (let i = 0; i < high; i++) out[zeros + high - 1 - i] = bytes[i];
58
+ return out;
36
59
  }
60
+ /**
61
+ * Encode bytes to a base58btc string — the exact inverse of
62
+ * {@link base58btcDecode}. Leading zero bytes map to leading `1`s; the value
63
+ * is accumulated as little-endian base58 digits (×256 + byte) and emitted
64
+ * big-endian. The high-order zero sentinel is dropped the same way the decoder
65
+ * drops its trailing zeros, so a single `0x00` byte encodes to `"1"`, not `"11"`.
66
+ */
37
67
  function base58btcEncode(bytes) {
38
- if (bytes.length === 0) return "";
39
- let zeros = 0;
40
- while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
41
- const digits = [0];
42
- for (let i = 0; i < bytes.length; i++) {
43
- let carry = bytes[i];
44
- for (let j = 0; j < digits.length; j++) {
45
- carry += digits[j] * 256;
46
- digits[j] = carry % 58;
47
- carry = Math.floor(carry / 58);
48
- }
49
- while (carry > 0) {
50
- digits.push(carry % 58);
51
- carry = Math.floor(carry / 58);
52
- }
53
- }
54
- let high = digits.length;
55
- while (high > 0 && digits[high - 1] === 0) high--;
56
- let out = BASE58_ALPHABET[0].repeat(zeros);
57
- for (let i = high - 1; i >= 0; i--) {
58
- out += BASE58_ALPHABET[digits[i]];
59
- }
60
- return out;
68
+ if (bytes.length === 0) return "";
69
+ let zeros = 0;
70
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
71
+ const digits = [0];
72
+ for (let i = 0; i < bytes.length; i++) {
73
+ let carry = bytes[i];
74
+ for (let j = 0; j < digits.length; j++) {
75
+ carry += digits[j] * 256;
76
+ digits[j] = carry % 58;
77
+ carry = Math.floor(carry / 58);
78
+ }
79
+ while (carry > 0) {
80
+ digits.push(carry % 58);
81
+ carry = Math.floor(carry / 58);
82
+ }
83
+ }
84
+ let high = digits.length;
85
+ while (high > 0 && digits[high - 1] === 0) high--;
86
+ let out = BASE58_ALPHABET[0].repeat(zeros);
87
+ for (let i = high - 1; i >= 0; i--) out += BASE58_ALPHABET[digits[i]];
88
+ return out;
61
89
  }
62
90
 
63
- // src/mcpi/multibase-ed25519.ts
64
- var ED25519_PUB_MULTICODEC = [237, 1];
65
- var ED25519_PUBKEY_LENGTH2 = 32;
66
- var ED25519_MULTIKEY_LENGTH2 = ED25519_PUB_MULTICODEC.length + ED25519_PUBKEY_LENGTH2;
67
- var MAX_ED25519_KEY_BODY_LENGTH = 64;
91
+ //#endregion
92
+ //#region src/mcpi/multibase-ed25519.ts
93
+ /**
94
+ * Tolerant + canonical multibase codec for Ed25519 public keys used across
95
+ * checkpoint's mcp-i auth surfaces (org DID docs, approver keys, worker
96
+ * signed-agent verification).
97
+ *
98
+ * Lifts two previously-divergent decoders into one shared implementation:
99
+ * - apps/gateway/src/lib/multibase.ts's `decodeEd25519PublicKeyMultibase`
100
+ * accepted ONLY `z` (base58btc) + exactly 34 bytes (multicodec), throwing
101
+ * on anything else.
102
+ * - apps/web/workers/gateway/src/detection/did-verifier.ts's local
103
+ * `decodeMultibase` accepted `z` and `m` (read as base64url, which
104
+ * deviates from the multibase spec where `m` = standard base64, but
105
+ * matches what knowthat.ai's DID generator actually emits), plus 32-byte
106
+ * raw or 34-byte multicodec bodies.
107
+ *
108
+ * Neither accepted `u`, the actual multibase-spec prefix for base64url.
109
+ * `decodeEd25519PublicKeyMultibaseTolerant` accepts z/m/u and both body
110
+ * shapes, and — unlike the strict gateway decoder — never throws; callers
111
+ * treat `null` as "not a decodable Ed25519 key" and route it into their
112
+ * existing fail-closed paths.
113
+ *
114
+ * Reuses the base58btc codec from `./did-key` rather than adding a third
115
+ * copy (a THIRD near-identical implementation was the state before this
116
+ * module existed).
117
+ */
118
+ const ED25519_PUB_MULTICODEC = [237, 1];
119
+ const ED25519_PUBKEY_LENGTH = 32;
120
+ const ED25519_MULTIKEY_LENGTH = ED25519_PUB_MULTICODEC.length + ED25519_PUBKEY_LENGTH;
121
+ /**
122
+ * Length ceiling applied BEFORE decoding. The longest legitimate body is a
123
+ * 34-byte multicodec key: 47 chars in base58btc, 48 in padded base64. Bodies
124
+ * past this cap are rejected by the length check anyway — the point is to
125
+ * reject them before `base58btcDecode`'s O(n^2) repeated division runs, since
126
+ * `publicKeyMultibase` / `publicKeyBase58` arrive from DID documents fetched
127
+ * over the network and a hostile document could otherwise burn seconds of
128
+ * event-loop (gateway) or isolate (worker) CPU per key. Mirrors the same guard
129
+ * on `decodeDidKeyEd25519` in ./did-key.
130
+ */
131
+ const MAX_ED25519_KEY_BODY_LENGTH = 64;
132
+ /**
133
+ * Decode a base64 body to bytes, accepting both the url-safe (`-`, `_`) and
134
+ * standard (`+`, `/`) alphabets and tolerating the presence or absence of
135
+ * `=` padding. Returns null on any malformed input — never throws.
136
+ */
68
137
  function base64AnyToBytes(body) {
69
- if (body.length === 0) return null;
70
- let normalized = body.replace(/-/g, "+").replace(/_/g, "/");
71
- const remainder = normalized.length % 4;
72
- if (remainder === 1) return null;
73
- if (remainder === 2) normalized += "==";
74
- else if (remainder === 3) normalized += "=";
75
- if (!/^[A-Za-z0-9+/]+={0,2}$/.test(normalized)) return null;
76
- try {
77
- const bin = atob(normalized);
78
- const out = new Uint8Array(bin.length);
79
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
80
- return out;
81
- } catch {
82
- return null;
83
- }
138
+ if (body.length === 0) return null;
139
+ let normalized = body.replace(/-/g, "+").replace(/_/g, "/");
140
+ const remainder = normalized.length % 4;
141
+ if (remainder === 1) return null;
142
+ if (remainder === 2) normalized += "==";
143
+ else if (remainder === 3) normalized += "=";
144
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(normalized)) return null;
145
+ try {
146
+ const bin = atob(normalized);
147
+ const out = new Uint8Array(bin.length);
148
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
149
+ return out;
150
+ } catch {
151
+ return null;
152
+ }
84
153
  }
154
+ /** Strip the ed25519-pub multicodec prefix if present; validate the length either way. */
85
155
  function toRawEd25519Key(decoded) {
86
- if (decoded.length === ED25519_PUBKEY_LENGTH2) return decoded;
87
- if (decoded.length === ED25519_MULTIKEY_LENGTH2 && decoded[0] === ED25519_PUB_MULTICODEC[0] && decoded[1] === ED25519_PUB_MULTICODEC[1]) {
88
- return decoded.slice(ED25519_PUB_MULTICODEC.length);
89
- }
90
- return null;
156
+ if (decoded.length === ED25519_PUBKEY_LENGTH) return decoded;
157
+ if (decoded.length === ED25519_MULTIKEY_LENGTH && decoded[0] === ED25519_PUB_MULTICODEC[0] && decoded[1] === ED25519_PUB_MULTICODEC[1]) return decoded.slice(ED25519_PUB_MULTICODEC.length);
158
+ return null;
91
159
  }
160
+ /**
161
+ * Decode a `publicKeyMultibase` value to a raw 32-byte Ed25519 public key.
162
+ * Accepts multibase prefixes `z` (base58btc), `m` (base64url — the value
163
+ * checkpoint's own DID documents emit, though not per the multibase spec),
164
+ * and `u` (base64url per the multibase spec). The decoded body may be 32
165
+ * raw key bytes or 34 bytes prefixed with the ed25519-pub multicodec
166
+ * (`0xed 0x01`), which is stripped. Returns null for any other prefix,
167
+ * length, or invalid encoding — never throws.
168
+ */
92
169
  function decodeEd25519PublicKeyMultibaseTolerant(mb) {
93
- if (typeof mb !== "string" || mb.length < 2) return null;
94
- const prefix = mb[0];
95
- const body = mb.slice(1);
96
- if (body.length > MAX_ED25519_KEY_BODY_LENGTH) return null;
97
- let decoded;
98
- if (prefix === "z") {
99
- decoded = base58btcDecode(body);
100
- } else if (prefix === "m" || prefix === "u") {
101
- decoded = base64AnyToBytes(body);
102
- } else {
103
- return null;
104
- }
105
- if (!decoded) return null;
106
- return toRawEd25519Key(decoded);
170
+ if (typeof mb !== "string" || mb.length < 2) return null;
171
+ const prefix = mb[0];
172
+ const body = mb.slice(1);
173
+ if (body.length > 64) return null;
174
+ let decoded;
175
+ if (prefix === "z") decoded = base58btcDecode(body);
176
+ else if (prefix === "m" || prefix === "u") decoded = base64AnyToBytes(body);
177
+ else return null;
178
+ if (!decoded) return null;
179
+ return toRawEd25519Key(decoded);
107
180
  }
181
+ /**
182
+ * Encode a raw 32-byte Ed25519 public key as a canonical `z`-prefixed,
183
+ * ed25519-pub-multicodec multibase string. Throws if the key is not
184
+ * exactly 32 bytes — an emitter handing in the wrong length is a
185
+ * programming error, not untrusted input (unlike the tolerant decoder).
186
+ */
108
187
  function encodeEd25519PublicKeyMultibase(rawPubKey) {
109
- if (rawPubKey.length !== ED25519_PUBKEY_LENGTH2) {
110
- throw new Error(
111
- `Ed25519 public key must be ${ED25519_PUBKEY_LENGTH2} bytes, got ${rawPubKey.length}`
112
- );
113
- }
114
- const prefixed = new Uint8Array(ED25519_MULTIKEY_LENGTH2);
115
- prefixed[0] = ED25519_PUB_MULTICODEC[0];
116
- prefixed[1] = ED25519_PUB_MULTICODEC[1];
117
- prefixed.set(rawPubKey, ED25519_PUB_MULTICODEC.length);
118
- return "z" + base58btcEncode(prefixed);
188
+ if (rawPubKey.length !== ED25519_PUBKEY_LENGTH) throw new Error(`Ed25519 public key must be ${ED25519_PUBKEY_LENGTH} bytes, got ${rawPubKey.length}`);
189
+ const prefixed = new Uint8Array(ED25519_MULTIKEY_LENGTH);
190
+ prefixed[0] = ED25519_PUB_MULTICODEC[0];
191
+ prefixed[1] = ED25519_PUB_MULTICODEC[1];
192
+ prefixed.set(rawPubKey, ED25519_PUB_MULTICODEC.length);
193
+ return "z" + base58btcEncode(prefixed);
119
194
  }
120
195
 
196
+ //#endregion
121
197
  exports.MAX_ED25519_KEY_BODY_LENGTH = MAX_ED25519_KEY_BODY_LENGTH;
122
198
  exports.base58btcDecode = base58btcDecode;
123
199
  exports.base58btcEncode = base58btcEncode;
124
200
  exports.decodeEd25519PublicKeyMultibaseTolerant = decodeEd25519PublicKeyMultibaseTolerant;
125
- exports.encodeEd25519PublicKeyMultibase = encodeEd25519PublicKeyMultibase;
201
+ exports.encodeEd25519PublicKeyMultibase = encodeEd25519PublicKeyMultibase;