@keetanetwork/anchor 0.0.112 → 0.0.114

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 (73) hide show
  1. package/lib/http-server/common.d.ts +3 -2
  2. package/lib/http-server/common.d.ts.map +1 -1
  3. package/lib/http-server/common.js +9 -13
  4. package/lib/http-server/common.js.map +1 -1
  5. package/lib/http-server/index.d.ts +31 -1
  6. package/lib/http-server/index.d.ts.map +1 -1
  7. package/lib/http-server/index.js +93 -36
  8. package/lib/http-server/index.js.map +1 -1
  9. package/lib/http-server/replay-guard-postgres.d.ts +41 -0
  10. package/lib/http-server/replay-guard-postgres.d.ts.map +1 -0
  11. package/lib/http-server/replay-guard-postgres.js +113 -0
  12. package/lib/http-server/replay-guard-postgres.js.map +1 -0
  13. package/lib/http-server/replay-guard-redis.d.ts +29 -0
  14. package/lib/http-server/replay-guard-redis.d.ts.map +1 -0
  15. package/lib/http-server/replay-guard-redis.js +23 -0
  16. package/lib/http-server/replay-guard-redis.js.map +1 -0
  17. package/lib/http-server/replay-guard.d.ts +29 -0
  18. package/lib/http-server/replay-guard.d.ts.map +1 -0
  19. package/lib/http-server/replay-guard.js +58 -0
  20. package/lib/http-server/replay-guard.js.map +1 -0
  21. package/lib/http-server/request-signing.d.ts +70 -0
  22. package/lib/http-server/request-signing.d.ts.map +1 -0
  23. package/lib/http-server/request-signing.js +179 -0
  24. package/lib/http-server/request-signing.js.map +1 -0
  25. package/lib/utils/signing.d.ts +6 -1
  26. package/lib/utils/signing.d.ts.map +1 -1
  27. package/lib/utils/signing.js +11 -6
  28. package/lib/utils/signing.js.map +1 -1
  29. package/npm-shrinkwrap.json +2 -2
  30. package/package.json +1 -1
  31. package/services/asset-movement/client.d.ts +5 -4
  32. package/services/asset-movement/client.d.ts.map +1 -1
  33. package/services/asset-movement/client.js +27 -13
  34. package/services/asset-movement/client.js.map +1 -1
  35. package/services/asset-movement/common.generated.js +1 -1
  36. package/services/asset-movement/common.server.generated.js +50 -50
  37. package/services/asset-movement/server.d.ts.map +1 -1
  38. package/services/asset-movement/server.js +22 -4
  39. package/services/asset-movement/server.js.map +1 -1
  40. package/services/fx/server.d.ts.map +1 -1
  41. package/services/fx/server.js +45 -38
  42. package/services/fx/server.js.map +1 -1
  43. package/services/kyc/client.d.ts +8 -3
  44. package/services/kyc/client.d.ts.map +1 -1
  45. package/services/kyc/client.js +24 -23
  46. package/services/kyc/client.js.map +1 -1
  47. package/services/kyc/common.d.ts +0 -7
  48. package/services/kyc/common.d.ts.map +1 -1
  49. package/services/kyc/common.js +0 -8
  50. package/services/kyc/common.js.map +1 -1
  51. package/services/kyc/server.d.ts +3 -1
  52. package/services/kyc/server.d.ts.map +1 -1
  53. package/services/kyc/server.js +15 -33
  54. package/services/kyc/server.js.map +1 -1
  55. package/services/notification/client.d.ts.map +1 -1
  56. package/services/notification/client.js +39 -33
  57. package/services/notification/client.js.map +1 -1
  58. package/services/notification/server.js +10 -10
  59. package/services/notification/server.js.map +1 -1
  60. package/services/storage/client.d.ts +3 -0
  61. package/services/storage/client.d.ts.map +1 -1
  62. package/services/storage/client.js +41 -11
  63. package/services/storage/client.js.map +1 -1
  64. package/services/storage/server.d.ts.map +1 -1
  65. package/services/storage/server.js +12 -11
  66. package/services/storage/server.js.map +1 -1
  67. package/services/username/client.d.ts +12 -1
  68. package/services/username/client.d.ts.map +1 -1
  69. package/services/username/client.js +36 -30
  70. package/services/username/client.js.map +1 -1
  71. package/services/username/server.d.ts.map +1 -1
  72. package/services/username/server.js +7 -6
  73. package/services/username/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/lib/http-server/index.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,OAAO,EACN,gBAAgB,EAChB,oBAAoB,EACpB,MAAM,aAAa,CAAC;AAOrB,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAC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Q,GAAG,GAAG,CAAC;QACtB,MAAM,CAAC,MAAM,GAAG,EAAE,CAAC;QAEnB,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;QAEjC,OAAM,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC;IAED,IAAI,GAAG,CAAC,KAA4D;QACnE,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC;IACnB,CAAC;IAED,CAAC,MAAM,CAAC,YAAY,CAAC;QACpB,OAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IACrB,CAAC;CACD","sourcesContent":["import * as http from 'http';\n\nimport {\n\tKeetaAnchorError,\n\tKeetaAnchorUserError\n} from '../error.js';\nimport type { JSONSerializable } from '../utils/json.js';\nimport type { Logger, LogLevel } from '../log/index.js';\nimport type {\n\tCertificateChainConfig,\n\tResolvedCertificateChainRequirement\n} from '../utils/certificate-network.js';\nimport { Log } from '../log/index.js';\nimport { createAssert } from 'typia';\nimport { assertNever } from '../utils/never.js';\nimport { resolveCertificateChainConfig } from '../utils/certificate-network.js';\nimport { Buffer } from '../utils/buffer.js';\n\nexport const AssertHTTPErrorData: (input: unknown) => { error: string; statusCode?: number; contentType?: string; } = createAssert<{ error: string; statusCode?: number; contentType?: string; }>();\n\n/**\n * The maximum size of a request (128MiB)\n */\nconst MAX_REQUEST_SIZE = 128 * (1024 ** 2);\n\ntype RouteHandlerMethod<BodyDataType = JSONSerializable | undefined> = (urlParams: Map<string, string>, postData: BodyDataType, requestHeaders: http.IncomingHttpHeaders, requestUrl: URL) => Promise<{ output: string | Buffer; statusCode?: number; contentType?: string; headers?: { [headerName: string]: string; }; }>;\ntype RouteHandlerWithConfig = {\n\tbodyType: 'raw';\n\tmaxBodySize?: number;\n\thandler: RouteHandlerMethod<Buffer>;\n} | {\n\tbodyType: 'parsed';\n\tmaxBodySize?: number;\n\thandler: RouteHandlerMethod;\n} | {\n\tbodyType: 'none';\n\thandler: RouteHandlerMethod<undefined>;\n};\ntype RouteHandler = RouteHandlerMethod | RouteHandlerWithConfig;\nexport type Routes = { [route: string]: RouteHandler };\nexport type RoutesWithConfigs = { [route: string]: RouteHandlerWithConfig };\n\nexport interface KeetaAnchorHTTPServerConfig {\n\t/**\n\t * Identifier for the server instance -- if one is not given\n\t * a random one will be generated.\n\t */\n\tid?: string;\n\n\t/**\n\t * The port for the HTTP server to listen on (default is an ephemeral port).\n\t */\n\tport?: number;\n\n\t/**\n\t * Enable debug logging\n\t */\n\tlogger?: Logger | undefined;\n\t/**\n\t * The URL for the server. By default, this will be generated based on\n\t * the port and will use \"localhost\" as the hostname, but it can be\n\t * overridden by setting this to a string, URL, or function that\n\t * generates the URL\n\t */\n\turl?: undefined | string | URL | ((object: KeetaNetAnchorHTTPServer) => string) | {\n\t\thostname?: string;\n\t\tport?: number;\n\t\tprotocol?: string;\n\t};\n\n\t/**\n\t * Optional on-chain cert-chain gate. When set, authenticated callers\n\t * MUST have a published cert chaining to one of `trustedIssuers`.\n\t */\n\trequireCertificateChain?: CertificateChainConfig | undefined;\n};\n\nexport abstract class KeetaNetAnchorHTTPServer<ConfigType extends KeetaAnchorHTTPServerConfig = KeetaAnchorHTTPServerConfig> implements Required<KeetaAnchorHTTPServerConfig> {\n\treadonly port: NonNullable<KeetaAnchorHTTPServerConfig['port']>;\n\treadonly logger: NonNullable<KeetaAnchorHTTPServerConfig['logger']>;\n\treadonly id: NonNullable<KeetaAnchorHTTPServerConfig['id']>;\n\t/**\n\t * Resolved cert-chain requirement, or `undefined` when disabled.\n\t * @see {@link requireCertificateChain}.\n\t */\n\tprotected readonly resolvedCertificateChainRequirement: ResolvedCertificateChainRequirement | undefined;\n\t#serverPromise?: Promise<void>;\n\t#server?: http.Server;\n\t#urlParts: undefined | { hostname?: string; port?: number; protocol?: string; };\n\t#url: undefined | string | URL | ((object: this) => string);\n\treadonly #config: ConfigType;\n\n\tconstructor(config: ConfigType) {\n\t\tthis.#config = { ...config };\n\t\tthis.port = config.port ?? 0;\n\t\tthis.id = config.id ?? crypto.randomUUID();\n\t\tthis.logger = config.logger ?? Log.Legacy('ANCHOR');\n\t\tthis.resolvedCertificateChainRequirement = resolveCertificateChainConfig(config.requireCertificateChain);\n\n\t\tif (config.url !== undefined) {\n\t\t\tif (config.url instanceof URL || typeof config.url === 'string') {\n\t\t\t\tthis.#url = config.url;\n\t\t\t\tthis.#urlParts = undefined;\n\t\t\t} else if (typeof config.url === 'function') {\n\t\t\t\t/**\n\t\t\t\t * The parameter for the call back is typed as\n\t\t\t\t * `this`, which means any subclass is typed\n\t\t\t\t * but the interface can't identify that --\n\t\t\t\t * instead it types it as the base class\n\t\t\t\t * (KeetaNetAnchorHTTPServer), which means it\n\t\t\t\t * can't be assigned to the type of `#url`\n\t\t\t\t * without overriding the type check. However,\n\t\t\t\t * we know that `this` will be at least\n\t\t\t\t * compatible with the base class.\n\t\t\t\t */\n\t\t\t\t// @ts-ignore\n\t\t\t\tthis.#url = config.url;\n\t\t\t\tthis.#urlParts = undefined;\n\t\t\t} else {\n\t\t\t\tthis.#url = undefined;\n\t\t\t\tthis.#urlParts = config.url;\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected abstract initRoutes(config: ConfigType): Promise<Routes>;\n\n\t/**\n\t * Public view of the cert-chain config, or `undefined` when disabled.\n\t */\n\tget requireCertificateChain(): CertificateChainConfig | undefined {\n\t\treturn(this.resolvedCertificateChainRequirement);\n\t}\n\n\t/**\n\t * Trusted-issuer DNs metadata. Is `undefined` when the gate is not configured.\n\t */\n\tprotected acceptedIssuerDNs(): { name: string; value: string }[][] | undefined {\n\t\tconst requirement = this.resolvedCertificateChainRequirement;\n\t\tif (requirement === undefined) {\n\t\t\treturn(undefined);\n\t\t}\n\n\t\treturn(requirement.acceptedIssuerDNs);\n\t}\n\n\tprivate static routeMatch(requestURL: URL, routeURL: URL): ({ match: true; params: Map<string, string>; wildcard?: { prefixLength: number }} | { match: false }) {\n\t\tconst requestURLPaths = requestURL.pathname.split('/');\n\t\tconst routeURLPaths = routeURL.pathname.split('/');\n\n\t\t// Check if route ends with wildcard /**\n\t\tconst isWildcard = routeURLPaths.length > 0 && routeURLPaths[routeURLPaths.length - 1] === '**';\n\t\tif (isWildcard) {\n\t\t\t// For wildcard routes, request must have more segments than route prefix (minus the **)\n\t\t\t// This ensures at least one segment is captured by the wildcard\n\t\t\tconst prefixLength = routeURLPaths.length - 1;\n\t\t\tif (requestURLPaths.length <= prefixLength) {\n\t\t\t\treturn({ match: false });\n\t\t\t}\n\n\t\t\t// Check that prefix segments match\n\t\t\tconst params = new Map<string, string>();\n\t\t\tfor (let partIndex = 0; partIndex < prefixLength; partIndex++) {\n\t\t\t\tconst requestPath = requestURLPaths[partIndex];\n\n\t\t\t\tconst routePath = routeURLPaths[partIndex];\n\t\t\t\tif (routePath === undefined || requestPath === undefined) {\n\t\t\t\t\treturn({ match: false });\n\t\t\t\t}\n\n\t\t\t\tif (routePath.startsWith(':')) {\n\t\t\t\t\tparams.set(routePath.slice(1), requestPath);\n\t\t\t\t} else if (requestPath !== routePath) {\n\t\t\t\t\treturn({ match: false });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Capture the remainder as the wildcard param\n\t\t\t// Filter empty segments to handle trailing slashes correctly\n\t\t\tconst remainder = requestURLPaths.slice(prefixLength)\n\t\t\t\t.filter(function(s) {\n\t\t\t\t\treturn(s !== '');\n\t\t\t\t})\n\t\t\t\t.join('/');\n\n\t\t\tif (remainder === '') {\n\t\t\t\t// Reject if wildcard would capture nothing\n\t\t\t\treturn({ match: false });\n\t\t\t}\n\n\t\t\tparams.set('**', remainder);\n\n\t\t\treturn({ match: true, params: params, wildcard: { prefixLength }});\n\t\t}\n\n\t\t// Non-wildcard: require exact segment count\n\t\tif (requestURLPaths.length !== routeURLPaths.length) {\n\t\t\treturn({ match: false });\n\t\t}\n\n\t\tconst params = new Map<string, string>();\n\t\tfor (let partIndex = 0; partIndex < requestURLPaths.length; partIndex++) {\n\t\t\tconst requestPath = requestURLPaths[partIndex];\n\t\t\tconst routePath = routeURLPaths[partIndex];\n\n\t\t\tif (routePath === undefined || requestPath === undefined) {\n\t\t\t\treturn({ match: false });\n\t\t\t}\n\n\t\t\tif (routePath.startsWith(':')) {\n\t\t\t\tparams.set(routePath.slice(1), requestPath);\n\t\t\t} else if (requestPath !== routePath) {\n\t\t\t\treturn({ match: false });\n\t\t\t}\n\t\t}\n\n\t\treturn({ match: true, params: params });\n\t}\n\n\tprivate static routeFind(method: string, requestURL: URL, routes: Routes): { route: Routes[keyof Routes]; params: Map<string, string> } | null {\n\t\tlet wildcardMatch: { route: Routes[keyof Routes]; params: Map<string, string> } | null = null;\n\t\tlet wildcardPrefixLength = -1;\n\n\t\tfor (const routeKey in routes) {\n\t\t\tconst route = routes[routeKey];\n\t\t\tif (route === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst [routeMethod, ...routePathParts] = routeKey.split(' ');\n\t\t\tconst routePath = `/${routePathParts.join(' ')}`.replace(/^\\/+/, '/');\n\n\t\t\tif (method !== routeMethod) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst routeURL = new URL(routePath, 'http://localhost');\n\t\t\tconst matchResult = this.routeMatch(requestURL, routeURL);\n\t\t\tif (matchResult.match) {\n\t\t\t\t// Exact matches take priority over wildcard matches\n\t\t\t\tif (matchResult.wildcard === undefined) {\n\t\t\t\t\treturn({\n\t\t\t\t\t\troute: route,\n\t\t\t\t\t\tparams: matchResult.params\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Keep the most specific wildcard (longest prefix wins)\n\t\t\t\tif (matchResult.wildcard.prefixLength > wildcardPrefixLength) {\n\t\t\t\t\twildcardPrefixLength = matchResult.wildcard.prefixLength;\n\t\t\t\t\twildcardMatch = {\n\t\t\t\t\t\troute: route,\n\t\t\t\t\t\tparams: matchResult.params\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Return most specific wildcard match if no exact match found\n\t\treturn(wildcardMatch);\n\t}\n\n\tprivate static addCORS(routes: Routes): RoutesWithConfigs {\n\t\tconst newRoutes: RoutesWithConfigs = {};\n\n\t\tconst validMethods = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']);\n\n\t\tconst methodsByPath: { [key: string]: Set<string>; } = {};\n\t\tfor (const routeKey in routes) {\n\t\t\tconst methodAndPath = routeKey.split(' ');\n\t\t\tconst method = methodAndPath[0];\n\t\t\tconst path = methodAndPath.slice(1).join(' ');\n\n\t\t\tif (method === undefined || path === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!validMethods.has(method)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!(path in methodsByPath)) {\n\t\t\t\tmethodsByPath[path] = new Set<string>();\n\t\t\t}\n\n\t\t\tif (methodsByPath[path] === undefined) {\n\t\t\t\tthrow(new Error(`internal error: methodsByPath missing path for ${path}`));\n\t\t\t}\n\n\t\t\tmethodsByPath[path].add(method);\n\t\t}\n\n\t\tconst seenPaths = new Set<string>();\n\t\tfor (const routeKey in routes) {\n\t\t\tconst methodAndPath = routeKey.split(' ');\n\t\t\tconst method = methodAndPath[0];\n\t\t\tconst path = methodAndPath.slice(1).join(' ');\n\n\t\t\tconst routeHandler = routes[routeKey];\n\t\t\tif (routeHandler === undefined) {\n\t\t\t\tthrow(new Error(`internal error: routeHandler missing for routeKey ${routeKey}`));\n\t\t\t}\n\n\t\t\tlet newRoute: RouteHandlerWithConfig;\n\n\t\t\tif (typeof routeHandler === 'function') {\n\t\t\t\tnewRoute = {\n\t\t\t\t\tbodyType: 'parsed',\n\t\t\t\t\thandler: routeHandler\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tnewRoute = routeHandler;\n\t\t\t}\n\n\t\t\tif (method !== 'ERROR') {\n\t\t\t\tif (method === undefined || path === undefined) {\n\t\t\t\t\tnewRoutes[routeKey] = newRoute;\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (!validMethods.has(method)) {\n\t\t\t\t\tnewRoutes[routeKey] = newRoute;\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst validMethodsForPath = methodsByPath[path];\n\n\t\t\tlet validMethodsForPathParts: string[] = [];\n\t\t\tif (validMethodsForPath !== undefined) {\n\t\t\t\tvalidMethodsForPath.add('OPTIONS');\n\t\t\t\tvalidMethodsForPathParts = Array.from(validMethodsForPath);\n\t\t\t} else {\n\t\t\t\tvalidMethodsForPathParts = [...Array.from(validMethods), 'OPTIONS'];\n\t\t\t}\n\n\t\t\tnewRoutes[routeKey] = {\n\t\t\t\t...newRoute,\n\t\t\t\tasync handler(...args: Parameters<RouteHandlerMethod<unknown>>) {\n\t\t\t\t\t// This is typed properly, but TS can't infer it here\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tconst retval = await newRoute.handler(...args);\n\n\t\t\t\t\t/* Add CORS headers to the response for the original route handler */\n\t\t\t\t\tif (retval.contentType === 'application/json' || retval.contentType === undefined) {\n\t\t\t\t\t\tif (!('headers' in retval) || retval.headers === undefined) {\n\t\t\t\t\t\t\tretval.headers = {};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretval.headers['Access-Control-Allow-Origin'] = '*';\n\t\t\t\t\t}\n\n\t\t\t\t\treturn(retval);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tif (!seenPaths.has(path) && path !== '' && path !== undefined) {\n\t\t\t\tconst corsRouteKey = `OPTIONS ${path}`;\n\n\t\t\t\tnewRoutes[corsRouteKey] = {\n\t\t\t\t\tbodyType: 'none',\n\t\t\t\t\tasync handler() {\n\t\t\t\t\t\treturn({\n\t\t\t\t\t\t\toutput: '',\n\t\t\t\t\t\t\tstatusCode: 204,\n\t\t\t\t\t\t\tcontentType: 'text/plain',\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\t'Access-Control-Allow-Origin': '*',\n\t\t\t\t\t\t\t\t'Access-Control-Allow-Methods': validMethodsForPathParts.join(', '),\n\t\t\t\t\t\t\t\t'Access-Control-Allow-Headers': 'Content-Type',\n\t\t\t\t\t\t\t\t'Access-Control-Max-Age': '86400'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tseenPaths.add(path);\n\t\t\t}\n\t\t}\n\n\t\treturn(newRoutes);\n\t}\n\n\tprivate async main(onSetPort?: (port: number) => void): Promise<void> {\n\t\tthis.logger?.debug('KeetaAnchorHTTP.Server', 'Starting HTTP server...');\n\n\t\tconst port = this.port;\n\n\t\tconst routes = KeetaNetAnchorHTTPServer.addCORS({\n\t\t\tERROR: async function(_ignore_params, postData) {\n\t\t\t\tconst errorInfo = AssertHTTPErrorData(postData);\n\n\t\t\t\tconst retval = {\n\t\t\t\t\toutput: errorInfo.error,\n\t\t\t\t\tstatusCode: errorInfo.statusCode ?? 400,\n\t\t\t\t\tcontentType: errorInfo.contentType ?? 'text/plain'\n\t\t\t\t};\n\n\t\t\t\treturn(retval);\n\t\t\t},\n\t\t\t...(await this.initRoutes(this.#config))\n\t\t});\n\n\t\tconst server = new http.Server(async (request, response) => {\n\t\t\tconst forwardedProtoHeader = request.headers['x-forwarded-proto'];\n\t\t\tlet forwardedProto: string | undefined;\n\t\t\tif (Array.isArray(forwardedProtoHeader)) {\n\t\t\t\tforwardedProto = forwardedProtoHeader[0];\n\t\t\t} else {\n\t\t\t\tforwardedProto = forwardedProtoHeader;\n\t\t\t}\n\t\t\tforwardedProto = forwardedProto?.split(',')[0]?.trim();\n\n\t\t\tlet protocol: string;\n\t\t\tif (forwardedProto !== undefined && forwardedProto !== '') {\n\t\t\t\tprotocol = forwardedProto;\n\t\t\t} else if ('encrypted' in request.socket && request.socket.encrypted === true) {\n\t\t\t\tprotocol = 'https';\n\t\t\t} else {\n\t\t\t\tprotocol = 'http';\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Get the Base URL from the request Host header (if\n\t\t\t * available) or default to localhost. This is used\n\t\t\t * to construct the full URL for routing.\n\t\t\t */\n\t\t\tconst inputURLBaseRaw = new URL(`${protocol}://${request.headers.host ?? 'localhost'}`);\n\t\t\tconst inputURLBase = inputURLBaseRaw.protocol + '//' + inputURLBaseRaw.host;\n\n\t\t\t/*\n\t\t\t * Normalize the input URL by stripping leading slashes and\n\t\t\t * combining it with the base URL to get the full URL for routing.\n\t\t\t */\n\t\t\tconst inputURLRaw = (request.url ?? '/').replace(/^\\/+/, '/');\n\t\t\tconst inputURLObject = new URL(inputURLRaw, 'http://localhost');\n\t\t\tconst inputURL = inputURLObject.pathname + (function() {\n\t\t\t\tif (inputURLObject.search === '') {\n\t\t\t\t\treturn('');\n\t\t\t\t}\n\n\t\t\t\treturn('?' + inputURLObject.searchParams.toString());\n\t\t\t})();\n\t\t\tconst url = new URL(inputURL, inputURLBase);\n\t\t\tconst method = request.method ?? 'GET';\n\n\t\t\t/*\n\t\t\t * Finalize the response by syncing the logger and ending\n\t\t\t * the response.\n\t\t\t */\n\t\t\tconst responseFinalize = async () => {\n\t\t\t\tif ('sync' in this.logger && typeof this.logger.sync === 'function') {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.logger.sync();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* ignore errors */\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresponse.end();\n\t\t\t};\n\n\t\t\t/*\n\t\t\t * If the request is malformed, reject it immediately\n\t\t\t */\n\t\t\tif (inputURLRaw.at(0) !== '/') {\n\t\t\t\tresponse.statusCode = 400;\n\t\t\t\tresponse.setHeader('Content-Type', 'text/plain');\n\t\t\t\tresponse.write('Bad Request');\n\t\t\t\tawait responseFinalize();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Lookup the route based on the request\n\t\t\t */\n\t\t\tconst requestedRouteAndParams = KeetaNetAnchorHTTPServer.routeFind(method, url, routes);\n\t\t\tif (requestedRouteAndParams === null) {\n\t\t\t\tresponse.statusCode = 404;\n\t\t\t\tresponse.setHeader('Content-Type', 'text/plain');\n\t\t\t\tresponse.write('Not Found');\n\t\t\t\tawait responseFinalize();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Extract the route handler and the parameters from\n\t\t\t * the request\n\t\t\t */\n\t\t\tconst { route, params } = requestedRouteAndParams;\n\n\t\t\t/**\n\t\t\t * Attempt to run the route, catch any errors\n\t\t\t */\n\t\t\tlet result: Awaited<ReturnType<RouteHandlerMethod>> | undefined = undefined;\n\t\t\tlet generatedResult = false;\n\t\t\ttry {\n\t\t\t\tif (!request.method) {\n\t\t\t\t\tthrow(new Error('internal error: No request method'));\n\t\t\t\t}\n\n\t\t\t\tlet bodyData: JSONSerializable | Buffer | undefined;\n\n\t\t\t\tconst shouldCheckBody = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(request.method);\n\n\t\t\t\tif (typeof route === 'function') {\n\t\t\t\t\tthrow(new Error('internal error: Route handler missing body type configuration, should have been added in addCORS'));\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * If POST'ing, PUT'ing, or PATCH'ing, read and parse the request body\n\t\t\t\t */\n\t\t\t\tif (shouldCheckBody && route.bodyType !== 'none') {\n\t\t\t\t\tconst bodySizeLimit = route.maxBodySize ?? MAX_REQUEST_SIZE;\n\n\t\t\t\t\t// Early rejection based on Content-Length header\n\t\t\t\t\tconst contentLength = request.headers['content-length'];\n\t\t\t\t\tif (contentLength !== undefined) {\n\t\t\t\t\t\tconst declaredSize = parseInt(contentLength, 10);\n\t\t\t\t\t\tif (!isNaN(declaredSize) && declaredSize > bodySizeLimit) {\n\t\t\t\t\t\t\trequest.resume();\n\n\t\t\t\t\t\t\tresponse.statusCode = 413;\n\t\t\t\t\t\t\tresponse.setHeader('Content-Type', 'text/plain');\n\t\t\t\t\t\t\tresponse.write('Payload Too Large');\n\n\t\t\t\t\t\t\tawait responseFinalize();\n\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst data = await request.map(function(chunk) {\n\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\t\t\t\treturn(Buffer.from(chunk));\n\t\t\t\t\t}).reduce(function(prev, curr) {\n\t\t\t\t\t\tif (prev.length > bodySizeLimit) {\n\t\t\t\t\t\t\tthrow(new Error('Request too large'));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!Buffer.isBuffer(curr)) {\n\t\t\t\t\t\t\tthrow(new Error(`internal error: Current item is not a buffer -- ${typeof curr}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn(Buffer.concat([prev, curr]));\n\t\t\t\t\t}, Buffer.from(''));\n\n\t\t\t\t\tif (route.bodyType === 'raw') {\n\t\t\t\t\t\tbodyData = data;\n\t\t\t\t\t} else if (route.bodyType === 'parsed' && request.headers['content-type'] === 'application/json') {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\t\t\t\t\tbodyData = JSON.parse(data.toString('utf-8'));\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tthrow(new Error('Invalid JSON data'));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (data.length > 0) {\n\t\t\t\t\t\tthrow(new KeetaAnchorUserError('Unsupported content type'));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * Call the route handler\n\t\t\t\t */\n\t\t\t\t// @ts-ignore\n\t\t\t\tresult = await route.handler(params, bodyData, request.headers, url);\n\n\t\t\t\tgeneratedResult = true;\n\t\t\t} catch (err) {\n\t\t\t\tlet logLevel: Lowercase<LogLevel> = 'error';\n\t\t\t\tif (KeetaAnchorError.isInstance(err)) {\n\t\t\t\t\t/*\n\t\t\t\t\t * We're able to safely cast this here because the cast\n\t\t\t\t\t * duplicates the logic.\n\t\t\t\t\t */\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n\t\t\t\t\tlogLevel = err.logLevel.toLowerCase() as Lowercase<typeof err.logLevel>;\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * If an error occurs, log it and return an error page\n\t\t\t\t */\n\t\t\t\tthis.logger?.[logLevel]('KeetaAnchorHTTP.Server', err);\n\n\t\t\t\t/**\n\t\t\t\t * If it is a user error, provide a user-friendly error page\n\t\t\t\t */\n\t\t\t\tconst errorHandlerRoute = routes['ERROR'];\n\t\t\t\tif (errorHandlerRoute !== undefined) {\n\t\t\t\t\tlet errBody;\n\t\t\t\t\tif (KeetaAnchorError.isInstance(err) && err['userError']) {\n\t\t\t\t\t\terrBody = err.asErrorResponse('application/json');\n\t\t\t\t\t} else {\n\t\t\t\t\t\terrBody = {\n\t\t\t\t\t\t\terror: JSON.stringify({ ok: false, error: 'Internal Server Error' }),\n\t\t\t\t\t\t\tstatusCode: 500,\n\t\t\t\t\t\t\tcontentType: 'application/json'\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tresult = await errorHandlerRoute.handler(new Map(), errBody, request.headers, url);\n\t\t\t\t\tgeneratedResult = true;\n\t\t\t\t}\n\n\t\t\t\tif (!generatedResult) {\n\t\t\t\t\t/**\n\t\t\t\t\t * Otherwise provide a generic error page\n\t\t\t\t\t */\n\t\t\t\t\tresponse.statusCode = 500;\n\t\t\t\t\tresponse.setHeader('Content-Type', 'text/plain');\n\t\t\t\t\tresponse.write('Internal Server Error');\n\t\t\t\t\tawait responseFinalize();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (result === undefined) {\n\t\t\t\tthrow(new Error('internal error: No result'));\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Write the response to the client\n\t\t\t */\n\t\t\tresponse.statusCode = result.statusCode ?? 200;\n\n\t\t\tfor (const headerKey in result.headers ?? {}) {\n\t\t\t\tconst headerValue = result.headers?.[headerKey];\n\t\t\t\tif (headerValue !== undefined) {\n\t\t\t\t\tresponse.setHeader(headerKey, headerValue);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse.setHeader('Content-Type', result.contentType ?? 'application/json');\n\t\t\tresponse.write(result.output);\n\t\t\tawait responseFinalize();\n\t\t});\n\t\tthis.#server = server;\n\n\t\t/**\n\t\t * Create a promise to wait for the server to close\n\t\t */\n\t\tconst waiter = new Promise<void>((resolve) => {\n\t\t\tserver.on('close', () => {\n\t\t\t\tthis.logger?.debug('KeetaAnchorHTTP.Server', 'Server closed');\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\n\t\t/**\n\t\t * Start listening on the port\n\t\t */\n\t\tserver.listen(port, () => {\n\t\t\tconst address = server.address();\n\t\t\tif (address !== null && typeof address === 'object') {\n\t\t\t\t// @ts-ignore\n\t\t\t\tthis.port = address.port;\n\t\t\t\tonSetPort?.(this.port);\n\t\t\t}\n\t\t\tthis.logger?.debug('KeetaAnchorHTTP.Server', 'Listening on port:', this.port);\n\t\t});\n\n\t\t/**\n\t\t * Wait for the server to close\n\t\t */\n\t\tawait waiter;\n\t}\n\n\t/**\n\t * Start the HTTP server and wait for it to be fully initialized.\n\t */\n\tasync start(): Promise<void> {\n\t\t/*\n\t\t * Start the server and wait for it to be initialized before returning\n\t\t */\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.#serverPromise = this.main(function() {\n\t\t\t\tresolve();\n\t\t\t}).catch(function(error: unknown) {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n\t\t\t\treject(error);\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Wait for the server to terminate. This will only resolve once the\n\t * server has been stopped.\n\t */\n\tasync wait(): Promise<void> {\n\t\tawait this.#serverPromise;\n\t}\n\n\t/**\n\t * Stop the HTTP server and wait for it to be fully terminated.\n\t */\n\tasync stop(): Promise<void> {\n\t\tthis.#server?.close();\n\t\t// @ts-ignore\n\t\tthis.#server = undefined;\n\t\tawait this.wait();\n\t}\n\n\t/**\n\t * Get the URL of the server, which can be used to make requests to\n\t * it. This will use \"localhost\" as the hostname and the port that\n\t * the server is listening on by default but can be overridden by\n\t * setting a custom URL.\n\t */\n\tget url(): string {\n\t\tif (this.port === 0 || this.#server === undefined) {\n\t\t\tthrow(new Error('Server not started'));\n\t\t}\n\n\t\tif (this.#url !== undefined) {\n\t\t\tlet newURL: string;\n\t\t\tif (typeof this.#url === 'string') {\n\t\t\t\tnewURL = this.#url;\n\t\t\t} else if (this.#url instanceof URL || ('port' in this.#url && 'hostname' in this.#url && 'toString' in this.#url)) {\n\t\t\t\tnewURL = this.#url.toString();\n\t\t\t} else if (typeof this.#url === 'function') {\n\t\t\t\tnewURL = this.#url(this);\n\t\t\t} else {\n\t\t\t\tassertNever(this.#url);\n\t\t\t}\n\n\t\t\tconst newURLObj = new URL(newURL);\n\t\t\tnewURLObj.pathname = '/';\n\t\t\tnewURLObj.search = '';\n\n\t\t\tconst retval = newURLObj.toString();\n\n\t\t\treturn(retval);\n\t\t}\n\n\t\tconst urlObj = new URL('http://localhost');\n\t\turlObj.port = String(this.#urlParts?.port ?? this.port);\n\t\turlObj.hostname = this.#urlParts?.hostname ?? 'localhost';\n\t\turlObj.protocol = this.#urlParts?.protocol ?? 'http:';\n\t\turlObj.pathname = '/';\n\t\turlObj.search = '';\n\n\t\tconst retval = urlObj.toString();\n\n\t\treturn(retval);\n\t}\n\n\tset url(value: undefined | string | URL | ((object: this) => string)) {\n\t\tthis.#urlParts = undefined;\n\t\tthis.#url = value;\n\t}\n\n\t[Symbol.asyncDispose](): Promise<void> {\n\t\treturn(this.stop());\n\t}\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/lib/http-server/index.ts"],"names":[],"mappings":";;AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,OAAO,EACN,gBAAgB,EAChB,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AAS,CAAC;QAC3B,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC;IACnB,CAAC;IAED;;;;OAIG;IACO,kBAAkB,CAAC,MAAc,EAAE,UAAe,EAAE,IAAiC;QAC9F,OAAM,CAAC;YACN,MAAM;YACN,GAAG,EAAE,gBAAgB,CAAC,IAAI,CAAC,GAAG,EAAE,UAAU,CAAC;YAC3C,IAAI;YACJ,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,sBAAsB,EAAE,IAAI,CAAC,6BAA6B;SAC1D,CAAC,CAAC;IACJ,CAAC;IAED,CAAC,MAAM,CAAC,YAAY,CAAC;QACpB,OAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IACrB,CAAC;CACD","sourcesContent":["import * as http from 'http';\n\nimport {\n\tKeetaAnchorError,\n\tKeetaAnchorUserError\n} from '../error.js';\nimport type { JSONSerializable } from '../utils/json.js';\nimport type { Logger, LogLevel } from '../log/index.js';\nimport type {\n\tCertificateChainConfig,\n\tResolvedCertificateChainRequirement\n} from '../utils/certificate-network.js';\nimport { Log } from '../log/index.js';\nimport { createAssert } from 'typia';\nimport { assertNever } from '../utils/never.js';\nimport { resolveCertificateChainConfig } from '../utils/certificate-network.js';\nimport { Buffer } from '../utils/buffer.js';\nimport { lib as KeetaNetLib } from '@keetanetwork/keetanet-client';\nimport type { KeetaAnchorReplayGuard } from './replay-guard.js';\nimport { MemoryReplayGuard } from './replay-guard.js';\nimport type { RequestAuthContext } from './request-signing.js';\nimport { normalizeRequestPath, publicRequestURL } from './request-signing.js';\n\ntype RequestTiming = InstanceType<typeof KeetaNetLib.RequestTiming>;\n\nexport const AssertHTTPErrorData: (input: unknown) => { error: string; statusCode?: number; contentType?: string; } = createAssert<{ error: string; statusCode?: number; contentType?: string; }>();\n\n/**\n * The maximum size of a request body when the route sets no\n * `maxBodySize` (1 MiB)\n */\nconst MAX_REQUEST_SIZE = 1024 ** 2;\n\n/**\n * Read a request body, refusing it once it passes `limit` bytes.\n * Returns null when the body is too large.\n */\nasync function readBody(request: http.IncomingMessage, limit: number): Promise<Buffer | null> {\n\tconst chunks: Buffer[] = [];\n\tlet size = 0;\n\tfor await (const chunk of request) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\tconst buffer = Buffer.from(chunk);\n\t\tsize += buffer.length;\n\t\tif (size > limit) {\n\t\t\treturn(null);\n\t\t}\n\n\t\tchunks.push(buffer);\n\t}\n\n\tconst body = Buffer.concat(chunks, size);\n\treturn(body);\n}\n\ntype RouteHandlerContext = {\n\ttiming: RequestTiming;\n};\n\n/*\n * Positional parameters are getting too numerous, so starting\n * with `timing` new parameters go into `RouteHandlerContext`\n *\n * TODO: Migrate the existing positional parameters into\n * `RouteHandlerContext` as well\n */\ntype RouteHandlerMethod<BodyDataType = JSONSerializable | undefined> = (\n\turlParams: Map<string, string>,\n\tpostData: BodyDataType,\n\trequestHeaders: http.IncomingHttpHeaders,\n\trequestUrl: URL,\n\tcontext: RouteHandlerContext\n) => Promise<{\n\toutput: string | Buffer;\n\tstatusCode?: number;\n\tcontentType?: string;\n\theaders?: { [headerName: string]: string; };\n}>;\n\ntype RouteHandlerWithConfig = {\n\tbodyType: 'raw';\n\tmaxBodySize?: number;\n\thandler: RouteHandlerMethod<Buffer>;\n} | {\n\tbodyType: 'parsed';\n\tmaxBodySize?: number;\n\thandler: RouteHandlerMethod;\n} | {\n\tbodyType: 'none';\n\thandler: RouteHandlerMethod<undefined>;\n};\ntype RouteHandler = RouteHandlerMethod | RouteHandlerWithConfig;\nexport type Routes = { [route: string]: RouteHandler };\nexport type RoutesWithConfigs = { [route: string]: RouteHandlerWithConfig };\n\nexport interface KeetaAnchorHTTPServerConfig {\n\t/**\n\t * Identifier for the server instance -- if one is not given\n\t * a random one will be generated.\n\t */\n\tid?: string;\n\n\t/**\n\t * The port for the HTTP server to listen on (default is an ephemeral port).\n\t */\n\tport?: number;\n\n\t/**\n\t * Enable debug logging\n\t */\n\tlogger?: Logger | undefined;\n\t/**\n\t * The URL for the server. By default, this will be generated based on\n\t * the port and will use \"localhost\" as the hostname, but it can be\n\t * overridden by setting this to a string, URL, or function that\n\t * generates the URL\n\t */\n\turl?: undefined | string | URL | ((object: KeetaNetAnchorHTTPServer) => string) | {\n\t\thostname?: string;\n\t\tport?: number;\n\t\tprotocol?: string;\n\t};\n\n\t/**\n\t * Optional on-chain cert-chain gate. When set, authenticated callers\n\t * MUST have a published cert chaining to one of `trustedIssuers`.\n\t */\n\trequireCertificateChain?: CertificateChainConfig | undefined;\n\n\t/**\n\t * Where signed request nonces are recorded so each signature is\n\t * accepted once. Defaults to a {@link MemoryReplayGuard}, which is\n\t * per process: servers running several instances behind one URL\n\t * must share one guard, such as a `RedisReplayGuard` or\n\t * `PostgresReplayGuard`.\n\t */\n\treplayGuard?: KeetaAnchorReplayGuard | undefined;\n\n\t/**\n\t * Accept request signatures from clients that predate request\n\t * binding. Such a signature covers only the operation's data, so it\n\t * can be replayed at another anchor. Defaults to `true`; set it to\n\t * `false` once every client signs requests.\n\t */\n\tacceptLegacyRequestSignatures?: boolean | undefined;\n};\n\nexport abstract class KeetaNetAnchorHTTPServer<ConfigType extends KeetaAnchorHTTPServerConfig = KeetaAnchorHTTPServerConfig> implements Required<KeetaAnchorHTTPServerConfig> {\n\treadonly port: NonNullable<KeetaAnchorHTTPServerConfig['port']>;\n\treadonly logger: NonNullable<KeetaAnchorHTTPServerConfig['logger']>;\n\treadonly id: NonNullable<KeetaAnchorHTTPServerConfig['id']>;\n\t/**\n\t * Resolved cert-chain requirement, or `undefined` when disabled.\n\t * @see {@link requireCertificateChain}.\n\t */\n\tprotected readonly resolvedCertificateChainRequirement: ResolvedCertificateChainRequirement | undefined;\n\treadonly replayGuard: KeetaAnchorReplayGuard;\n\treadonly acceptLegacyRequestSignatures: boolean;\n\t#serverPromise?: Promise<void>;\n\t#server?: http.Server;\n\t#urlParts: undefined | { hostname?: string; port?: number; protocol?: string; };\n\t#url: undefined | string | URL | ((object: this) => string);\n\treadonly #config: ConfigType;\n\n\tconstructor(config: ConfigType) {\n\t\tthis.#config = { ...config };\n\t\tthis.port = config.port ?? 0;\n\t\tthis.id = config.id ?? crypto.randomUUID();\n\t\tthis.logger = config.logger ?? Log.Legacy('ANCHOR');\n\t\tthis.resolvedCertificateChainRequirement = resolveCertificateChainConfig(config.requireCertificateChain);\n\t\tthis.replayGuard = config.replayGuard ?? new MemoryReplayGuard();\n\t\t/*\n\t\t * XXX:TODO: Default to `false` in the first release after every\n\t\t * supported client sends dual signatures, and drop the\n\t\t * legacy path once no anchor runs a release before them\n\t\t */\n\t\tthis.acceptLegacyRequestSignatures = config.acceptLegacyRequestSignatures ?? true;\n\n\t\tif (config.url !== undefined) {\n\t\t\tif (config.url instanceof URL || typeof config.url === 'string') {\n\t\t\t\tthis.#url = config.url;\n\t\t\t\tthis.#urlParts = undefined;\n\t\t\t} else if (typeof config.url === 'function') {\n\t\t\t\t/**\n\t\t\t\t * The parameter for the call back is typed as\n\t\t\t\t * `this`, which means any subclass is typed\n\t\t\t\t * but the interface can't identify that --\n\t\t\t\t * instead it types it as the base class\n\t\t\t\t * (KeetaNetAnchorHTTPServer), which means it\n\t\t\t\t * can't be assigned to the type of `#url`\n\t\t\t\t * without overriding the type check. However,\n\t\t\t\t * we know that `this` will be at least\n\t\t\t\t * compatible with the base class.\n\t\t\t\t */\n\t\t\t\t// @ts-ignore\n\t\t\t\tthis.#url = config.url;\n\t\t\t\tthis.#urlParts = undefined;\n\t\t\t} else {\n\t\t\t\tthis.#url = undefined;\n\t\t\t\tthis.#urlParts = config.url;\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected abstract initRoutes(config: ConfigType): Promise<Routes>;\n\n\t/**\n\t * Public view of the cert-chain config, or `undefined` when disabled.\n\t */\n\tget requireCertificateChain(): CertificateChainConfig | undefined {\n\t\treturn(this.resolvedCertificateChainRequirement);\n\t}\n\n\t/**\n\t * Trusted-issuer DNs metadata. Is `undefined` when the gate is not configured.\n\t */\n\tprotected acceptedIssuerDNs(): { name: string; value: string }[][] | undefined {\n\t\tconst requirement = this.resolvedCertificateChainRequirement;\n\t\tif (requirement === undefined) {\n\t\t\treturn(undefined);\n\t\t}\n\n\t\treturn(requirement.acceptedIssuerDNs);\n\t}\n\n\tprivate static routeMatch(requestURL: URL, routeURL: URL): ({ match: true; params: Map<string, string>; wildcard?: { prefixLength: number }} | { match: false }) {\n\t\tconst requestURLPaths = requestURL.pathname.split('/');\n\t\tconst routeURLPaths = routeURL.pathname.split('/');\n\n\t\t// Check if route ends with wildcard /**\n\t\tconst isWildcard = routeURLPaths.length > 0 && routeURLPaths[routeURLPaths.length - 1] === '**';\n\t\tif (isWildcard) {\n\t\t\t// For wildcard routes, request must have more segments than route prefix (minus the **)\n\t\t\t// This ensures at least one segment is captured by the wildcard\n\t\t\tconst prefixLength = routeURLPaths.length - 1;\n\t\t\tif (requestURLPaths.length <= prefixLength) {\n\t\t\t\treturn({ match: false });\n\t\t\t}\n\n\t\t\t// Check that prefix segments match\n\t\t\tconst params = new Map<string, string>();\n\t\t\tfor (let partIndex = 0; partIndex < prefixLength; partIndex++) {\n\t\t\t\tconst requestPath = requestURLPaths[partIndex];\n\n\t\t\t\tconst routePath = routeURLPaths[partIndex];\n\t\t\t\tif (routePath === undefined || requestPath === undefined) {\n\t\t\t\t\treturn({ match: false });\n\t\t\t\t}\n\n\t\t\t\tif (routePath.startsWith(':')) {\n\t\t\t\t\tparams.set(routePath.slice(1), requestPath);\n\t\t\t\t} else if (requestPath !== routePath) {\n\t\t\t\t\treturn({ match: false });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Capture the remainder as the wildcard param\n\t\t\t// Filter empty segments to handle trailing slashes correctly\n\t\t\tconst remainder = requestURLPaths.slice(prefixLength)\n\t\t\t\t.filter(function(s) {\n\t\t\t\t\treturn(s !== '');\n\t\t\t\t})\n\t\t\t\t.join('/');\n\n\t\t\tif (remainder === '') {\n\t\t\t\t// Reject if wildcard would capture nothing\n\t\t\t\treturn({ match: false });\n\t\t\t}\n\n\t\t\tparams.set('**', remainder);\n\n\t\t\treturn({ match: true, params: params, wildcard: { prefixLength }});\n\t\t}\n\n\t\t// Non-wildcard: require exact segment count\n\t\tif (requestURLPaths.length !== routeURLPaths.length) {\n\t\t\treturn({ match: false });\n\t\t}\n\n\t\tconst params = new Map<string, string>();\n\t\tfor (let partIndex = 0; partIndex < requestURLPaths.length; partIndex++) {\n\t\t\tconst requestPath = requestURLPaths[partIndex];\n\t\t\tconst routePath = routeURLPaths[partIndex];\n\n\t\t\tif (routePath === undefined || requestPath === undefined) {\n\t\t\t\treturn({ match: false });\n\t\t\t}\n\n\t\t\tif (routePath.startsWith(':')) {\n\t\t\t\tparams.set(routePath.slice(1), requestPath);\n\t\t\t} else if (requestPath !== routePath) {\n\t\t\t\treturn({ match: false });\n\t\t\t}\n\t\t}\n\n\t\treturn({ match: true, params: params });\n\t}\n\n\tprivate static routeFind(method: string, requestURL: URL, routes: Routes): { route: Routes[keyof Routes]; params: Map<string, string> } | null {\n\t\tlet wildcardMatch: { route: Routes[keyof Routes]; params: Map<string, string> } | null = null;\n\t\tlet wildcardPrefixLength = -1;\n\n\t\tfor (const routeKey in routes) {\n\t\t\tconst route = routes[routeKey];\n\t\t\tif (route === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst [routeMethod, ...routePathParts] = routeKey.split(' ');\n\t\t\tconst routePath = `/${routePathParts.join(' ')}`.replace(/^\\/+/, '/');\n\n\t\t\tif (method !== routeMethod) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst routeURL = new URL(routePath, 'http://localhost');\n\t\t\tconst matchResult = this.routeMatch(requestURL, routeURL);\n\t\t\tif (matchResult.match) {\n\t\t\t\t// Exact matches take priority over wildcard matches\n\t\t\t\tif (matchResult.wildcard === undefined) {\n\t\t\t\t\treturn({\n\t\t\t\t\t\troute: route,\n\t\t\t\t\t\tparams: matchResult.params\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Keep the most specific wildcard (longest prefix wins)\n\t\t\t\tif (matchResult.wildcard.prefixLength > wildcardPrefixLength) {\n\t\t\t\t\twildcardPrefixLength = matchResult.wildcard.prefixLength;\n\t\t\t\t\twildcardMatch = {\n\t\t\t\t\t\troute: route,\n\t\t\t\t\t\tparams: matchResult.params\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Return most specific wildcard match if no exact match found\n\t\treturn(wildcardMatch);\n\t}\n\n\tprivate static addCORS(routes: Routes): RoutesWithConfigs {\n\t\tconst newRoutes: RoutesWithConfigs = {};\n\n\t\tconst validMethods = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']);\n\n\t\tconst methodsByPath: { [key: string]: Set<string>; } = {};\n\t\tfor (const routeKey in routes) {\n\t\t\tconst methodAndPath = routeKey.split(' ');\n\t\t\tconst method = methodAndPath[0];\n\t\t\tconst path = methodAndPath.slice(1).join(' ');\n\n\t\t\tif (method === undefined || path === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!validMethods.has(method)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!(path in methodsByPath)) {\n\t\t\t\tmethodsByPath[path] = new Set<string>();\n\t\t\t}\n\n\t\t\tif (methodsByPath[path] === undefined) {\n\t\t\t\tthrow(new Error(`internal error: methodsByPath missing path for ${path}`));\n\t\t\t}\n\n\t\t\tmethodsByPath[path].add(method);\n\t\t}\n\n\t\tconst seenPaths = new Set<string>();\n\t\tfor (const routeKey in routes) {\n\t\t\tconst methodAndPath = routeKey.split(' ');\n\t\t\tconst method = methodAndPath[0];\n\t\t\tconst path = methodAndPath.slice(1).join(' ');\n\n\t\t\tconst routeHandler = routes[routeKey];\n\t\t\tif (routeHandler === undefined) {\n\t\t\t\tthrow(new Error(`internal error: routeHandler missing for routeKey ${routeKey}`));\n\t\t\t}\n\n\t\t\tlet newRoute: RouteHandlerWithConfig;\n\n\t\t\tif (typeof routeHandler === 'function') {\n\t\t\t\tnewRoute = {\n\t\t\t\t\tbodyType: 'parsed',\n\t\t\t\t\thandler: routeHandler\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tnewRoute = routeHandler;\n\t\t\t}\n\n\t\t\tif (method !== 'ERROR') {\n\t\t\t\tif (method === undefined || path === undefined) {\n\t\t\t\t\tnewRoutes[routeKey] = newRoute;\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (!validMethods.has(method)) {\n\t\t\t\t\tnewRoutes[routeKey] = newRoute;\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst validMethodsForPath = methodsByPath[path];\n\n\t\t\tlet validMethodsForPathParts: string[] = [];\n\t\t\tif (validMethodsForPath !== undefined) {\n\t\t\t\tvalidMethodsForPath.add('OPTIONS');\n\t\t\t\tvalidMethodsForPathParts = Array.from(validMethodsForPath);\n\t\t\t} else {\n\t\t\t\tvalidMethodsForPathParts = [...Array.from(validMethods), 'OPTIONS'];\n\t\t\t}\n\n\t\t\tnewRoutes[routeKey] = {\n\t\t\t\t...newRoute,\n\t\t\t\tasync handler(...args: Parameters<RouteHandlerMethod<unknown>>) {\n\t\t\t\t\t// This is typed properly, but TS can't infer it here\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tconst retval = await newRoute.handler(...args);\n\n\t\t\t\t\t/* Add CORS headers to the response for the original route handler */\n\t\t\t\t\tif (retval.contentType === 'application/json' || retval.contentType === undefined) {\n\t\t\t\t\t\tif (!('headers' in retval) || retval.headers === undefined) {\n\t\t\t\t\t\t\tretval.headers = {};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretval.headers['Access-Control-Allow-Origin'] = '*';\n\t\t\t\t\t}\n\n\t\t\t\t\treturn(retval);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tif (!seenPaths.has(path) && path !== '' && path !== undefined) {\n\t\t\t\tconst corsRouteKey = `OPTIONS ${path}`;\n\n\t\t\t\tnewRoutes[corsRouteKey] = {\n\t\t\t\t\tbodyType: 'none',\n\t\t\t\t\tasync handler() {\n\t\t\t\t\t\treturn({\n\t\t\t\t\t\t\toutput: '',\n\t\t\t\t\t\t\tstatusCode: 204,\n\t\t\t\t\t\t\tcontentType: 'text/plain',\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\t'Access-Control-Allow-Origin': '*',\n\t\t\t\t\t\t\t\t'Access-Control-Allow-Methods': validMethodsForPathParts.join(', '),\n\t\t\t\t\t\t\t\t'Access-Control-Allow-Headers': 'Content-Type',\n\t\t\t\t\t\t\t\t'Access-Control-Max-Age': '86400'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tseenPaths.add(path);\n\t\t\t}\n\t\t}\n\n\t\treturn(newRoutes);\n\t}\n\n\tprivate async main(onSetPort?: (port: number) => void): Promise<void> {\n\t\tthis.logger?.debug('KeetaAnchorHTTP.Server', 'Starting HTTP server...');\n\n\t\tconst port = this.port;\n\n\t\tconst routes = KeetaNetAnchorHTTPServer.addCORS({\n\t\t\tERROR: async function(_ignore_params, postData) {\n\t\t\t\tconst errorInfo = AssertHTTPErrorData(postData);\n\n\t\t\t\tconst retval = {\n\t\t\t\t\toutput: errorInfo.error,\n\t\t\t\t\tstatusCode: errorInfo.statusCode ?? 400,\n\t\t\t\t\tcontentType: errorInfo.contentType ?? 'text/plain'\n\t\t\t\t};\n\n\t\t\t\treturn(retval);\n\t\t\t},\n\t\t\t...(await this.initRoutes(this.#config))\n\t\t});\n\n\t\tconst server = new http.Server(async (request, response) => {\n\t\t\tconst timing = new KeetaNetLib.RequestTiming();\n\t\t\ttiming.log = this.logger;\n\n\t\t\tconst forwardedProtoHeader = request.headers['x-forwarded-proto'];\n\t\t\tlet forwardedProto: string | undefined;\n\t\t\tif (Array.isArray(forwardedProtoHeader)) {\n\t\t\t\tforwardedProto = forwardedProtoHeader[0];\n\t\t\t} else {\n\t\t\t\tforwardedProto = forwardedProtoHeader;\n\t\t\t}\n\t\t\tforwardedProto = forwardedProto?.split(',')[0]?.trim();\n\n\t\t\tlet protocol: string;\n\t\t\tif (forwardedProto !== undefined && forwardedProto !== '') {\n\t\t\t\tprotocol = forwardedProto;\n\t\t\t} else if ('encrypted' in request.socket && request.socket.encrypted === true) {\n\t\t\t\tprotocol = 'https';\n\t\t\t} else {\n\t\t\t\tprotocol = 'http';\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Get the Base URL from the request Host header (if\n\t\t\t * available) or default to localhost. This is used\n\t\t\t * to construct the full URL for routing.\n\t\t\t */\n\t\t\tconst inputURLBaseRaw = new URL(`${protocol}://${request.headers.host ?? 'localhost'}`);\n\t\t\tconst inputURLBase = inputURLBaseRaw.protocol + '//' + inputURLBaseRaw.host;\n\n\t\t\t/*\n\t\t\t * Normalize the input URL by stripping leading slashes and\n\t\t\t * combining it with the base URL to get the full URL for routing.\n\t\t\t */\n\t\t\tconst inputURLRaw = normalizeRequestPath(request.url ?? '/');\n\t\t\tconst inputURLObject = new URL(inputURLRaw, 'http://localhost');\n\t\t\tconst inputURL = inputURLObject.pathname + (function() {\n\t\t\t\tif (inputURLObject.search === '') {\n\t\t\t\t\treturn('');\n\t\t\t\t}\n\n\t\t\t\treturn('?' + inputURLObject.searchParams.toString());\n\t\t\t})();\n\t\t\tconst url = new URL(inputURL, inputURLBase);\n\t\t\tconst method = request.method ?? 'GET';\n\n\t\t\t/*\n\t\t\t * Finalize the response by adding the Server-Timing\n\t\t\t * header, **writing the output**, syncing the logger and\n\t\t\t * ending the response.\n\t\t\t */\n\t\t\tconst responseFinalize = async (output: string | Buffer) => {\n\t\t\t\tconst serverTiming = timing.toServerTimingHeader();\n\t\t\t\tif (serverTiming !== '') {\n\t\t\t\t\tresponse.setHeader('Server-Timing', serverTiming);\n\t\t\t\t}\n\n\t\t\t\tresponse.write(output);\n\n\t\t\t\tif ('sync' in this.logger && typeof this.logger.sync === 'function') {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.logger.sync();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* ignore errors */\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresponse.end();\n\t\t\t};\n\n\t\t\t/*\n\t\t\t * If the request is malformed, reject it immediately\n\t\t\t */\n\t\t\tif (inputURLRaw.at(0) !== '/') {\n\t\t\t\tresponse.statusCode = 400;\n\t\t\t\tresponse.setHeader('Content-Type', 'text/plain');\n\t\t\t\tawait responseFinalize('Bad Request');\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Lookup the route based on the request\n\t\t\t */\n\t\t\tconst requestedRouteAndParams = KeetaNetAnchorHTTPServer.routeFind(method, url, routes);\n\t\t\tif (requestedRouteAndParams === null) {\n\t\t\t\tresponse.statusCode = 404;\n\t\t\t\tresponse.setHeader('Content-Type', 'text/plain');\n\t\t\t\tawait responseFinalize('Not Found');\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Extract the route handler and the parameters from\n\t\t\t * the request\n\t\t\t */\n\t\t\tconst { route, params } = requestedRouteAndParams;\n\n\t\t\t/**\n\t\t\t * Attempt to run the route, catch any errors\n\t\t\t */\n\t\t\tlet result: Awaited<ReturnType<RouteHandlerMethod>> | undefined = undefined;\n\t\t\tlet generatedResult = false;\n\t\t\ttry {\n\t\t\t\tif (!request.method) {\n\t\t\t\t\tthrow(new Error('internal error: No request method'));\n\t\t\t\t}\n\n\t\t\t\tlet bodyData: JSONSerializable | Buffer | undefined;\n\n\t\t\t\tconst shouldCheckBody = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(request.method);\n\n\t\t\t\tif (typeof route === 'function') {\n\t\t\t\t\tthrow(new Error('internal error: Route handler missing body type configuration, should have been added in addCORS'));\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * If POST'ing, PUT'ing, or PATCH'ing, read and parse the request body\n\t\t\t\t */\n\t\t\t\tif (shouldCheckBody && route.bodyType !== 'none') {\n\t\t\t\t\tconst bodySizeLimit = route.maxBodySize ?? MAX_REQUEST_SIZE;\n\n\t\t\t\t\t// Early rejection based on Content-Length header\n\t\t\t\t\tconst contentLength = request.headers['content-length'];\n\t\t\t\t\tlet declaredSize = Number.NaN;\n\t\t\t\t\tif (contentLength !== undefined) {\n\t\t\t\t\t\tdeclaredSize = Number.parseInt(contentLength, 10);\n\t\t\t\t\t}\n\n\t\t\t\t\tlet data: Buffer | null = null;\n\t\t\t\t\tif (Number.isNaN(declaredSize) || declaredSize <= bodySizeLimit) {\n\t\t\t\t\t\tusing bodyTimer = timing.startTime('http-request-body');\n\t\t\t\t\t\tdata = await readBody(request, bodySizeLimit);\n\t\t\t\t\t\tbodyTimer.end();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (data === null) {\n\t\t\t\t\t\trequest.resume();\n\n\t\t\t\t\t\tresponse.statusCode = 413;\n\t\t\t\t\t\tresponse.setHeader('Content-Type', 'text/plain');\n\t\t\t\t\t\tawait responseFinalize('Payload Too Large');\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (route.bodyType === 'raw') {\n\t\t\t\t\t\tbodyData = data;\n\t\t\t\t\t} else if (route.bodyType === 'parsed' && request.headers['content-type'] === 'application/json') {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\t\t\t\t\tbodyData = JSON.parse(data.toString('utf-8'));\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tthrow(new Error('Invalid JSON data'));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (data.length > 0) {\n\t\t\t\t\t\tthrow(new KeetaAnchorUserError('Unsupported content type'));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * Call the route handler\n\t\t\t\t */\n\t\t\t\tresult = await timing.runTimer('http-handler', async function() {\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\treturn(await route.handler(params, bodyData, request.headers, url, { timing }));\n\t\t\t\t});\n\n\t\t\t\tgeneratedResult = true;\n\t\t\t} catch (err) {\n\t\t\t\tlet logLevel: Lowercase<LogLevel> = 'error';\n\t\t\t\tif (KeetaAnchorError.isInstance(err)) {\n\t\t\t\t\t/*\n\t\t\t\t\t * We're able to safely cast this here because the cast\n\t\t\t\t\t * duplicates the logic.\n\t\t\t\t\t */\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n\t\t\t\t\tlogLevel = err.logLevel.toLowerCase() as Lowercase<typeof err.logLevel>;\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * If an error occurs, log it and return an error page\n\t\t\t\t */\n\t\t\t\tthis.logger?.[logLevel]('KeetaAnchorHTTP.Server', err);\n\n\t\t\t\t/**\n\t\t\t\t * If it is a user error, provide a user-friendly error page\n\t\t\t\t */\n\t\t\t\tconst errorHandlerRoute = routes['ERROR'];\n\t\t\t\tif (errorHandlerRoute !== undefined) {\n\t\t\t\t\tlet errBody;\n\t\t\t\t\tif (KeetaAnchorError.isInstance(err) && err['userError']) {\n\t\t\t\t\t\terrBody = err.asErrorResponse('application/json');\n\t\t\t\t\t} else {\n\t\t\t\t\t\terrBody = {\n\t\t\t\t\t\t\terror: JSON.stringify({ ok: false, error: 'Internal Server Error' }),\n\t\t\t\t\t\t\tstatusCode: 500,\n\t\t\t\t\t\t\tcontentType: 'application/json'\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tresult = await errorHandlerRoute.handler(new Map(), errBody, request.headers, url, { timing });\n\t\t\t\t\tgeneratedResult = true;\n\t\t\t\t}\n\n\t\t\t\tif (!generatedResult) {\n\t\t\t\t\t/**\n\t\t\t\t\t * Otherwise provide a generic error page\n\t\t\t\t\t */\n\t\t\t\t\tresponse.statusCode = 500;\n\t\t\t\t\tresponse.setHeader('Content-Type', 'text/plain');\n\t\t\t\t\tawait responseFinalize('Internal Server Error');\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (result === undefined) {\n\t\t\t\tthrow(new Error('internal error: No result'));\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Write the response to the client\n\t\t\t */\n\t\t\tresponse.statusCode = result.statusCode ?? 200;\n\n\t\t\tfor (const headerKey in result.headers ?? {}) {\n\t\t\t\tconst headerValue = result.headers?.[headerKey];\n\t\t\t\tif (headerValue !== undefined) {\n\t\t\t\t\tresponse.setHeader(headerKey, headerValue);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse.setHeader('Content-Type', result.contentType ?? 'application/json');\n\t\t\tawait responseFinalize(result.output);\n\t\t});\n\t\tthis.#server = server;\n\n\t\t/**\n\t\t * Create a promise to wait for the server to close\n\t\t */\n\t\tconst waiter = new Promise<void>((resolve) => {\n\t\t\tserver.on('close', () => {\n\t\t\t\tthis.logger?.debug('KeetaAnchorHTTP.Server', 'Server closed');\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\n\t\t/**\n\t\t * Start listening on the port\n\t\t */\n\t\tserver.listen(port, () => {\n\t\t\tconst address = server.address();\n\t\t\tif (address !== null && typeof address === 'object') {\n\t\t\t\t// @ts-ignore\n\t\t\t\tthis.port = address.port;\n\t\t\t\tonSetPort?.(this.port);\n\t\t\t}\n\t\t\tthis.logger?.debug('KeetaAnchorHTTP.Server', 'Listening on port:', this.port);\n\t\t});\n\n\t\t/**\n\t\t * Wait for the server to close\n\t\t */\n\t\tawait waiter;\n\t}\n\n\t/**\n\t * Start the HTTP server and wait for it to be fully initialized.\n\t */\n\tasync start(): Promise<void> {\n\t\t/*\n\t\t * Start the server and wait for it to be initialized before returning\n\t\t */\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.#serverPromise = this.main(function() {\n\t\t\t\tresolve();\n\t\t\t}).catch(function(error: unknown) {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n\t\t\t\treject(error);\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Wait for the server to terminate. This will only resolve once the\n\t * server has been stopped.\n\t */\n\tasync wait(): Promise<void> {\n\t\tawait this.#serverPromise;\n\t}\n\n\t/**\n\t * Stop the HTTP server and wait for it to be fully terminated.\n\t */\n\tasync stop(): Promise<void> {\n\t\tthis.#server?.close();\n\t\t// @ts-ignore\n\t\tthis.#server = undefined;\n\t\tawait this.wait();\n\t}\n\n\t/**\n\t * Get the URL of the server, which can be used to make requests to\n\t * it. This will use \"localhost\" as the hostname and the port that\n\t * the server is listening on by default but can be overridden by\n\t * setting a custom URL.\n\t */\n\tget url(): string {\n\t\tif (this.port === 0 || this.#server === undefined) {\n\t\t\tthrow(new Error('Server not started'));\n\t\t}\n\n\t\tif (this.#url !== undefined) {\n\t\t\tlet newURL: string;\n\t\t\tif (typeof this.#url === 'string') {\n\t\t\t\tnewURL = this.#url;\n\t\t\t} else if (this.#url instanceof URL || ('port' in this.#url && 'hostname' in this.#url && 'toString' in this.#url)) {\n\t\t\t\tnewURL = this.#url.toString();\n\t\t\t} else if (typeof this.#url === 'function') {\n\t\t\t\tnewURL = this.#url(this);\n\t\t\t} else {\n\t\t\t\tassertNever(this.#url);\n\t\t\t}\n\n\t\t\tconst newURLObj = new URL(newURL);\n\t\t\tnewURLObj.pathname = '/';\n\t\t\tnewURLObj.search = '';\n\n\t\t\tconst retval = newURLObj.toString();\n\n\t\t\treturn(retval);\n\t\t}\n\n\t\tconst urlObj = new URL('http://localhost');\n\t\turlObj.port = String(this.#urlParts?.port ?? this.port);\n\t\turlObj.hostname = this.#urlParts?.hostname ?? 'localhost';\n\t\turlObj.protocol = this.#urlParts?.protocol ?? 'http:';\n\t\turlObj.pathname = '/';\n\t\turlObj.search = '';\n\n\t\tconst retval = urlObj.toString();\n\n\t\treturn(retval);\n\t}\n\n\tset url(value: undefined | string | URL | ((object: this) => string)) {\n\t\tthis.#urlParts = undefined;\n\t\tthis.#url = value;\n\t}\n\n\t/**\n\t * The context to verify a signed request against: the request as\n\t * seen at this server's public URL, this server's replay guard, and\n\t * whether it accepts legacy signatures.\n\t */\n\tprotected requestAuthContext(method: string, requestURL: URL, body?: RequestAuthContext['body']): RequestAuthContext {\n\t\treturn({\n\t\t\tmethod,\n\t\t\turl: publicRequestURL(this.url, requestURL),\n\t\t\tbody,\n\t\t\treplayGuard: this.replayGuard,\n\t\t\tacceptLegacySignatures: this.acceptLegacyRequestSignatures\n\t\t});\n\t}\n\n\t[Symbol.asyncDispose](): Promise<void> {\n\t\treturn(this.stop());\n\t}\n}\n"]}
@@ -0,0 +1,41 @@
1
+ import type * as pg from 'pg';
2
+ import type { Logger } from '../log/index.js';
3
+ import type { KeetaAnchorReplayGuard } from './replay-guard.js';
4
+ /**
5
+ * Options for {@link PostgresReplayGuard}
6
+ */
7
+ export interface PostgresReplayGuardOptions {
8
+ /**
9
+ * Returns a Postgres connection pool. Every instance of a server must
10
+ * reach the same database.
11
+ */
12
+ pool: () => Promise<pg.Pool>;
13
+ /**
14
+ * Name of the table the guard keeps its claims in. Created, with a
15
+ * `<tableName>_schema_version` table beside it, when the guard is
16
+ * first used. Defaults to `replay_guard_claims`.
17
+ */
18
+ tableName?: string | undefined;
19
+ /**
20
+ * How often, at most, one instance deletes expired claims, in
21
+ * milliseconds. Defaults to one minute.
22
+ */
23
+ sweepIntervalMs?: number | undefined;
24
+ /**
25
+ * Receives errors from deleting expired claims, which never fail a
26
+ * claim
27
+ */
28
+ logger?: Logger | undefined;
29
+ }
30
+ /**
31
+ * {@link KeetaAnchorReplayGuard} shared through Postgres, for servers
32
+ * that run several instances behind one URL. A claim inserts its key,
33
+ * or takes over the row of an expired claim, in one statement, so a
34
+ * nonce spent at one instance is refused at every other.
35
+ */
36
+ export declare class PostgresReplayGuard implements KeetaAnchorReplayGuard {
37
+ #private;
38
+ constructor(options: PostgresReplayGuardOptions);
39
+ claim(key: string, expiresAt: Date): Promise<boolean>;
40
+ }
41
+ //# sourceMappingURL=replay-guard-postgres.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay-guard-postgres.d.ts","sourceRoot":"","sources":["../../../src/lib/http-server/replay-guard-postgres.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,EAAE,MAAM,IAAI,CAAC;AAC9B,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAEhE;;GAEG;AACH,MAAM,WAAW,0BAA0B;IAC1C;;;OAGG;IACH,IAAI,EAAE,MAAM,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;IAE7B;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE/B;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAErC;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5B;AAeD;;;;;GAKG;AACH,qBAAa,mBAAoB,YAAW,sBAAsB;;gBAQrD,OAAO,EAAE,0BAA0B;IAYzC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC;CAoF3D"}
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Table names are written into the SQL, so they are limited to plain
3
+ * identifiers short enough that the names built from them, such as
4
+ * `<tableName>_schema_version`, fit the 63 bytes Postgres allows
5
+ */
6
+ const TableNamePattern = /^[a-z_][a-z0-9_]{0,47}$/;
7
+ /**
8
+ * Key of the advisory lock that instances hold while they bring the
9
+ * tables to the current schema version, one at a time
10
+ */
11
+ const SCHEMA_LOCK_ID = 0x5245504C;
12
+ /**
13
+ * {@link KeetaAnchorReplayGuard} shared through Postgres, for servers
14
+ * that run several instances behind one URL. A claim inserts its key,
15
+ * or takes over the row of an expired claim, in one statement, so a
16
+ * nonce spent at one instance is refused at every other.
17
+ */
18
+ export class PostgresReplayGuard {
19
+ #pool;
20
+ #tableName;
21
+ #sweepIntervalMs;
22
+ #logger;
23
+ #ready;
24
+ #lastSweep = 0;
25
+ constructor(options) {
26
+ const tableName = options.tableName ?? 'replay_guard_claims';
27
+ if (!TableNamePattern.test(tableName)) {
28
+ throw (new Error(`Invalid tableName ${tableName}: use lowercase letters, digits and underscores, at most 48 characters`));
29
+ }
30
+ this.#pool = options.pool;
31
+ this.#tableName = tableName;
32
+ this.#sweepIntervalMs = options.sweepIntervalMs ?? 60_000;
33
+ this.#logger = options.logger;
34
+ }
35
+ async claim(key, expiresAt) {
36
+ const pool = await this.#getPool();
37
+ const now = new Date();
38
+ const result = await pool.query(`
39
+ INSERT INTO ${this.#tableName} (key, expires_at) VALUES ($1, $2)
40
+ ON CONFLICT (key) DO UPDATE SET expires_at = EXCLUDED.expires_at
41
+ WHERE ${this.#tableName}.expires_at <= $3
42
+ RETURNING key
43
+ `, [key, expiresAt, now]);
44
+ const claimed = result.rowCount === 1;
45
+ /* The claim is recorded, so a failed sweep must not fail it */
46
+ try {
47
+ await this.#sweep(pool, now);
48
+ }
49
+ catch (error) {
50
+ this.#logger?.error('PostgresReplayGuard::claim', 'Could not delete expired claims:', error);
51
+ }
52
+ return (claimed);
53
+ }
54
+ async #getPool() {
55
+ this.#ready ??= (async () => {
56
+ const pool = await this.#pool();
57
+ const client = await pool.connect();
58
+ try {
59
+ /* Instances starting together migrate the tables one at a time */
60
+ await client.query('BEGIN');
61
+ await client.query('SELECT pg_advisory_xact_lock($1)', [SCHEMA_LOCK_ID]);
62
+ await client.query(`
63
+ CREATE TABLE IF NOT EXISTS ${this.#tableName}_schema_version (
64
+ version INTEGER PRIMARY KEY,
65
+ applied_at TIMESTAMPTZ NOT NULL
66
+ )
67
+ `);
68
+ const versionResult = await client.query(`SELECT MAX(version) AS version FROM ${this.#tableName}_schema_version`);
69
+ const currentVersion = versionResult.rows[0]?.version ?? 0;
70
+ /* Version 1: the claims table and its expiry index */
71
+ if (currentVersion < 1) {
72
+ await client.query(`
73
+ CREATE TABLE ${this.#tableName} (
74
+ key TEXT PRIMARY KEY,
75
+ expires_at TIMESTAMPTZ NOT NULL
76
+ )
77
+ `);
78
+ await client.query(`CREATE INDEX ${this.#tableName}_expires_at ON ${this.#tableName} (expires_at)`);
79
+ await client.query(`INSERT INTO ${this.#tableName}_schema_version (version, applied_at) VALUES (1, now())`);
80
+ }
81
+ await client.query('COMMIT');
82
+ }
83
+ catch (error) {
84
+ await client.query('ROLLBACK');
85
+ throw (error);
86
+ }
87
+ finally {
88
+ client.release();
89
+ }
90
+ return (pool);
91
+ })();
92
+ try {
93
+ return (await this.#ready);
94
+ }
95
+ catch (error) {
96
+ /* Try again on the next claim */
97
+ this.#ready = undefined;
98
+ throw (error);
99
+ }
100
+ }
101
+ /**
102
+ * Delete expired claims, at most once per sweep interval. A claim
103
+ * never depends on this, since an expired row is taken over in place.
104
+ */
105
+ async #sweep(pool, now) {
106
+ if (now.valueOf() - this.#lastSweep < this.#sweepIntervalMs) {
107
+ return;
108
+ }
109
+ this.#lastSweep = now.valueOf();
110
+ await pool.query(`DELETE FROM ${this.#tableName} WHERE expires_at <= $1`, [now]);
111
+ }
112
+ }
113
+ //# sourceMappingURL=replay-guard-postgres.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay-guard-postgres.js","sourceRoot":"","sources":["../../../src/lib/http-server/replay-guard-postgres.ts"],"names":[],"mappings":"AAoCA;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,yBAAyB,CAAC;AAEnD;;;GAGG;AACH,MAAM,cAAc,GAAG,UAAU,CAAC;AAElC;;;;;GAKG;AACH,MAAM,OAAO,mBAAmB;IACtB,KAAK,CAAqC;IAC1C,UAAU,CAAS;IACnB,gBAAgB,CAAS;IACzB,OAAO,CAAqB;IACrC,MAAM,CAA+B;IACrC,UAAU,GAAG,CAAC,CAAC;IAEf,YAAY,OAAmC;QAC9C,MAAM,SAAS,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,CAAC;YACJ,OAAM,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC;QAC3B,CAAC;QAAC,OAAO,KAAc,EAAE,CAAC;YACzB,iCAAiC;YACjC,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;YACxB,MAAK,CAAC,KAAK,CAAC,CAAC;QACd,CAAC;IACF,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,MAAM,CAAC,IAAa,EAAE,GAAS;QACpC,IAAI,GAAG,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,gBAAgB,EAAE,CAAC;YAC7D,OAAO;QACR,CAAC;QAED,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,OAAO,EAAE,CAAC;QAChC,MAAM,IAAI,CAAC,KAAK,CAAC,eAAe,IAAI,CAAC,UAAU,yBAAyB,EAAE,CAAE,GAAG,CAAE,CAAC,CAAC;IACpF,CAAC;CACD","sourcesContent":["// cspell:ignore TIMESTAMPTZ xact\n\nimport type * as pg from 'pg';\nimport type { Logger } from '../log/index.js';\nimport type { KeetaAnchorReplayGuard } from './replay-guard.js';\n\n/**\n * Options for {@link PostgresReplayGuard}\n */\nexport interface PostgresReplayGuardOptions {\n\t/**\n\t * Returns a Postgres connection pool. Every instance of a server must\n\t * reach the same database.\n\t */\n\tpool: () => Promise<pg.Pool>;\n\n\t/**\n\t * Name of the table the guard keeps its claims in. Created, with a\n\t * `<tableName>_schema_version` table beside it, when the guard is\n\t * first used. Defaults to `replay_guard_claims`.\n\t */\n\ttableName?: string | undefined;\n\n\t/**\n\t * How often, at most, one instance deletes expired claims, in\n\t * milliseconds. Defaults to one minute.\n\t */\n\tsweepIntervalMs?: number | undefined;\n\n\t/**\n\t * Receives errors from deleting expired claims, which never fail a\n\t * claim\n\t */\n\tlogger?: Logger | undefined;\n}\n\n/**\n * Table names are written into the SQL, so they are limited to plain\n * identifiers short enough that the names built from them, such as\n * `<tableName>_schema_version`, fit the 63 bytes Postgres allows\n */\nconst TableNamePattern = /^[a-z_][a-z0-9_]{0,47}$/;\n\n/**\n * Key of the advisory lock that instances hold while they bring the\n * tables to the current schema version, one at a time\n */\nconst SCHEMA_LOCK_ID = 0x5245504C;\n\n/**\n * {@link KeetaAnchorReplayGuard} shared through Postgres, for servers\n * that run several instances behind one URL. A claim inserts its key,\n * or takes over the row of an expired claim, in one statement, so a\n * nonce spent at one instance is refused at every other.\n */\nexport class PostgresReplayGuard implements KeetaAnchorReplayGuard {\n\treadonly #pool: PostgresReplayGuardOptions['pool'];\n\treadonly #tableName: string;\n\treadonly #sweepIntervalMs: number;\n\treadonly #logger: Logger | undefined;\n\t#ready: Promise<pg.Pool> | undefined;\n\t#lastSweep = 0;\n\n\tconstructor(options: PostgresReplayGuardOptions) {\n\t\tconst tableName = options.tableName ?? 'replay_guard_claims';\n\t\tif (!TableNamePattern.test(tableName)) {\n\t\t\tthrow(new Error(`Invalid tableName ${tableName}: use lowercase letters, digits and underscores, at most 48 characters`));\n\t\t}\n\n\t\tthis.#pool = options.pool;\n\t\tthis.#tableName = tableName;\n\t\tthis.#sweepIntervalMs = options.sweepIntervalMs ?? 60_000;\n\t\tthis.#logger = options.logger;\n\t}\n\n\tasync claim(key: string, expiresAt: Date): Promise<boolean> {\n\t\tconst pool = await this.#getPool();\n\t\tconst now = new Date();\n\n\t\tconst result = await pool.query(`\n\t\t\tINSERT INTO ${this.#tableName} (key, expires_at) VALUES ($1, $2)\n\t\t\tON CONFLICT (key) DO UPDATE SET expires_at = EXCLUDED.expires_at\n\t\t\tWHERE ${this.#tableName}.expires_at <= $3\n\t\t\tRETURNING key\n\t\t`, [ key, expiresAt, now ]);\n\n\t\tconst claimed = result.rowCount === 1;\n\n\t\t/* The claim is recorded, so a failed sweep must not fail it */\n\t\ttry {\n\t\t\tawait this.#sweep(pool, now);\n\t\t} catch (error: unknown) {\n\t\t\tthis.#logger?.error('PostgresReplayGuard::claim', 'Could not delete expired claims:', error);\n\t\t}\n\n\t\treturn(claimed);\n\t}\n\n\tasync #getPool(): Promise<pg.Pool> {\n\t\tthis.#ready ??= (async () => {\n\t\t\tconst pool = await this.#pool();\n\t\t\tconst client = await pool.connect();\n\t\t\ttry {\n\t\t\t\t/* Instances starting together migrate the tables one at a time */\n\t\t\t\tawait client.query('BEGIN');\n\t\t\t\tawait client.query('SELECT pg_advisory_xact_lock($1)', [ SCHEMA_LOCK_ID ]);\n\t\t\t\tawait client.query(`\n\t\t\t\t\tCREATE TABLE IF NOT EXISTS ${this.#tableName}_schema_version (\n\t\t\t\t\t\tversion INTEGER PRIMARY KEY,\n\t\t\t\t\t\tapplied_at TIMESTAMPTZ NOT NULL\n\t\t\t\t\t)\n\t\t\t\t`);\n\t\t\t\tconst versionResult = await client.query<{ version: number | null }>(`SELECT MAX(version) AS version FROM ${this.#tableName}_schema_version`);\n\t\t\t\tconst currentVersion = versionResult.rows[0]?.version ?? 0;\n\n\t\t\t\t/* Version 1: the claims table and its expiry index */\n\t\t\t\tif (currentVersion < 1) {\n\t\t\t\t\tawait client.query(`\n\t\t\t\t\t\tCREATE TABLE ${this.#tableName} (\n\t\t\t\t\t\t\tkey TEXT PRIMARY KEY,\n\t\t\t\t\t\t\texpires_at TIMESTAMPTZ NOT NULL\n\t\t\t\t\t\t)\n\t\t\t\t\t`);\n\t\t\t\t\tawait client.query(`CREATE INDEX ${this.#tableName}_expires_at ON ${this.#tableName} (expires_at)`);\n\t\t\t\t\tawait client.query(`INSERT INTO ${this.#tableName}_schema_version (version, applied_at) VALUES (1, now())`);\n\t\t\t\t}\n\n\t\t\t\tawait client.query('COMMIT');\n\t\t\t} catch (error: unknown) {\n\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t\tthrow(error);\n\t\t\t} finally {\n\t\t\t\tclient.release();\n\t\t\t}\n\n\t\t\treturn(pool);\n\t\t})();\n\n\t\ttry {\n\t\t\treturn(await this.#ready);\n\t\t} catch (error: unknown) {\n\t\t\t/* Try again on the next claim */\n\t\t\tthis.#ready = undefined;\n\t\t\tthrow(error);\n\t\t}\n\t}\n\n\t/**\n\t * Delete expired claims, at most once per sweep interval. A claim\n\t * never depends on this, since an expired row is taken over in place.\n\t */\n\tasync #sweep(pool: pg.Pool, now: Date): Promise<void> {\n\t\tif (now.valueOf() - this.#lastSweep < this.#sweepIntervalMs) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#lastSweep = now.valueOf();\n\t\tawait pool.query(`DELETE FROM ${this.#tableName} WHERE expires_at <= $1`, [ now ]);\n\t}\n}\n"]}
@@ -0,0 +1,29 @@
1
+ import type { RedisClientType } from 'redis';
2
+ import type { KeetaAnchorReplayGuard } from './replay-guard.js';
3
+ /**
4
+ * Options for {@link RedisReplayGuard}
5
+ */
6
+ export interface RedisReplayGuardOptions {
7
+ /**
8
+ * Returns a connected Redis client. Every instance of a server must
9
+ * reach the same Redis database.
10
+ */
11
+ redis: () => Promise<RedisClientType>;
12
+ /**
13
+ * Prefix for the keys the guard writes, so several servers can share
14
+ * one database. Defaults to `replay-guard`.
15
+ */
16
+ keyPrefix?: string | undefined;
17
+ }
18
+ /**
19
+ * {@link KeetaAnchorReplayGuard} shared through Redis, for servers that
20
+ * run several instances behind one URL. Each claim is one `SET NX` that
21
+ * Redis expires at the claim's expiry, so a nonce spent at one instance
22
+ * is refused at every other.
23
+ */
24
+ export declare class RedisReplayGuard implements KeetaAnchorReplayGuard {
25
+ #private;
26
+ constructor(options: RedisReplayGuardOptions);
27
+ claim(key: string, expiresAt: Date): Promise<boolean>;
28
+ }
29
+ //# sourceMappingURL=replay-guard-redis.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay-guard-redis.d.ts","sourceRoot":"","sources":["../../../src/lib/http-server/replay-guard-redis.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAEhE;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACvC;;;OAGG;IACH,KAAK,EAAE,MAAM,OAAO,CAAC,eAAe,CAAC,CAAC;IAEtC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC/B;AAED;;;;;GAKG;AACH,qBAAa,gBAAiB,YAAW,sBAAsB;;gBAIlD,OAAO,EAAE,uBAAuB;IAKtC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC;CAS3D"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * {@link KeetaAnchorReplayGuard} shared through Redis, for servers that
3
+ * run several instances behind one URL. Each claim is one `SET NX` that
4
+ * Redis expires at the claim's expiry, so a nonce spent at one instance
5
+ * is refused at every other.
6
+ */
7
+ export class RedisReplayGuard {
8
+ #redis;
9
+ #keyPrefix;
10
+ constructor(options) {
11
+ this.#redis = options.redis;
12
+ this.#keyPrefix = options.keyPrefix ?? 'replay-guard';
13
+ }
14
+ async claim(key, expiresAt) {
15
+ const redis = await this.#redis();
16
+ const result = await redis.set(`${this.#keyPrefix}:${key}`, '1', {
17
+ NX: true,
18
+ PXAT: expiresAt.valueOf()
19
+ });
20
+ return (result === 'OK');
21
+ }
22
+ }
23
+ //# sourceMappingURL=replay-guard-redis.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay-guard-redis.js","sourceRoot":"","sources":["../../../src/lib/http-server/replay-guard-redis.ts"],"names":[],"mappings":"AAsBA;;;;;GAKG;AACH,MAAM,OAAO,gBAAgB;IACnB,MAAM,CAAmC;IACzC,UAAU,CAAS;IAE5B,YAAY,OAAgC;QAC3C,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC;QAC5B,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,SAAS,IAAI,cAAc,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,GAAW,EAAE,SAAe;QACvC,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;QAClC,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,UAAU,IAAI,GAAG,EAAE,EAAE,GAAG,EAAE;YAChE,EAAE,EAAE,IAAI;YACR,IAAI,EAAE,SAAS,CAAC,OAAO,EAAE;SACzB,CAAC,CAAC;QAEH,OAAM,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACzB,CAAC;CACD","sourcesContent":["// cspell:ignore PXAT\n\nimport type { RedisClientType } from 'redis';\nimport type { KeetaAnchorReplayGuard } from './replay-guard.js';\n\n/**\n * Options for {@link RedisReplayGuard}\n */\nexport interface RedisReplayGuardOptions {\n\t/**\n\t * Returns a connected Redis client. Every instance of a server must\n\t * reach the same Redis database.\n\t */\n\tredis: () => Promise<RedisClientType>;\n\n\t/**\n\t * Prefix for the keys the guard writes, so several servers can share\n\t * one database. Defaults to `replay-guard`.\n\t */\n\tkeyPrefix?: string | undefined;\n}\n\n/**\n * {@link KeetaAnchorReplayGuard} shared through Redis, for servers that\n * run several instances behind one URL. Each claim is one `SET NX` that\n * Redis expires at the claim's expiry, so a nonce spent at one instance\n * is refused at every other.\n */\nexport class RedisReplayGuard implements KeetaAnchorReplayGuard {\n\treadonly #redis: RedisReplayGuardOptions['redis'];\n\treadonly #keyPrefix: string;\n\n\tconstructor(options: RedisReplayGuardOptions) {\n\t\tthis.#redis = options.redis;\n\t\tthis.#keyPrefix = options.keyPrefix ?? 'replay-guard';\n\t}\n\n\tasync claim(key: string, expiresAt: Date): Promise<boolean> {\n\t\tconst redis = await this.#redis();\n\t\tconst result = await redis.set(`${this.#keyPrefix}:${key}`, '1', {\n\t\t\tNX: true,\n\t\t\tPXAT: expiresAt.valueOf()\n\t\t});\n\n\t\treturn(result === 'OK');\n\t}\n}\n"]}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Records each signed request nonce so the same signature is accepted
3
+ * only once while its timestamp is still within the allowed skew.
4
+ *
5
+ * Servers that run several instances behind one URL must share one
6
+ * guard, such as a `RedisReplayGuard` or `PostgresReplayGuard`, or a
7
+ * signature can be replayed against another instance.
8
+ */
9
+ export interface KeetaAnchorReplayGuard {
10
+ /**
11
+ * Claim `key` until `expiresAt`. Resolves `true` the first time a key
12
+ * is claimed, and `false` while an earlier claim on it has not expired.
13
+ */
14
+ claim(key: string, expiresAt: Date): Promise<boolean>;
15
+ }
16
+ /**
17
+ * Process-local {@link KeetaAnchorReplayGuard}. When it holds the maximum
18
+ * number of live claims, it refuses new ones rather than forgetting an
19
+ * earlier claim, so a flood of signed requests cannot make a spent nonce
20
+ * usable again.
21
+ */
22
+ export declare class MemoryReplayGuard implements KeetaAnchorReplayGuard {
23
+ #private;
24
+ constructor(options?: {
25
+ maxEntries?: number;
26
+ });
27
+ claim(key: string, expiresAt: Date): Promise<boolean>;
28
+ }
29
+ //# sourceMappingURL=replay-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay-guard.d.ts","sourceRoot":"","sources":["../../../src/lib/http-server/replay-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,WAAW,sBAAsB;IACtC;;;OAGG;IACH,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACtD;AAOD;;;;;GAKG;AACH,qBAAa,iBAAkB,YAAW,sBAAsB;;gBAInD,OAAO,CAAC,EAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE;IAIvC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC;CA+C3D"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Default number of live claims {@link MemoryReplayGuard} holds.
3
+ */
4
+ const DEFAULT_MAX_ENTRIES = 100_000;
5
+ /**
6
+ * Process-local {@link KeetaAnchorReplayGuard}. When it holds the maximum
7
+ * number of live claims, it refuses new ones rather than forgetting an
8
+ * earlier claim, so a flood of signed requests cannot make a spent nonce
9
+ * usable again.
10
+ */
11
+ export class MemoryReplayGuard {
12
+ #expiries = new Map();
13
+ #maxEntries;
14
+ constructor(options) {
15
+ this.#maxEntries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES;
16
+ }
17
+ async claim(key, expiresAt) {
18
+ const now = Date.now();
19
+ this.#dropExpired(now);
20
+ const existing = this.#expiries.get(key);
21
+ if (existing !== undefined && existing > now) {
22
+ return (false);
23
+ }
24
+ if (existing === undefined && this.#expiries.size >= this.#maxEntries) {
25
+ /* A claim with a later expiry can hide expired ones behind it */
26
+ this.#dropAllExpired(now);
27
+ if (this.#expiries.size >= this.#maxEntries) {
28
+ return (false);
29
+ }
30
+ }
31
+ this.#expiries.delete(key);
32
+ this.#expiries.set(key, expiresAt.valueOf());
33
+ return (true);
34
+ }
35
+ /**
36
+ * Drop expired claims from the front of the insertion order. Claims
37
+ * are inserted roughly in expiry order, so this stays cheap.
38
+ */
39
+ #dropExpired(now) {
40
+ for (const [key, expiry] of this.#expiries) {
41
+ if (expiry > now) {
42
+ return;
43
+ }
44
+ this.#expiries.delete(key);
45
+ }
46
+ }
47
+ /**
48
+ * Drop every expired claim, wherever it sits in insertion order.
49
+ */
50
+ #dropAllExpired(now) {
51
+ for (const [key, expiry] of this.#expiries) {
52
+ if (expiry <= now) {
53
+ this.#expiries.delete(key);
54
+ }
55
+ }
56
+ }
57
+ }
58
+ //# sourceMappingURL=replay-guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay-guard.js","sourceRoot":"","sources":["../../../src/lib/http-server/replay-guard.ts"],"names":[],"mappings":"AAgBA;;GAEG;AACH,MAAM,mBAAmB,GAAG,OAAO,CAAC;AAEpC;;;;;GAKG;AACH,MAAM,OAAO,iBAAiB;IACpB,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;IACtC,WAAW,CAAS;IAE7B,YAAY,OAAiC;QAC5C,IAAI,CAAC,WAAW,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CAAE,GAAG,EAAE,MAAM,CAAE,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YAC9C,IAAI,MAAM,IAAI,GAAG,EAAE,CAAC;gBACnB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC5B,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["/**\n * Records each signed request nonce so the same signature is accepted\n * only once while its timestamp is still within the allowed skew.\n *\n * Servers that run several instances behind one URL must share one\n * guard, such as a `RedisReplayGuard` or `PostgresReplayGuard`, or a\n * signature can be replayed against another instance.\n */\nexport interface KeetaAnchorReplayGuard {\n\t/**\n\t * Claim `key` until `expiresAt`. Resolves `true` the first time a key\n\t * is claimed, and `false` while an earlier claim on it has not expired.\n\t */\n\tclaim(key: string, expiresAt: Date): Promise<boolean>;\n}\n\n/**\n * Default number of live claims {@link MemoryReplayGuard} holds.\n */\nconst DEFAULT_MAX_ENTRIES = 100_000;\n\n/**\n * Process-local {@link KeetaAnchorReplayGuard}. When it holds the maximum\n * number of live claims, it refuses new ones rather than forgetting an\n * earlier claim, so a flood of signed requests cannot make a spent nonce\n * usable again.\n */\nexport class MemoryReplayGuard implements KeetaAnchorReplayGuard {\n\treadonly #expiries = new Map<string, number>();\n\treadonly #maxEntries: number;\n\n\tconstructor(options?: { maxEntries?: number }) {\n\t\tthis.#maxEntries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES;\n\t}\n\n\tasync claim(key: string, expiresAt: Date): Promise<boolean> {\n\t\tconst now = Date.now();\n\t\tthis.#dropExpired(now);\n\n\t\tconst existing = this.#expiries.get(key);\n\t\tif (existing !== undefined && existing > now) {\n\t\t\treturn(false);\n\t\t}\n\n\t\tif (existing === undefined && this.#expiries.size >= this.#maxEntries) {\n\t\t\t/* A claim with a later expiry can hide expired ones behind it */\n\t\t\tthis.#dropAllExpired(now);\n\t\t\tif (this.#expiries.size >= this.#maxEntries) {\n\t\t\t\treturn(false);\n\t\t\t}\n\t\t}\n\n\t\tthis.#expiries.delete(key);\n\t\tthis.#expiries.set(key, expiresAt.valueOf());\n\n\t\treturn(true);\n\t}\n\n\t/**\n\t * Drop expired claims from the front of the insertion order. Claims\n\t * are inserted roughly in expiry order, so this stays cheap.\n\t */\n\t#dropExpired(now: number): void {\n\t\tfor (const [ key, expiry ] of this.#expiries) {\n\t\t\tif (expiry > now) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.#expiries.delete(key);\n\t\t}\n\t}\n\n\t/**\n\t * Drop every expired claim, wherever it sits in insertion order.\n\t */\n\t#dropAllExpired(now: number): void {\n\t\tfor (const [ key, expiry ] of this.#expiries) {\n\t\t\tif (expiry <= now) {\n\t\t\t\tthis.#expiries.delete(key);\n\t\t\t}\n\t\t}\n\t}\n}\n"]}