@keetanetwork/anchor 0.0.112 → 0.0.113
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/http-server/common.d.ts +3 -2
- package/lib/http-server/common.d.ts.map +1 -1
- package/lib/http-server/common.js +9 -13
- package/lib/http-server/common.js.map +1 -1
- package/lib/http-server/index.d.ts +21 -1
- package/lib/http-server/index.d.ts.map +1 -1
- package/lib/http-server/index.js +84 -36
- package/lib/http-server/index.js.map +1 -1
- package/lib/http-server/replay-guard.d.ts +29 -0
- package/lib/http-server/replay-guard.d.ts.map +1 -0
- package/lib/http-server/replay-guard.js +58 -0
- package/lib/http-server/replay-guard.js.map +1 -0
- package/lib/http-server/request-signing.d.ts +53 -0
- package/lib/http-server/request-signing.d.ts.map +1 -0
- package/lib/http-server/request-signing.js +130 -0
- package/lib/http-server/request-signing.js.map +1 -0
- package/lib/utils/signing.d.ts +5 -0
- package/lib/utils/signing.d.ts.map +1 -1
- package/lib/utils/signing.js +6 -1
- package/lib/utils/signing.js.map +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/services/asset-movement/client.d.ts +5 -4
- package/services/asset-movement/client.d.ts.map +1 -1
- package/services/asset-movement/client.js +27 -13
- package/services/asset-movement/client.js.map +1 -1
- package/services/asset-movement/common.generated.js +1 -1
- package/services/asset-movement/common.server.generated.js +50 -50
- package/services/asset-movement/server.d.ts.map +1 -1
- package/services/asset-movement/server.js +22 -4
- package/services/asset-movement/server.js.map +1 -1
- package/services/fx/server.d.ts.map +1 -1
- package/services/fx/server.js +45 -38
- package/services/fx/server.js.map +1 -1
- package/services/kyc/client.d.ts +8 -3
- package/services/kyc/client.d.ts.map +1 -1
- package/services/kyc/client.js +24 -23
- package/services/kyc/client.js.map +1 -1
- package/services/kyc/common.d.ts +0 -7
- package/services/kyc/common.d.ts.map +1 -1
- package/services/kyc/common.js +0 -8
- package/services/kyc/common.js.map +1 -1
- package/services/kyc/server.d.ts +3 -1
- package/services/kyc/server.d.ts.map +1 -1
- package/services/kyc/server.js +15 -33
- package/services/kyc/server.js.map +1 -1
- package/services/notification/client.d.ts.map +1 -1
- package/services/notification/client.js +39 -33
- package/services/notification/client.js.map +1 -1
- package/services/notification/server.js +10 -10
- package/services/notification/server.js.map +1 -1
- package/services/storage/client.d.ts +3 -0
- package/services/storage/client.d.ts.map +1 -1
- package/services/storage/client.js +41 -11
- package/services/storage/client.js.map +1 -1
- package/services/storage/server.d.ts.map +1 -1
- package/services/storage/server.js +12 -11
- package/services/storage/server.js.map +1 -1
- package/services/username/client.d.ts +12 -1
- package/services/username/client.d.ts.map +1 -1
- package/services/username/client.js +36 -30
- package/services/username/client.js.map +1 -1
- package/services/username/server.d.ts.map +1 -1
- package/services/username/server.js +7 -6
- 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;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,MAAM,CAAC,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAAmK,CAAC;AAEpM;;GAEG;AACH,MAAM,gBAAgB,GAAG,GAAG,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;AAoD1C,CAAC;AAEF,MAAM,OAAgB,wBAAwB;IACpC,IAAI,CAAmD;IACvD,MAAM,CAAqD;IAC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eetaAnchorUserError\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,oBAAoB,EACpB,MAAM,aAAa,CAAC;AAOrB,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,GAAG,IAAI,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAEnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEtD,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,E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M,MAAM,GAAG,SAAS,CAAC,QAAQ,EAAE,CAAC;YAEpC,OAAM,CAAC,MAAM,CAAC,CAAC;QAChB,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,kBAAkB,CAAC,CAAC;QAC3C,MAAM,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;QACxD,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,SAAS,EAAE,QAAQ,IAAI,WAAW,CAAC;QAC1D,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,SAAS,EAAE,QAAQ,IAAI,OAAO,CAAC;QACtD,MAAM,CAAC,QAAQ,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;;;OAGG;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;SAC7B,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.\n\t */\n\treplayGuard?: KeetaAnchorReplayGuard | 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\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\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, and this server's replay guard.\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});\n\t}\n\n\t[Symbol.asyncDispose](): Promise<void> {\n\t\treturn(this.stop());\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 one backed by Redis or SQL, or a signature can be
|
|
7
|
+
* 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,iB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AAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC5B,CAAC;IACF,CAAC;IAED;;OAEG;IACH,eAAe,CAAC,GAAW;QAC1B,KAAK,MAAM,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 one backed by Redis or SQL, or a signature can be\n * 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"]}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Signable, SignableAccount, VerifiableAccount } from '../utils/signing.js';
|
|
2
|
+
import type { HTTPSignedField } from './common.js';
|
|
3
|
+
import type { KeetaAnchorReplayGuard } from './replay-guard.js';
|
|
4
|
+
/**
|
|
5
|
+
* The request a signature is made for: the operation URL as the client
|
|
6
|
+
* calls it, and the body. A JSON body is given as the value passed to
|
|
7
|
+
* `JSON.stringify` (its `signed` field is ignored), and a raw body as a
|
|
8
|
+
* `Buffer`.
|
|
9
|
+
*/
|
|
10
|
+
export interface RequestTarget {
|
|
11
|
+
method: string;
|
|
12
|
+
url: URL;
|
|
13
|
+
body?: unknown;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* What a server needs to verify a signed request: the request as seen
|
|
17
|
+
* at the server's public URL, and where it records spent nonces.
|
|
18
|
+
*/
|
|
19
|
+
export interface RequestAuthContext extends RequestTarget {
|
|
20
|
+
replayGuard: KeetaAnchorReplayGuard;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Collapse leading slashes in a request path, as the server does before
|
|
24
|
+
* routing, so `//api/x` and `/api/x` name the same operation.
|
|
25
|
+
*/
|
|
26
|
+
export declare function normalizeRequestPath(path: string): string;
|
|
27
|
+
/**
|
|
28
|
+
* Rebase a request URL onto the server's configured public URL, so the
|
|
29
|
+
* audience never comes from the Host header.
|
|
30
|
+
*/
|
|
31
|
+
export declare function publicRequestURL(serverURL: string, requestURL: URL): URL;
|
|
32
|
+
/**
|
|
33
|
+
* Sign `data` for one request.
|
|
34
|
+
*/
|
|
35
|
+
export declare function signRequest(account: SignableAccount, target: RequestTarget, data: Signable): Promise<HTTPSignedField>;
|
|
36
|
+
/**
|
|
37
|
+
* Check that a request signature covers this request, without spending
|
|
38
|
+
* its nonce. Resolves `false` when it does not.
|
|
39
|
+
*/
|
|
40
|
+
export declare function verifyRequestSignature(account: VerifiableAccount, context: RequestTarget, data: Signable, signed: HTTPSignedField): Promise<boolean>;
|
|
41
|
+
/**
|
|
42
|
+
* Spend the nonce of a verified request signature. Throws
|
|
43
|
+
* `KeetaAnchorUserError` when the replay guard refuses it: the nonce was
|
|
44
|
+
* already used, or the guard cannot record more claims now.
|
|
45
|
+
*/
|
|
46
|
+
export declare function claimRequestNonce(account: VerifiableAccount, context: RequestAuthContext, signed: HTTPSignedField): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* Verify a request signature, then spend its nonce. Resolves `false`
|
|
49
|
+
* when the signature does not cover this request, and throws as
|
|
50
|
+
* {@link claimRequestNonce} does when the nonce is refused.
|
|
51
|
+
*/
|
|
52
|
+
export declare function verifySignedRequest(account: VerifiableAccount, context: RequestAuthContext, data: Signable, signed: HTTPSignedField): Promise<boolean>;
|
|
53
|
+
//# sourceMappingURL=request-signing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-signing.d.ts","sourceRoot":"","sources":["../../../src/lib/http-server/request-signing.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,Q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@ -0,0 +1,130 @@
|
|
|
1
|
+
import { lib as KeetaNetLib } from '@keetanetwork/keetanet-client';
|
|
2
|
+
import { Buffer } from '../utils/buffer.js';
|
|
3
|
+
import { KeetaAnchorUserError } from '../error.js';
|
|
4
|
+
import { DEFAULT_MAX_SKEW_MS, SignData, VerifySignedData, canonicalizeJson } from '../utils/signing.js';
|
|
5
|
+
/**
|
|
6
|
+
* Version tag of the request signable layout. A signature made for
|
|
7
|
+
* another layout never verifies.
|
|
8
|
+
*/
|
|
9
|
+
const REQUEST_SIGNABLE_TAG = 'keeta-anchor-request-v1';
|
|
10
|
+
/**
|
|
11
|
+
* Collapse leading slashes in a request path, as the server does before
|
|
12
|
+
* routing, so `//api/x` and `/api/x` name the same operation.
|
|
13
|
+
*/
|
|
14
|
+
export function normalizeRequestPath(path) {
|
|
15
|
+
return (path.replace(/^\/+/, '/'));
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The URL a signature covers: origin, path, and every query parameter
|
|
19
|
+
* except the signature and the signer, in sorted order.
|
|
20
|
+
*/
|
|
21
|
+
function canonicalRequestURL(url) {
|
|
22
|
+
const params = [...url.searchParams].filter(function ([key]) {
|
|
23
|
+
return (key !== 'account' && !key.startsWith('signed.'));
|
|
24
|
+
}).sort(function ([a], [b]) {
|
|
25
|
+
if (a === b) {
|
|
26
|
+
return (0);
|
|
27
|
+
}
|
|
28
|
+
return (a < b ? -1 : 1);
|
|
29
|
+
});
|
|
30
|
+
let query = '';
|
|
31
|
+
if (params.length > 0) {
|
|
32
|
+
query = `?${new URLSearchParams(params).toString()}`;
|
|
33
|
+
}
|
|
34
|
+
return (`${url.origin}${normalizeRequestPath(url.pathname)}${query}`);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Hash of the body a signature covers. A JSON body is hashed in the form
|
|
38
|
+
* the server parses, without its top-level `signed` field.
|
|
39
|
+
*/
|
|
40
|
+
function requestBodyDigest(body) {
|
|
41
|
+
if (body === undefined) {
|
|
42
|
+
return ('');
|
|
43
|
+
}
|
|
44
|
+
let bytes;
|
|
45
|
+
if (Buffer.isBuffer(body)) {
|
|
46
|
+
bytes = body;
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
/* The server sees the body as it parses from the wire */
|
|
50
|
+
const wire = JSON.stringify(body);
|
|
51
|
+
const parsed = JSON.parse(wire);
|
|
52
|
+
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) && 'signed' in parsed) {
|
|
53
|
+
const unsigned = Object.entries(parsed).filter(function ([key]) {
|
|
54
|
+
return (key !== 'signed');
|
|
55
|
+
});
|
|
56
|
+
bytes = Buffer.from(canonicalizeJson(Object.fromEntries(unsigned)), 'utf-8');
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
bytes = Buffer.from(canonicalizeJson(parsed), 'utf-8');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return (Buffer.from(KeetaNetLib.Utils.Hash.Hash(bytes)).toString('hex'));
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Bind `data` to one request: the method, the URL (which names the
|
|
66
|
+
* anchor and the operation), and the body.
|
|
67
|
+
*/
|
|
68
|
+
function requestSignable(target, data) {
|
|
69
|
+
return ([
|
|
70
|
+
REQUEST_SIGNABLE_TAG,
|
|
71
|
+
target.method.toUpperCase(),
|
|
72
|
+
canonicalRequestURL(target.url),
|
|
73
|
+
requestBodyDigest(target.body),
|
|
74
|
+
...data
|
|
75
|
+
]);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Rebase a request URL onto the server's configured public URL, so the
|
|
79
|
+
* audience never comes from the Host header.
|
|
80
|
+
*/
|
|
81
|
+
export function publicRequestURL(serverURL, requestURL) {
|
|
82
|
+
return (new URL(`${requestURL.pathname}${requestURL.search}`, serverURL));
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Sign `data` for one request.
|
|
86
|
+
*/
|
|
87
|
+
export async function signRequest(account, target, data) {
|
|
88
|
+
return (await SignData(account, requestSignable(target, data)));
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Check that a request signature covers this request, without spending
|
|
92
|
+
* its nonce. Resolves `false` when it does not.
|
|
93
|
+
*/
|
|
94
|
+
export async function verifyRequestSignature(account, context, data, signed) {
|
|
95
|
+
let signable;
|
|
96
|
+
try {
|
|
97
|
+
signable = requestSignable(context, data);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
/* A body that cannot be canonicalized cannot have been signed */
|
|
101
|
+
return (false);
|
|
102
|
+
}
|
|
103
|
+
return (await VerifySignedData(account, signable, signed, { maxSkewMs: DEFAULT_MAX_SKEW_MS }));
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Spend the nonce of a verified request signature. Throws
|
|
107
|
+
* `KeetaAnchorUserError` when the replay guard refuses it: the nonce was
|
|
108
|
+
* already used, or the guard cannot record more claims now.
|
|
109
|
+
*/
|
|
110
|
+
export async function claimRequestNonce(account, context, signed) {
|
|
111
|
+
const expiresAt = new Date(new Date(signed.timestamp).valueOf() + DEFAULT_MAX_SKEW_MS);
|
|
112
|
+
const claimed = await context.replayGuard.claim(`request:${account.publicKeyString.get()}:${signed.nonce}`, expiresAt);
|
|
113
|
+
if (!claimed) {
|
|
114
|
+
throw (new KeetaAnchorUserError('Signed request refused: its nonce was already used, or the server cannot accept more signed requests now'));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Verify a request signature, then spend its nonce. Resolves `false`
|
|
119
|
+
* when the signature does not cover this request, and throws as
|
|
120
|
+
* {@link claimRequestNonce} does when the nonce is refused.
|
|
121
|
+
*/
|
|
122
|
+
export async function verifySignedRequest(account, context, data, signed) {
|
|
123
|
+
const valid = await verifyRequestSignature(account, context, data, signed);
|
|
124
|
+
if (!valid) {
|
|
125
|
+
return (false);
|
|
126
|
+
}
|
|
127
|
+
await claimRequestNonce(account, context, signed);
|
|
128
|
+
return (true);
|
|
129
|
+
}
|
|
130
|
+
//# sourceMappingURL=request-signing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-signing.js","sourceRoot":"","sources":["../../../src/lib/http-server/request-signing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,IAAI,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAInE,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,QAAQ,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAExG;;;GAGG;AACH,MAAM,oBAAoB,GAAG,yBAAyB,CAAC;AAsBvD;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,IAAY;IAChD,OAAM,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;AACnC,CAAC;AAED;;;GAGG;AACH,SAAS,mBAAmB,CAAC,GAAQ;IACpC,MAAM,MAAM,GAAG,CAAE,GAAG,GAAG,CAAC,YAAY,CAAE,CAAC,MAAM,CAAC,UAAS,CAAE,GAAG,CAAE;QAC7D,OAAM,CAAC,GAAG,KAAK,SAAS,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC,CAAC,CAAC,IAAI,CAAC,UAAS,CAAE,CAAC,CAAE,EAAE,CAAE,CAAC,CAAE;QAC5B,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACb,OAAM,CAAC,CAAC,CAAC,CAAC;QACX,CAAC;QAED,OAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACxB,CAAC,CAAC,CAAC;IAEH,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,IAAI,MAAM,CAAC,MAAM,GAAG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,SAAS,EAAE,mBAAmB,EAAE,CAAC,CAAC,CAAC;AAC/F,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,OAA0B,EAAE,OAA2B,EAAE,MAAuB;IACvH,MAAM,SAAS,GAAG,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,GAAG,mBAAmB,CAAC,CAAC;IACvF,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,WAAW,OAAO,CAAC,eAAe,CAAC,GAAG,EAAE,IAAI,MAAM,CAAC,KAAK,EAAE,EAAE,SAAS,CAAC,CAAC;IACvH,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,MAAK,CAAC,IAAI,oBAAoB,CAAC,0GAA0G,CAAC,CAAC,CAAC;IAC7I,CAAC;AACF,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,OAA0B,EAAE,OAA2B,EAAE,IAAc,EAAE,MAAuB;IACzI,MAAM,KAAK,GAAG,MAAM,sBAAsB,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IAC3E,IAAI,CAAC,KAAK,EAAE,CAAC;QACZ,OAAM,CAAC,KAAK,CAAC,CAAC;IACf,CAAC;IAED,MAAM,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IAElD,OAAM,CAAC,IAAI,CAAC,CAAC;AACd,CAAC","sourcesContent":["import { lib as KeetaNetLib } from '@keetanetwork/keetanet-client';\nimport type { Signable, SignableAccount, VerifiableAccount } from '../utils/signing.js';\nimport type { HTTPSignedField } from './common.js';\nimport type { KeetaAnchorReplayGuard } from './replay-guard.js';\nimport { Buffer } from '../utils/buffer.js';\nimport { KeetaAnchorUserError } from '../error.js';\nimport { DEFAULT_MAX_SKEW_MS, SignData, VerifySignedData, canonicalizeJson } from '../utils/signing.js';\n\n/**\n * Version tag of the request signable layout. A signature made for\n * another layout never verifies.\n */\nconst REQUEST_SIGNABLE_TAG = 'keeta-anchor-request-v1';\n\n/**\n * The request a signature is made for: the operation URL as the client\n * calls it, and the body. A JSON body is given as the value passed to\n * `JSON.stringify` (its `signed` field is ignored), and a raw body as a\n * `Buffer`.\n */\nexport interface RequestTarget {\n\tmethod: string;\n\turl: URL;\n\tbody?: unknown;\n}\n\n/**\n * What a server needs to verify a signed request: the request as seen\n * at the server's public URL, and where it records spent nonces.\n */\nexport interface RequestAuthContext extends RequestTarget {\n\treplayGuard: KeetaAnchorReplayGuard;\n}\n\n/**\n * Collapse leading slashes in a request path, as the server does before\n * routing, so `//api/x` and `/api/x` name the same operation.\n */\nexport function normalizeRequestPath(path: string): string {\n\treturn(path.replace(/^\\/+/, '/'));\n}\n\n/**\n * The URL a signature covers: origin, path, and every query parameter\n * except the signature and the signer, in sorted order.\n */\nfunction canonicalRequestURL(url: URL): string {\n\tconst params = [ ...url.searchParams ].filter(function([ key ]) {\n\t\treturn(key !== 'account' && !key.startsWith('signed.'));\n\t}).sort(function([ a ], [ b ]) {\n\t\tif (a === b) {\n\t\t\treturn(0);\n\t\t}\n\n\t\treturn(a < b ? -1 : 1);\n\t});\n\n\tlet query = '';\n\tif (params.length > 0) {\n\t\tquery = `?${new URLSearchParams(params).toString()}`;\n\t}\n\n\treturn(`${url.origin}${normalizeRequestPath(url.pathname)}${query}`);\n}\n\n/**\n * Hash of the body a signature covers. A JSON body is hashed in the form\n * the server parses, without its top-level `signed` field.\n */\nfunction requestBodyDigest(body: RequestTarget['body']): string {\n\tif (body === undefined) {\n\t\treturn('');\n\t}\n\n\tlet bytes: Buffer;\n\tif (Buffer.isBuffer(body)) {\n\t\tbytes = body;\n\t} else {\n\t\t/* The server sees the body as it parses from the wire */\n\t\tconst wire = JSON.stringify(body);\n\t\tconst parsed: unknown = JSON.parse(wire);\n\t\tif (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) && 'signed' in parsed) {\n\t\t\tconst unsigned = Object.entries(parsed).filter(function([ key ]) {\n\t\t\t\treturn(key !== 'signed');\n\t\t\t});\n\t\t\tbytes = Buffer.from(canonicalizeJson(Object.fromEntries(unsigned)), 'utf-8');\n\t\t} else {\n\t\t\tbytes = Buffer.from(canonicalizeJson(parsed), 'utf-8');\n\t\t}\n\t}\n\n\treturn(Buffer.from(KeetaNetLib.Utils.Hash.Hash(bytes)).toString('hex'));\n}\n\n/**\n * Bind `data` to one request: the method, the URL (which names the\n * anchor and the operation), and the body.\n */\nfunction requestSignable(target: RequestTarget, data: Signable): Signable {\n\treturn([\n\t\tREQUEST_SIGNABLE_TAG,\n\t\ttarget.method.toUpperCase(),\n\t\tcanonicalRequestURL(target.url),\n\t\trequestBodyDigest(target.body),\n\t\t...data\n\t]);\n}\n\n/**\n * Rebase a request URL onto the server's configured public URL, so the\n * audience never comes from the Host header.\n */\nexport function publicRequestURL(serverURL: string, requestURL: URL): URL {\n\treturn(new URL(`${requestURL.pathname}${requestURL.search}`, serverURL));\n}\n\n/**\n * Sign `data` for one request.\n */\nexport async function signRequest(account: SignableAccount, target: RequestTarget, data: Signable): Promise<HTTPSignedField> {\n\treturn(await SignData(account, requestSignable(target, data)));\n}\n\n/**\n * Check that a request signature covers this request, without spending\n * its nonce. Resolves `false` when it does not.\n */\nexport async function verifyRequestSignature(account: VerifiableAccount, context: RequestTarget, data: Signable, signed: HTTPSignedField): Promise<boolean> {\n\tlet signable: Signable;\n\ttry {\n\t\tsignable = requestSignable(context, data);\n\t} catch {\n\t\t/* A body that cannot be canonicalized cannot have been signed */\n\t\treturn(false);\n\t}\n\n\treturn(await VerifySignedData(account, signable, signed, { maxSkewMs: DEFAULT_MAX_SKEW_MS }));\n}\n\n/**\n * Spend the nonce of a verified request signature. Throws\n * `KeetaAnchorUserError` when the replay guard refuses it: the nonce was\n * already used, or the guard cannot record more claims now.\n */\nexport async function claimRequestNonce(account: VerifiableAccount, context: RequestAuthContext, signed: HTTPSignedField): Promise<void> {\n\tconst expiresAt = new Date(new Date(signed.timestamp).valueOf() + DEFAULT_MAX_SKEW_MS);\n\tconst claimed = await context.replayGuard.claim(`request:${account.publicKeyString.get()}:${signed.nonce}`, expiresAt);\n\tif (!claimed) {\n\t\tthrow(new KeetaAnchorUserError('Signed request refused: its nonce was already used, or the server cannot accept more signed requests now'));\n\t}\n}\n\n/**\n * Verify a request signature, then spend its nonce. Resolves `false`\n * when the signature does not cover this request, and throws as\n * {@link claimRequestNonce} does when the nonce is refused.\n */\nexport async function verifySignedRequest(account: VerifiableAccount, context: RequestAuthContext, data: Signable, signed: HTTPSignedField): Promise<boolean> {\n\tconst valid = await verifyRequestSignature(account, context, data, signed);\n\tif (!valid) {\n\t\treturn(false);\n\t}\n\n\tawait claimRequestNonce(account, context, signed);\n\n\treturn(true);\n}\n"]}
|
package/lib/utils/signing.d.ts
CHANGED
|
@@ -20,6 +20,11 @@ export declare function canonicalizeJson(value: unknown): string;
|
|
|
20
20
|
* {@link Date} instances are replaced by their ISO 8601 string.
|
|
21
21
|
*/
|
|
22
22
|
export declare function objectToSignable(item: SignableInput): Signable;
|
|
23
|
+
/**
|
|
24
|
+
* How far a signature's timestamp may be from the verifier's clock, by
|
|
25
|
+
* default (5 minutes)
|
|
26
|
+
*/
|
|
27
|
+
export declare const DEFAULT_MAX_SKEW_MS: number;
|
|
23
28
|
/**
|
|
24
29
|
* Options for signature verification
|
|
25
30
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signing.d.ts","sourceRoot":"","sources":["../../../src/lib/utils/signing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,IAAI,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAMnE,OAAO,EAAE,MAAM,EAAgD,MAAM,2BAA2B,CAAC;AAKjG,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,YAAY,CAAC,OAAO,WAAW,CAAC,OAAO,CAAC,CAAC,eAAe,CAAC,C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nB,gEAAgE;IAChE,aAAa,CAAC,EAAE,IAAI,CAAC;CACrB;AAED,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,gBAAgB,EAAE,MAAM,CAAC;CAAE,CAoDjL;AAED,wBAAsB,QAAQ,CAAC,OAAO,EAAE,eAAe,EAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;CAAE,CAAC,CAS1I;AAED,wBAAsB,gBAAgB,CACrC,OAAO,EAAE,iBAAiB,EAC1B,IAAI,EAAE,QAAQ,EACd,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,QAAQ,CAAC,CAAC,EAC5C,OAAO,CAAC,EAAE,aAAa,GACrB,OAAO,CAAC,OAAO,CAAC,CA6BlB"}
|
package/lib/utils/signing.js
CHANGED
|
@@ -145,6 +145,11 @@ export function objectToSignable(item) {
|
|
|
145
145
|
}
|
|
146
146
|
return ([canonical]);
|
|
147
147
|
}
|
|
148
|
+
/**
|
|
149
|
+
* How far a signature's timestamp may be from the verifier's clock, by
|
|
150
|
+
* default (5 minutes)
|
|
151
|
+
*/
|
|
152
|
+
export const DEFAULT_MAX_SKEW_MS = 5 * 60 * 1000;
|
|
148
153
|
export function FormatData(account, data, nonce, timestamp) {
|
|
149
154
|
nonce ??= crypto.randomUUID();
|
|
150
155
|
timestamp ??= new Date();
|
|
@@ -221,7 +226,7 @@ export async function VerifySignedData(account, data, signed, options) {
|
|
|
221
226
|
if (timestamp.toISOString() !== timestampString) {
|
|
222
227
|
return (false);
|
|
223
228
|
}
|
|
224
|
-
const maxSkewMs = options?.maxSkewMs ??
|
|
229
|
+
const maxSkewMs = options?.maxSkewMs ?? DEFAULT_MAX_SKEW_MS;
|
|
225
230
|
const referenceTime = options?.referenceTime ?? new Date();
|
|
226
231
|
if (Math.abs(timestamp.valueOf() - referenceTime.valueOf()) > maxSkewMs) {
|
|
227
232
|
/* Timestamp exceeds allowed skew from reference time */
|