polite-crawler 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +1 -0
  2. package/build/{browser-56dBBLec.mjs → browser-Cp5W-dmj.mjs} +5 -10
  3. package/build/{browser-56dBBLec.mjs.map → browser-Cp5W-dmj.mjs.map} +1 -1
  4. package/build/classify.d.mts +0 -2
  5. package/build/classify.mjs +1 -2
  6. package/build/{cli-daemon-kNj07eYU.mjs → cli-daemon-oSJWogkA.mjs} +3 -4
  7. package/build/{cli-daemon-kNj07eYU.mjs.map → cli-daemon-oSJWogkA.mjs.map} +1 -1
  8. package/build/{cli-recipes-DB3PgVig.mjs → cli-recipes-DVTMTQLx.mjs} +4 -5
  9. package/build/{cli-recipes-DB3PgVig.mjs.map → cli-recipes-DVTMTQLx.mjs.map} +1 -1
  10. package/build/cli.mjs +16 -19
  11. package/build/cli.mjs.map +1 -1
  12. package/build/{daemon-DePmNqn9.mjs → daemon-DNGSr4hR.mjs} +7 -13
  13. package/build/{daemon-DePmNqn9.mjs.map → daemon-DNGSr4hR.mjs.map} +1 -1
  14. package/build/{diff-Db1AmXuk.mjs → diff-ChsL3yux.mjs} +5 -12
  15. package/build/{diff-Db1AmXuk.mjs.map → diff-ChsL3yux.mjs.map} +1 -1
  16. package/build/{extract-D4J0D0IZ.mjs → extract-DO-NFOmF.mjs} +7 -12
  17. package/build/{extract-D4J0D0IZ.mjs.map → extract-DO-NFOmF.mjs.map} +1 -1
  18. package/build/hours.d.mts +0 -2
  19. package/build/hours.mjs +1 -2
  20. package/build/{html-Dir5QEi0.mjs → html-CawWTgMQ.mjs} +4 -6
  21. package/build/{html-Dir5QEi0.mjs.map → html-CawWTgMQ.mjs.map} +1 -1
  22. package/build/{html-o5bDHjNi.d.mts → html-oS_ueu9U.d.mts} +2 -20
  23. package/build/html.d.mts +2 -1
  24. package/build/html.mjs +2 -2
  25. package/build/index.d.mts +5 -72
  26. package/build/index.mjs +20 -19
  27. package/build/{log-CmBWcyQm.mjs → log-CB5bADmd.mjs} +3 -5
  28. package/build/{log-CmBWcyQm.mjs.map → log-CB5bADmd.mjs.map} +1 -1
  29. package/build/{mcp-package-Y0bREnOS.mjs → mcp-package-D9ACY0Ux.mjs} +2 -3
  30. package/build/{mcp-package-Y0bREnOS.mjs.map → mcp-package-D9ACY0Ux.mjs.map} +1 -1
  31. package/build/{ollama-D1xRh3hY.mjs → ollama-BDZjLDOK.mjs} +4 -10
  32. package/build/{ollama-D1xRh3hY.mjs.map → ollama-BDZjLDOK.mjs.map} +1 -1
  33. package/build/{open-EuCYPZVC.mjs → open-DOgE033K.mjs} +23 -40
  34. package/build/{open-EuCYPZVC.mjs.map → open-DOgE033K.mjs.map} +1 -1
  35. package/build/politeness.d.mts +0 -2
  36. package/build/politeness.mjs +1 -2
  37. package/build/{recipe-uLu2GLkr.mjs → recipe-BsGOZJyi.mjs} +5 -6
  38. package/build/{recipe-uLu2GLkr.mjs.map → recipe-BsGOZJyi.mjs.map} +1 -1
  39. package/build/{recipe-product-C_zv5j3z.mjs → recipe-product-DEDPKMY5.mjs} +7 -9
  40. package/build/{recipe-product-C_zv5j3z.mjs.map → recipe-product-DEDPKMY5.mjs.map} +1 -1
  41. package/build/{render-CKE2LILH.mjs → render-CZaqvjQh.mjs} +2 -3
  42. package/build/{render-CKE2LILH.mjs.map → render-CZaqvjQh.mjs.map} +1 -1
  43. package/build/robots.d.mts +0 -2
  44. package/build/robots.mjs +1 -2
  45. package/build/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
  46. package/build/{runtime-ByOn76mm.mjs → runtime-NyweI69B.mjs} +13 -20
  47. package/build/{runtime-ByOn76mm.mjs.map → runtime-NyweI69B.mjs.map} +1 -1
  48. package/build/signals.d.mts +0 -2
  49. package/build/signals.mjs +1 -2
  50. package/build/{transformers-BNiuiLxT.mjs → transformers-C_ziG8yf.mjs} +4 -9
  51. package/build/{transformers-BNiuiLxT.mjs.map → transformers-C_ziG8yf.mjs.map} +1 -1
  52. package/build/urls.d.mts +28 -0
  53. package/build/{urls-BHFeSyEK.mjs → urls.mjs} +3 -4
  54. package/build/urls.mjs.map +1 -0
  55. package/build/{version-D4u8ScwH.mjs → version-hVv3n9O6.mjs} +4 -6
  56. package/build/{version-D4u8ScwH.mjs.map → version-hVv3n9O6.mjs.map} +1 -1
  57. package/build/{wacz-DlGT0YXp.mjs → wacz-Blvh5qwS.mjs} +7 -9
  58. package/build/{wacz-DlGT0YXp.mjs.map → wacz-Blvh5qwS.mjs.map} +1 -1
  59. package/build/{warc-Cq3gO3NK.mjs → warc-DiE1M5le.mjs} +7 -17
  60. package/build/{warc-Cq3gO3NK.mjs.map → warc-DiE1M5le.mjs.map} +1 -1
  61. package/build/{webbotauth-Dq_dA_u3.mjs → webbotauth-W3GXY3dy.mjs} +4 -11
  62. package/build/{webbotauth-Dq_dA_u3.mjs.map → webbotauth-W3GXY3dy.mjs.map} +1 -1
  63. package/package.json +5 -1
  64. package/build/urls-BHFeSyEK.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"warc-Cq3gO3NK.mjs","names":[],"sources":["../src/zip.ts","../src/warc.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport { open, stat } from \"node:fs/promises\";\nimport { pipeline } from \"node:stream/promises\";\nimport * as zlib from \"node:zlib\";\n\n/*\n * This module writes a ZIP file with node:zlib only. The WACZ export uses it. It is not part of the\n * API of the package.\n *\n * - A member is stored (method 0) or deflated (method 8).\n * - The writer knows the CRC-32 and the sizes of each member before it writes the member. Thus the\n * local headers hold the true values, and the file has no data descriptors.\n * - The writer adds the Zip64 records only when a size, an offset or the count of members is too\n * large for the fields of 32 bits. The option `zip64: \"always\"` adds them in each case, for a test.\n */\n\nconst TABLE: Uint32Array = (() => {\n const table = new Uint32Array(256);\n for (let n = 0; n < 256; n += 1) {\n let c = n;\n for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n return table;\n})();\n\n/** This function calculates the CRC-32 of ISO 3309 with a table. It is the fallback of `crc32`. */\nexport const tableCrc32 = (bytes: Uint8Array, value = 0): number => {\n let crc = ~value >>> 0;\n for (const byte of bytes) crc = TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);\n return ~crc >>> 0;\n};\n\nconst native = (zlib as { readonly crc32?: (data: Uint8Array, value?: number) => number }).crc32;\n\n/** This function calculates the CRC-32 of the bytes. It continues from `value`. It uses `zlib.crc32` when Node.js has it. */\nexport const crc32 = (bytes: Uint8Array, value = 0): number =>\n native === undefined ? tableCrc32(bytes, value) : native(bytes, value);\n\n/** These are the facts of a file that a tally gives at its close. */\nexport interface Tallied {\n readonly path: string;\n readonly size: number;\n readonly crc: number;\n /** This value is the SHA-256 of the bytes, as hexadecimal digits. */\n readonly sha256: string;\n}\n\n/** This function writes the whole buffer. A write can write less than the buffer, and the loop writes the rest. */\nexport const writeAll = async (handle: FileHandle, bytes: Uint8Array): Promise<void> => {\n let at = 0;\n while (at < bytes.length) {\n const { bytesWritten } = await handle.write(bytes, at, bytes.length - at);\n at += bytesWritten;\n }\n};\n\n/** A tally writes a new file in sequence. It counts the bytes and calculates their CRC-32 and SHA-256. */\nexport class TalliedFile {\n private readonly hash = createHash(\"sha256\");\n private crcValue = 0;\n private count = 0;\n\n private constructor(\n readonly path: string,\n private readonly handle: FileHandle,\n ) {}\n\n /** This method makes a new file. It fails when the file exists. */\n static async create(path: string): Promise<TalliedFile> {\n return new TalliedFile(path, await open(path, \"wx\", 0o600));\n }\n\n /** This value is the count of bytes that the tally wrote. It is the offset of the next write. */\n get size(): number {\n return this.count;\n }\n\n async write(bytes: Uint8Array): Promise<void> {\n await writeAll(this.handle, bytes);\n this.hash.update(bytes);\n this.crcValue = crc32(bytes, this.crcValue);\n this.count += bytes.length;\n }\n\n /** This method closes the file and gives its facts. */\n async close(): Promise<Tallied> {\n await this.handle.close();\n return {\n path: this.path,\n size: this.count,\n crc: this.crcValue,\n sha256: this.hash.digest(\"hex\"),\n };\n }\n\n /** This method closes the file after an error. It gives no facts. */\n async abandon(): Promise<void> {\n await this.handle.close().catch(() => undefined);\n }\n}\n\n/** This function deflates a file into a new file (raw deflate, as ZIP needs it). It gives the size of the new file. */\nexport const deflateFile = async (from: string, to: string): Promise<number> => {\n await pipeline(\n createReadStream(from),\n zlib.createDeflateRaw(),\n createWriteStream(to, { flags: \"wx\", mode: 0o600 }),\n );\n return (await stat(to)).size;\n};\n\n/** A member of a ZIP file. Its bytes are in a file or in memory, as the ZIP stores them. */\nexport interface ZipMember {\n /** This value is the path of the member in the ZIP file. */\n readonly name: string;\n /** The value 0 stores the bytes. The value 8 holds deflated bytes. */\n readonly method: 0 | 8;\n /** This value is the CRC-32 of the bytes before compression. */\n readonly crc: number;\n /** This value is the count of bytes before compression. */\n readonly size: number;\n /** This value is the count of bytes in the ZIP file. */\n readonly compressedSize: number;\n /** This file holds the bytes as the ZIP stores them. */\n readonly file?: string | undefined;\n /** These bytes are the member as the ZIP stores them, when `file` is not given. */\n readonly data?: Uint8Array | undefined;\n}\n\n/** This function makes a member from bytes in memory. A member of method 8 holds the bytes deflated. */\nexport const memberOf = (name: string, bytes: Uint8Array, method: 0 | 8 = 8): ZipMember => {\n const data = method === 8 ? zlib.deflateRawSync(bytes) : bytes;\n return {\n name,\n method,\n crc: crc32(bytes),\n size: bytes.length,\n compressedSize: data.length,\n data,\n };\n};\n\n/** These options change a ZIP file. */\nexport interface ZipOptions {\n /** This time goes into each member, in the MS-DOS format of ZIP (UTC, to 2 seconds). */\n readonly date: Date;\n /** The value `auto` (the default) adds the Zip64 records only when they are necessary. */\n readonly zip64?: \"auto\" | \"always\" | undefined;\n}\n\nconst MAX32 = 0xffffffff;\nconst MAX16 = 0xffff;\nconst VERSION_ZIP = 20;\nconst VERSION_ZIP64 = 45;\n/** The member was made on Unix (3), with version 4.5 of the specification. */\nconst MADE_BY = (3 << 8) | VERSION_ZIP64;\n/** A plain file that its owner can read and write, and the others can read (`0o100644`). */\nconst FILE_MODE = (0o100644 << 16) >>> 0;\n/** Bit 11 of the flags tells that the name is UTF-8. */\nconst UTF8_NAMES = 0x0800;\n\nconst dosTime = (date: Date): { readonly time: number; readonly day: number } => {\n const year = Math.min(Math.max(date.getUTCFullYear(), 1980), 2107);\n return {\n time: (date.getUTCHours() << 11) | (date.getUTCMinutes() << 5) | (date.getUTCSeconds() >> 1),\n day: ((year - 1980) << 9) | ((date.getUTCMonth() + 1) << 5) | date.getUTCDate(),\n };\n};\n\n/** This function makes the Zip64 extra field (id 0x0001) with these values of 64 bits. */\nconst zip64Extra = (values: readonly number[]): Buffer => {\n const extra = Buffer.alloc(4 + 8 * values.length);\n extra.writeUInt16LE(0x0001, 0);\n extra.writeUInt16LE(8 * values.length, 2);\n values.forEach((value, at) => extra.writeBigUInt64LE(BigInt(value), 4 + 8 * at));\n return extra;\n};\n\n/**\n * This function writes a ZIP file with these members, in this sequence. It writes a new file and\n * fails when the file exists. It gives the size of the ZIP file.\n */\nexport const writeZip = async (\n target: string,\n members: readonly ZipMember[],\n options: ZipOptions,\n): Promise<number> => {\n const always = options.zip64 === \"always\";\n const { time, day } = dosTime(options.date);\n const handle = await open(target, \"wx\", 0o600);\n let offset = 0;\n const put = async (bytes: Uint8Array): Promise<void> => {\n await writeAll(handle, bytes);\n offset += bytes.length;\n };\n try {\n const central: Buffer[] = [];\n for (const member of members) {\n const name = Buffer.from(member.name, \"utf8\");\n const start = offset;\n const bigSizes = always || member.size >= MAX32 || member.compressedSize >= MAX32;\n const localExtra = bigSizes\n ? zip64Extra([member.size, member.compressedSize])\n : Buffer.alloc(0);\n const local = Buffer.alloc(30);\n local.writeUInt32LE(0x04034b50, 0);\n local.writeUInt16LE(bigSizes ? VERSION_ZIP64 : VERSION_ZIP, 4);\n local.writeUInt16LE(UTF8_NAMES, 6);\n local.writeUInt16LE(member.method, 8);\n local.writeUInt16LE(time, 10);\n local.writeUInt16LE(day, 12);\n local.writeUInt32LE(member.crc >>> 0, 14);\n local.writeUInt32LE(bigSizes ? MAX32 : member.compressedSize, 18);\n local.writeUInt32LE(bigSizes ? MAX32 : member.size, 22);\n local.writeUInt16LE(name.length, 26);\n local.writeUInt16LE(localExtra.length, 28);\n await put(local);\n await put(name);\n await put(localExtra);\n const before = offset;\n if (member.file !== undefined) {\n for await (const chunk of createReadStream(member.file) as AsyncIterable<Buffer>)\n await put(chunk);\n } else await put(member.data ?? new Uint8Array());\n if (offset - before !== member.compressedSize)\n throw new Error(\n `the member ${member.name} has ${String(offset - before)} bytes, not ${String(member.compressedSize)}`,\n );\n\n // the central header names only the values that are too large, in this sequence\n const bigSize = always || member.size >= MAX32;\n const bigCompressed = always || member.compressedSize >= MAX32;\n const bigOffset = always || start >= MAX32;\n const values = [\n ...(bigSize ? [member.size] : []),\n ...(bigCompressed ? [member.compressedSize] : []),\n ...(bigOffset ? [start] : []),\n ];\n const extra = values.length > 0 ? zip64Extra(values) : Buffer.alloc(0);\n const header = Buffer.alloc(46);\n header.writeUInt32LE(0x02014b50, 0);\n header.writeUInt16LE(MADE_BY, 4);\n header.writeUInt16LE(values.length > 0 ? VERSION_ZIP64 : VERSION_ZIP, 6);\n header.writeUInt16LE(UTF8_NAMES, 8);\n header.writeUInt16LE(member.method, 10);\n header.writeUInt16LE(time, 12);\n header.writeUInt16LE(day, 14);\n header.writeUInt32LE(member.crc >>> 0, 16);\n header.writeUInt32LE(bigCompressed ? MAX32 : member.compressedSize, 20);\n header.writeUInt32LE(bigSize ? MAX32 : member.size, 24);\n header.writeUInt16LE(name.length, 28);\n header.writeUInt16LE(extra.length, 30);\n header.writeUInt16LE(0, 32);\n header.writeUInt16LE(0, 34);\n header.writeUInt16LE(0, 36);\n header.writeUInt32LE(FILE_MODE, 38);\n header.writeUInt32LE(bigOffset ? MAX32 : start, 42);\n central.push(header, name, extra);\n }\n\n const centralStart = offset;\n for (const part of central) await put(part);\n const centralSize = offset - centralStart;\n const count = members.length;\n const zip64End = always || count >= MAX16 || centralStart >= MAX32 || centralSize >= MAX32;\n if (zip64End) {\n const recordAt = offset;\n const record = Buffer.alloc(56);\n record.writeUInt32LE(0x06064b50, 0);\n record.writeBigUInt64LE(44n, 4);\n record.writeUInt16LE(MADE_BY, 12);\n record.writeUInt16LE(VERSION_ZIP64, 14);\n record.writeUInt32LE(0, 16);\n record.writeUInt32LE(0, 20);\n record.writeBigUInt64LE(BigInt(count), 24);\n record.writeBigUInt64LE(BigInt(count), 32);\n record.writeBigUInt64LE(BigInt(centralSize), 40);\n record.writeBigUInt64LE(BigInt(centralStart), 48);\n await put(record);\n const locator = Buffer.alloc(20);\n locator.writeUInt32LE(0x07064b50, 0);\n locator.writeUInt32LE(0, 4);\n locator.writeBigUInt64LE(BigInt(recordAt), 8);\n locator.writeUInt32LE(1, 16);\n await put(locator);\n }\n const end = Buffer.alloc(22);\n end.writeUInt32LE(0x06054b50, 0);\n end.writeUInt16LE(0, 4);\n end.writeUInt16LE(0, 6);\n end.writeUInt16LE(zip64End ? MAX16 : count, 8);\n end.writeUInt16LE(zip64End ? MAX16 : count, 10);\n end.writeUInt32LE(zip64End ? MAX32 : centralSize, 12);\n end.writeUInt32LE(zip64End ? MAX32 : centralStart, 16);\n end.writeUInt16LE(0, 20);\n await put(end);\n } finally {\n await handle.close();\n }\n return offset;\n};\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { rename, rm } from \"node:fs/promises\";\nimport { STATUS_CODES } from \"node:http\";\nimport { basename, join, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gzip } from \"node:zlib\";\nimport type { BlobStore } from \"./blobs.ts\";\nimport { FileBlobStore } from \"./blobs.ts\";\nimport type { CaptureReader } from \"./log.ts\";\nimport { CaptureLog } from \"./log.ts\";\nimport type { CaptureRecord } from \"./record.ts\";\nimport { BOT_PAGE, VERSION } from \"./version.ts\";\nimport { TalliedFile } from \"./zip.ts\";\n\n/*\n * This module writes the capture log as WARC/1.1 (ISO 28500:2017). The README tells what goes into\n * the archive and why. These are the records:\n *\n * - One `warcinfo` record names the software and the filters of the export.\n * - A capture with a body gives a `response` record. Its HTTP header block is rebuilt from the\n * headers that the capture kept, and its payload is the stored body.\n * - A 304 gives a `revisit` record with the profile `server-not-modified`.\n * - A page that the headless browser rendered gives a `conversion` record: the page after\n * JavaScript, not the body that the server sent.\n * - Each of them has a `metadata` record (`WARC-Concurrent-To`) with the JSON of the capture.\n *\n * Each record is one gzip member. The export reads the log as a stream and holds one body at a time.\n */\n\nconst gzipAsync = promisify(gzip);\n\nconst HOME = new URL(\"../\", BOT_PAGE).href;\nconst CRLF = \"\\r\\n\";\nconst END = Buffer.from(\"\\r\\n\\r\\n\", \"latin1\");\nconst KINDS: ReadonlySet<string> = new Set([\"capture\", \"revisit\", \"skipped\"]);\nconst HASH = /^[0-9a-f]{64}$/;\n/** The revisit records name their original from this count of recent responses. */\nconst ORIGINALS = 65_536;\nconst SERVER_NOT_MODIFIED = \"http://netpreserve.org/warc/1.1/revisit/server-not-modified\";\nconst HTTP_RESPONSE = \"application/http; msgtype=response\";\n\n/** The source of an export: the folder of a store, or the capture log and the blob store of a runtime. */\nexport type ArchiveSource =\n string | { readonly captures: CaptureReader; readonly blobs: BlobStore };\n\n/** These filters select the captures of an export. Each filter that you give makes the selection smaller. */\nexport interface ArchiveFilter {\n /** The export holds the captures received at this time or later. */\n readonly since?: string | Date | undefined;\n /** The export holds the captures received before this time. */\n readonly until?: string | Date | undefined;\n /** The export holds the captures of this host and of its subdomains, for example `example.com`. */\n readonly host?: string | undefined;\n /** The export holds the captures whose URL starts with this text. */\n readonly urlPrefix?: string | undefined;\n /** The export holds only the captures with these ids. */\n readonly ids?: readonly string[] | undefined;\n}\n\n/** These options control an export. Only `out` is necessary. */\nexport interface ArchiveOptions extends ArchiveFilter {\n /** This file gets the archive. The export writes a temporary file and gives it this name at the end. */\n readonly out: string;\n /**\n * When this value is true, each capture with no body (a refusal, a skip of robots.txt, an error, a\n * redirect) gets a `metadata` record. The default is false: the export leaves them out.\n */\n readonly includeRefusals?: boolean | undefined;\n /** When this value is true, the export replaces a file that exists. The default is false: the export fails. */\n readonly overwrite?: boolean | undefined;\n}\n\n/** These counts tell what an export wrote. */\nexport interface ArchiveCounts {\n /** This value is the count of capture records that the filters selected. */\n readonly captures: number;\n readonly responses: number;\n readonly revisits: number;\n /** This value is the count of rendered pages (`conversion` records). */\n readonly conversions: number;\n readonly metadata: number;\n /** This value is the count of captures with no body: refusals, skips, errors and redirects. */\n readonly bodiless: number;\n /** This value is the count of captures whose body is not in the blob store, or does not agree with its hash. */\n readonly missing: number;\n /** This value is the count of damaged lines of the capture log. */\n readonly damaged: number;\n}\n\n/** This is the result of `exportWarc`. */\nexport interface WarcResult extends ArchiveCounts {\n readonly format: \"warc\";\n /** This value is the absolute path of the archive. */\n readonly out: string;\n readonly bytes: number;\n}\n\n/** These are the facts of a `response` or `revisit` record that the index of a WACZ file needs. */\nexport interface ArchivedRecord {\n readonly type: \"response\" | \"revisit\";\n readonly url: string;\n readonly date: string;\n readonly status: number;\n readonly mime: string;\n readonly digest: string;\n readonly offset: number;\n readonly length: number;\n readonly capture: string;\n /** This value is true for a page of the page list: a 200 response that is not a robots.txt file. */\n readonly page: boolean;\n}\n\n/** A plan is a valid filter and an open source. An export makes it before it writes a file. */\nexport interface ArchivePlan {\n readonly captures: CaptureReader;\n readonly blobs: BlobStore;\n readonly filter: ArchiveSelection;\n readonly includeRefusals: boolean;\n}\n\n/** This is a filter after the checks: times in ISO 8601, a lowercase host and a set of ids. */\nexport interface ArchiveSelection {\n readonly since?: string | undefined;\n readonly until?: string | undefined;\n readonly host?: string | undefined;\n readonly urlPrefix?: string | undefined;\n readonly ids?: ReadonlySet<string> | undefined;\n}\n\nconst RFC4648 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n\n/** This function writes bytes in base 32 (RFC 4648), with capitals and padding. WARC tools write SHA-256 digests in this form. */\nexport const base32 = (bytes: Uint8Array): string => {\n let out = \"\";\n let value = 0;\n let bits = 0;\n for (const byte of bytes) {\n value = ((value << 8) | byte) & 0xffff;\n bits += 8;\n while (bits >= 5) {\n out += RFC4648[(value >>> (bits - 5)) & 31]!;\n bits -= 5;\n }\n }\n if (bits > 0) out += RFC4648[(value << (5 - bits)) & 31]!;\n while (out.length % 8 !== 0) out += \"=\";\n return out;\n};\n\nconst digestOf = (bytes: Uint8Array): string => `sha256:${base32(bytes)}`;\n\nconst sha256Of = (...parts: readonly Uint8Array[]): Buffer => {\n const hash = createHash(\"sha256\");\n for (const part of parts) hash.update(part);\n return hash.digest();\n};\n\n/** This function gives a version 5 UUID (RFC 9562): the SHA-1 of a namespace and a name. */\nconst uuidV5 = (namespace: string, name: string): string => {\n const hash = createHash(\"sha1\")\n .update(Buffer.from(namespace.replace(/-/g, \"\"), \"hex\"))\n .update(name, \"utf8\")\n .digest();\n hash[6] = (hash[6]! & 0x0f) | 0x50;\n hash[8] = (hash[8]! & 0x3f) | 0x80;\n const hex = hash.subarray(0, 16).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n};\n\n/** The namespace of the record ids: a UUID of the URL of the site, in the URL namespace of RFC 9562. */\nconst NAMESPACE = uuidV5(\"6ba7b811-9dad-11d1-80b4-00c04fd430c8\", HOME);\n\n/** The id of a record of a capture is the same at each export: it comes from the hash of the capture. */\nconst recordId = (record: CaptureRecord, type: string): string =>\n `<urn:uuid:${uuidV5(NAMESPACE, `${record.content_hash || `${record.id}@${record.received_at}`}/${type}`)}>`;\n\n/** A field of a header holds no line break. */\nconst clean = (value: string): string => value.replace(/[\\r\\n]+/g, \" \").trim();\n\n/** This function gives one record: the WARC header, the block and the two line breaks at the end. */\nconst recordBytes = (\n fields: ReadonlyArray<readonly [string, string]>,\n block: readonly Uint8Array[],\n): Buffer => {\n const length = block.reduce((sum, part) => sum + part.length, 0);\n const head = [\n \"WARC/1.1\",\n ...fields.map(([name, value]) => `${name}: ${clean(value)}`),\n `Content-Length: ${String(length)}`,\n \"\",\n \"\",\n ].join(CRLF);\n return Buffer.concat([Buffer.from(head, \"utf8\"), ...block, END]);\n};\n\n/**\n * This function gives an HTTP status line and header block. HTTP headers are Latin-1 bytes, and\n * undici gives each byte as one character. Thus the block gives back the bytes that the server sent.\n */\nconst httpHead = (status: number, headers: ReadonlyArray<readonly [string, string]>): Buffer =>\n Buffer.from(\n [\n `HTTP/1.1 ${String(status)} ${STATUS_CODES[status] ?? \"Unknown\"}`,\n ...headers.map(([name, value]) => `${name}: ${clean(value)}`),\n \"\",\n \"\",\n ].join(CRLF),\n \"latin1\",\n );\n\n/** These fields of a capture keep a header of the response. */\nconst KEPT_HEADERS: ReadonlyArray<readonly [string, string]> = [\n [\"etag\", \"ETag\"],\n [\"last_modified\", \"Last-Modified\"],\n [\"cache_control\", \"Cache-Control\"],\n [\"expires\", \"Expires\"],\n [\"age\", \"Age\"],\n [\"date\", \"Date\"],\n [\"vary\", \"Vary\"],\n];\n\n/** These are the facts of a fetch record that the export reads. */\ninterface Facts {\n readonly url: string;\n readonly date: string;\n readonly status: number | undefined;\n readonly blob: string | undefined;\n readonly contentType: string | undefined;\n readonly rendered: boolean;\n readonly truncated: boolean;\n readonly cut: boolean;\n readonly revisitOf: string | undefined;\n readonly recipe: string | undefined;\n readonly headers: ReadonlyArray<readonly [string, string]>;\n}\n\nconst text = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/** This function gives the time of a capture in ISO 8601, with milliseconds. WARC/1.1 permits them. */\nconst isoOf = (value: unknown, fallback: string): string => {\n const ms = typeof value === \"string\" ? Date.parse(value) : Number.NaN;\n if (Number.isFinite(ms)) return new Date(ms).toISOString();\n const other = Date.parse(fallback);\n return Number.isFinite(other) ? new Date(other).toISOString() : fallback;\n};\n\nconst factsOf = (record: CaptureRecord): Facts | undefined => {\n const payload = record.payload;\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const fields = payload as Readonly<Record<string, unknown>>;\n const url = text(fields[\"url\"]) ?? text(record.external_id);\n if (url === undefined) return undefined;\n const blob = text(fields[\"blob\"]);\n const status = fields[\"status\"];\n return {\n url,\n date: isoOf(fields[\"fetched_at\"], record.received_at),\n status: typeof status === \"number\" && Number.isInteger(status) ? status : undefined,\n blob: blob !== undefined && HASH.test(blob) ? blob : undefined,\n contentType: text(fields[\"content_type\"]),\n rendered: fields[\"rendered\"] === true,\n truncated: fields[\"truncated\"] === true,\n cut: fields[\"cut\"] === true,\n revisitOf: text(fields[\"revisit_of\"]),\n recipe: text(fields[\"recipe\"]),\n headers: KEPT_HEADERS.flatMap(([field, name]) => {\n const value = text(fields[field]);\n return value === undefined ? [] : [[name, value] as const];\n }),\n };\n};\n\nconst timeOf = (name: string, value: string | Date | undefined): string | undefined => {\n if (value === undefined) return undefined;\n const ms = value instanceof Date ? value.getTime() : Date.parse(value);\n if (!Number.isFinite(ms)) throw new RangeError(`${name} is not a time: \"${String(value)}\"`);\n return new Date(ms).toISOString();\n};\n\nconst hostName = (value: string): string | undefined => {\n try {\n return new URL(value).hostname.toLowerCase().replace(/\\.$/, \"\");\n } catch {\n return undefined;\n }\n};\n\nconst filterOf = (options: ArchiveFilter): ArchiveSelection => {\n const since = timeOf(\"since\", options.since);\n const until = timeOf(\"until\", options.until);\n let host: string | undefined;\n if (options.host !== undefined) {\n host = options.host.trim().toLowerCase().replace(/^\\*\\./, \"\").replace(/\\.$/, \"\");\n if (host === \"\" || /[/:@\\s]/.test(host))\n throw new RangeError(`host is a host name, for example example.com, not \"${options.host}\"`);\n }\n return {\n since,\n until,\n host,\n urlPrefix: options.urlPrefix === \"\" ? undefined : options.urlPrefix,\n ids: options.ids === undefined ? undefined : new Set(options.ids),\n };\n};\n\nconst selected = (record: CaptureRecord, facts: Facts, filter: ArchiveSelection): boolean => {\n if (filter.since !== undefined && record.received_at < filter.since) return false;\n if (filter.until !== undefined && record.received_at >= filter.until) return false;\n if (filter.urlPrefix !== undefined && !facts.url.startsWith(filter.urlPrefix)) return false;\n if (filter.ids !== undefined && !filter.ids.has(record.id)) return false;\n if (filter.host !== undefined) {\n const host = hostName(facts.url);\n if (host === undefined || (host !== filter.host && !host.endsWith(`.${filter.host}`)))\n return false;\n }\n return true;\n};\n\n/**\n * This function checks the filters and opens the source. It writes nothing. A folder must hold a\n * capture log, and the export does not make a store.\n */\nexport const planArchive = (source: ArchiveSource, options: ArchiveOptions): ArchivePlan => {\n const filter = filterOf(options);\n const includeRefusals = options.includeRefusals === true;\n if (typeof source !== \"string\") {\n return { captures: source.captures, blobs: source.blobs, filter, includeRefusals };\n }\n const dir = resolve(source);\n if (!existsSync(join(dir, \"captures\")))\n throw new Error(`the store ${dir} has no capture log (captures/)`);\n return {\n captures: new CaptureLog(join(dir, \"captures\"), { sync: false }),\n blobs: new FileBlobStore(join(dir, \"blobs\"), { sync: false }),\n filter,\n includeRefusals,\n };\n};\n\n/** This function gives the path of the archive and of its temporary file. It fails when the archive exists, unless `overwrite` is true. */\nexport const outputOf = (\n options: ArchiveOptions,\n): { readonly target: string; readonly temporary: string } => {\n if (typeof options.out !== \"string\" || options.out.trim() === \"\")\n throw new Error(\"an export needs out: the file of the archive\");\n const target = resolve(options.out);\n if (options.overwrite !== true && existsSync(target))\n throw new Error(`${target} exists: give a different file, or set overwrite`);\n return { target, temporary: `${target}.${randomUUID()}.tmp` };\n};\n\n/** This function reads a body from the blob store. It gives no body when the bytes do not agree with the hash. */\nconst bodyOf = async (\n blobs: BlobStore,\n hash: string,\n): Promise<{ readonly bytes: Uint8Array; readonly digest: Buffer } | undefined> => {\n let bytes: Uint8Array | undefined;\n try {\n bytes = await blobs.get(hash);\n } catch {\n return undefined;\n }\n if (bytes === undefined) return undefined;\n const digest = sha256Of(bytes);\n return digest.toString(\"hex\") === hash ? { bytes, digest } : undefined;\n};\n\nconst mimeOf = (contentType: string | undefined): string =>\n contentType?.split(\";\")[0]?.trim().toLowerCase() || \"-\";\n\n/** This function gives the JSON of the metadata record of a capture. The labels and the scope of the application stay out. */\nconst metadataOf = (record: CaptureRecord, written: Readonly<Record<string, string>>): Buffer =>\n Buffer.from(\n `${JSON.stringify({\n capture: {\n id: record.id,\n source: record.source,\n kind: record.kind,\n ...(record.external_id !== undefined ? { external_id: record.external_id } : {}),\n ...(record.occurred_at !== undefined ? { occurred_at: record.occurred_at } : {}),\n received_at: record.received_at,\n content_hash: record.content_hash,\n payload: record.payload,\n },\n export: written,\n })}\\n`,\n \"utf8\",\n );\n\n/**\n * This function writes the records of an archive into a file: the `warcinfo` record, then the\n * records of each capture that the plan selects. It gives the facts of each `response` and\n * `revisit` record to `onRecord`, for the index of a WACZ file.\n */\nexport const writeArchive = async (\n plan: ArchivePlan,\n file: TalliedFile,\n filename: string,\n onRecord?: (record: ArchivedRecord) => Promise<void>,\n): Promise<ArchiveCounts> => {\n const counts = {\n captures: 0,\n responses: 0,\n revisits: 0,\n conversions: 0,\n metadata: 0,\n bodiless: 0,\n missing: 0,\n damaged: 0,\n };\n const { filter } = plan;\n const put = async (\n bytes: Buffer,\n ): Promise<{ readonly offset: number; readonly length: number }> => {\n const member = await gzipAsync(bytes);\n const offset = file.size;\n await file.write(member);\n return { offset, length: member.length };\n };\n\n const info = `<urn:uuid:${randomUUID()}>`;\n const shown = Object.fromEntries(\n Object.entries({\n since: filter.since,\n until: filter.until,\n host: filter.host,\n url_prefix: filter.urlPrefix,\n ids: filter.ids === undefined ? undefined : filter.ids.size,\n include_refusals: plan.includeRefusals,\n }).filter(([, value]) => value !== undefined),\n );\n const fields = [\n `software: polite-crawler/${VERSION} (+${HOME})`,\n \"format: WARC File Format 1.1\",\n \"conformsTo: https://iipc.github.io/warc-specifications/specifications/warc-format/warc-1.1/\",\n \"robots: obey\",\n \"description: An export of the capture log of polite-crawler. The HTTP headers of each response are rebuilt from the headers that the capture kept.\",\n `polite-crawler-filter: ${JSON.stringify(shown)}`,\n ];\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"warcinfo\"],\n [\"WARC-Record-ID\", info],\n [\"WARC-Date\", new Date().toISOString()],\n [\"WARC-Filename\", filename],\n [\"Content-Type\", \"application/warc-fields\"],\n ],\n [Buffer.from(`${fields.join(CRLF)}${CRLF}`, \"utf8\")],\n ),\n );\n\n // a revisit names its original when the original is one of the recent responses of the export\n const originals = new Map<\n string,\n { readonly id: string; readonly date: string; readonly url: string }\n >();\n const remember = (\n capture: string,\n original: { readonly id: string; readonly date: string; readonly url: string },\n ): void => {\n originals.delete(capture);\n originals.set(capture, original);\n if (originals.size > ORIGINALS) originals.delete(originals.keys().next().value!);\n };\n\n const scan = plan.captures.scan(\n { source: \"fetch\", since: filter.since },\n { onDamaged: () => void (counts.damaged += 1) },\n );\n for await (const record of scan) {\n if (record.source !== \"fetch\" || !KINDS.has(record.kind)) continue;\n const facts = factsOf(record);\n if (facts === undefined || !selected(record, facts, filter)) continue;\n counts.captures += 1;\n const common: Array<readonly [string, string]> = [\n [\"WARC-Date\", facts.date],\n [\"WARC-Target-URI\", facts.url],\n [\"WARC-Warcinfo-ID\", info],\n ];\n const vendor: Array<readonly [string, string]> = [[\"WARC-Polite-Crawler-Capture\", record.id]];\n let main: string | undefined;\n let written: Record<string, string> = { record: \"none\", reason: \"no body\" };\n\n if (record.kind === \"revisit\" && facts.blob !== undefined) {\n // the 304 confirmed the stored body, so the payload digest is the digest of that body\n const original = facts.revisitOf === undefined ? undefined : originals.get(facts.revisitOf);\n const head = httpHead(304, [\n ...(facts.contentType !== undefined ? [[\"Content-Type\", facts.contentType] as const] : []),\n ...facts.headers,\n ]);\n const digest = digestOf(Buffer.from(facts.blob, \"hex\"));\n main = recordId(record, \"revisit\");\n const at = await put(\n recordBytes(\n [\n [\"WARC-Type\", \"revisit\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Profile\", SERVER_NOT_MODIFIED],\n ...(original !== undefined ? [[\"WARC-Refers-To\", original.id] as const] : []),\n [\"WARC-Refers-To-Target-URI\", original?.url ?? facts.url],\n ...(original !== undefined ? [[\"WARC-Refers-To-Date\", original.date] as const] : []),\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digestOf(sha256Of(head))],\n ...vendor,\n [\"WARC-Polite-Crawler-Headers\", \"rebuilt\"],\n [\"Content-Type\", HTTP_RESPONSE],\n ],\n [head],\n ),\n );\n counts.revisits += 1;\n written = { record: \"revisit\", http_headers: \"rebuilt\" };\n await onRecord?.({\n type: \"revisit\",\n url: facts.url,\n date: facts.date,\n status: 304,\n mime: \"warc/revisit\",\n digest,\n ...at,\n capture: record.id,\n page: false,\n });\n } else if (record.kind === \"capture\" && facts.blob !== undefined) {\n const body = await bodyOf(plan.blobs, facts.blob);\n if (body === undefined) {\n counts.missing += 1;\n written = { record: \"none\", reason: \"body missing\" };\n } else if (facts.rendered) {\n // the page after JavaScript is a conversion of the page, not the body that the server sent\n const digest = digestOf(body.digest);\n main = recordId(record, \"conversion\");\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"conversion\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digest],\n ...vendor,\n [\"Content-Type\", facts.contentType ?? \"text/html; charset=utf-8\"],\n ],\n [body.bytes],\n ),\n );\n counts.conversions += 1;\n written = { record: \"conversion\", body: \"rendered\" };\n } else if (facts.status !== undefined && facts.status >= 100 && facts.status <= 999) {\n const head = httpHead(facts.status, [\n ...(facts.contentType !== undefined\n ? [[\"Content-Type\", facts.contentType] as const]\n : []),\n [\"Content-Length\", String(body.bytes.length)],\n ...facts.headers,\n ]);\n const digest = digestOf(body.digest);\n main = recordId(record, \"response\");\n // a body that the crawler cut at its limit, or that ended early, says so\n const truncated = facts.cut ? \"disconnect\" : facts.truncated ? \"length\" : undefined;\n const at = await put(\n recordBytes(\n [\n [\"WARC-Type\", \"response\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digestOf(sha256Of(head, body.bytes))],\n ...(truncated !== undefined ? [[\"WARC-Truncated\", truncated] as const] : []),\n ...vendor,\n [\"WARC-Polite-Crawler-Headers\", \"rebuilt\"],\n [\"Content-Type\", HTTP_RESPONSE],\n ],\n [head, body.bytes],\n ),\n );\n counts.responses += 1;\n written = { record: \"response\", http_headers: \"rebuilt\", body: \"decoded\" };\n remember(record.id, { id: main, date: facts.date, url: facts.url });\n await onRecord?.({\n type: \"response\",\n url: facts.url,\n date: facts.date,\n status: facts.status,\n mime: mimeOf(facts.contentType),\n digest,\n ...at,\n capture: record.id,\n page: facts.status === 200 && facts.recipe !== \"robots.txt\",\n });\n }\n }\n\n if (main === undefined) {\n if (written[\"reason\"] === \"no body\") counts.bodiless += 1;\n if (!plan.includeRefusals) continue;\n }\n const block = metadataOf(record, written);\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"metadata\"],\n [\"WARC-Record-ID\", recordId(record, \"metadata\")],\n ...common,\n ...(main !== undefined ? [[\"WARC-Concurrent-To\", main] as const] : []),\n [\"WARC-Block-Digest\", digestOf(sha256Of(block))],\n ...vendor,\n [\"Content-Type\", \"application/json\"],\n ],\n [block],\n ),\n );\n counts.metadata += 1;\n }\n return counts;\n};\n\n/**\n * This function gives the SURT key of a URL, as `pywb` and the `surt` library make it with their\n * defaults. The host is reversed with commas and has no `www.` and no default port. The path\n * and the query are lowercase, the path has no slash at the end, and the parts of the query are\n * sorted.\n */\nexport const surt = (value: string): string => {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return value.toLowerCase();\n }\n const host = url.hostname\n .toLowerCase()\n .replace(/\\.$/, \"\")\n .replace(/^www\\d*\\./, \"\");\n const key = host.startsWith(\"[\") ? host : host.split(\".\").reverse().join(\",\");\n let path = url.pathname.toLowerCase();\n if (path.length > 1 && path.endsWith(\"/\")) path = path.slice(0, -1);\n const query = url.search.slice(1).toLowerCase().split(\"&\").filter(Boolean).sort().join(\"&\");\n return `${key}${url.port === \"\" ? \"\" : `:${url.port}`})${path}${query === \"\" ? \"\" : `?${query}`}`;\n};\n\n/** This function gives the line of a record in a CDXJ index: the SURT key, the time to the second, and JSON. */\nexport const cdxjLine = (record: ArchivedRecord, filename: string): string =>\n `${surt(record.url)} ${record.date.slice(0, 19).replace(/\\D/g, \"\")} ${JSON.stringify({\n url: record.url,\n mime: record.mime,\n status: String(record.status),\n digest: record.digest,\n length: String(record.length),\n offset: String(record.offset),\n filename,\n })}`;\n\n/**\n * This function writes the captures of a store as a WARC/1.1 file, with one gzip member for each\n * record (`.warc.gz`). It reads the capture log as a stream, so its memory does not grow with the\n * store. It writes a temporary file and gives it the name `out` at the end, so a failed export\n * leaves no part of a file.\n *\n * The source is the folder of a store, or the capture log and the blob store of a runtime\n * (`crawler.runtime`). The export only reads the store.\n */\nexport const exportWarc = async (\n source: ArchiveSource,\n options: ArchiveOptions,\n): Promise<WarcResult> => {\n const plan = planArchive(source, options);\n const { target, temporary } = outputOf(options);\n const file = await TalliedFile.create(temporary);\n try {\n const counts = await writeArchive(plan, file, basename(target));\n const done = await file.close();\n await rename(temporary, target);\n return { format: \"warc\", out: target, bytes: done.size, ...counts };\n } catch (error) {\n await file.abandon();\n await rm(temporary, { force: true }).catch(() => undefined);\n throw error;\n }\n};\n"],"mappings":";;;;;;;;;;;;;AAkBA,MAAM,eAA4B;CAChC,MAAM,wBAAQ,IAAI,YAAY,GAAG;CACjC,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,KAAK,GAAG;EAC/B,IAAI,IAAI;EACR,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,IAAI,IAAI,IAAI,aAAc,MAAM,IAAK,MAAM;EAC1E,MAAM,KAAK,MAAM;CACnB;CACA,OAAO;AACT,EAAA,CAAG;;AAGH,MAAa,cAA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AAG;CAC1F,OAAO,GAAG,MAAM,IAAI,SAAS,KAAK,KAAK,IAAI,IAAI,OAAO,GAAG,OAAO,UAAU,KAAK,KAAK,IAAI;AAC1F;;AAGA,MAAa,YAAY,QAAwB,aAC/C,GAAG,KAAK,OAAO,GAAG,EAAE,GAAG,OAAO,KAAK,MAAM,GAAG,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE,EAAE,GAAG,KAAK,UAAU;CACnF,KAAK,OAAO;CACZ,MAAM,OAAO;CACb,QAAQ,OAAO,OAAO,MAAM;CAC5B,QAAQ,OAAO;CACf,QAAQ,OAAO,OAAO,MAAM;CAC5B,QAAQ,OAAO,OAAO,MAAM;CAC5B;AACF,CAAC;;;;;;;;;;AAWH,MAAa,aAAa,OACxB,QACA,YACwB;CACxB,MAAM,OAAO,YAAY,QAAQ,OAAO;CACxC,MAAM,EAAE,QAAQ,cAAc,SAAS,OAAO;CAC9C,MAAM,OAAO,MAAM,YAAY,OAAO,SAAS;CAC/C,IAAI;EACF,MAAM,SAAS,MAAM,aAAa,MAAM,MAAM,SAAS,MAAM,CAAC;EAC9D,MAAM,OAAO,MAAM,KAAK,MAAM;EAC9B,MAAM,OAAO,WAAW,MAAM;EAC9B,OAAO;GAAE,QAAQ;GAAQ,KAAK;GAAQ,OAAO,KAAK;GAAM,GAAG;EAAO;CACpE,SAAS,OAAO;EACd,MAAM,KAAK,QAAQ;EACnB,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;EAC1D,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"warc-DiE1M5le.mjs","names":[],"sources":["../src/zip.ts","../src/warc.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport { open, stat } from \"node:fs/promises\";\nimport { pipeline } from \"node:stream/promises\";\nimport * as zlib from \"node:zlib\";\n\n/*\n * This module writes a ZIP file with node:zlib only. The WACZ export uses it. It is not part of the\n * API of the package.\n *\n * - A member is stored (method 0) or deflated (method 8).\n * - The writer knows the CRC-32 and the sizes of each member before it writes the member. Thus the\n * local headers hold the true values, and the file has no data descriptors.\n * - The writer adds the Zip64 records only when a size, an offset or the count of members is too\n * large for the fields of 32 bits. The option `zip64: \"always\"` adds them in each case, for a test.\n */\n\nconst TABLE: Uint32Array = (() => {\n const table = new Uint32Array(256);\n for (let n = 0; n < 256; n += 1) {\n let c = n;\n for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n return table;\n})();\n\n/** This function calculates the CRC-32 of ISO 3309 with a table. It is the fallback of `crc32`. */\nexport const tableCrc32 = (bytes: Uint8Array, value = 0): number => {\n let crc = ~value >>> 0;\n for (const byte of bytes) crc = TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);\n return ~crc >>> 0;\n};\n\nconst native = (zlib as { readonly crc32?: (data: Uint8Array, value?: number) => number }).crc32;\n\n/** This function calculates the CRC-32 of the bytes. It continues from `value`. It uses `zlib.crc32` when Node.js has it. */\nexport const crc32 = (bytes: Uint8Array, value = 0): number =>\n native === undefined ? tableCrc32(bytes, value) : native(bytes, value);\n\n/** These are the facts of a file that a tally gives at its close. */\nexport interface Tallied {\n readonly path: string;\n readonly size: number;\n readonly crc: number;\n /** This value is the SHA-256 of the bytes, as hexadecimal digits. */\n readonly sha256: string;\n}\n\n/** This function writes the whole buffer. A write can write less than the buffer, and the loop writes the rest. */\nexport const writeAll = async (handle: FileHandle, bytes: Uint8Array): Promise<void> => {\n let at = 0;\n while (at < bytes.length) {\n const { bytesWritten } = await handle.write(bytes, at, bytes.length - at);\n at += bytesWritten;\n }\n};\n\n/** A tally writes a new file in sequence. It counts the bytes and calculates their CRC-32 and SHA-256. */\nexport class TalliedFile {\n private readonly hash = createHash(\"sha256\");\n private crcValue = 0;\n private count = 0;\n\n private constructor(\n readonly path: string,\n private readonly handle: FileHandle,\n ) {}\n\n /** This method makes a new file. It fails when the file exists. */\n static async create(path: string): Promise<TalliedFile> {\n return new TalliedFile(path, await open(path, \"wx\", 0o600));\n }\n\n /** This value is the count of bytes that the tally wrote. It is the offset of the next write. */\n get size(): number {\n return this.count;\n }\n\n async write(bytes: Uint8Array): Promise<void> {\n await writeAll(this.handle, bytes);\n this.hash.update(bytes);\n this.crcValue = crc32(bytes, this.crcValue);\n this.count += bytes.length;\n }\n\n /** This method closes the file and gives its facts. */\n async close(): Promise<Tallied> {\n await this.handle.close();\n return {\n path: this.path,\n size: this.count,\n crc: this.crcValue,\n sha256: this.hash.digest(\"hex\"),\n };\n }\n\n /** This method closes the file after an error. It gives no facts. */\n async abandon(): Promise<void> {\n await this.handle.close().catch(() => undefined);\n }\n}\n\n/** This function deflates a file into a new file (raw deflate, as ZIP needs it). It gives the size of the new file. */\nexport const deflateFile = async (from: string, to: string): Promise<number> => {\n await pipeline(\n createReadStream(from),\n zlib.createDeflateRaw(),\n createWriteStream(to, { flags: \"wx\", mode: 0o600 }),\n );\n return (await stat(to)).size;\n};\n\n/** A member of a ZIP file. Its bytes are in a file or in memory, as the ZIP stores them. */\nexport interface ZipMember {\n /** This value is the path of the member in the ZIP file. */\n readonly name: string;\n /** The value 0 stores the bytes. The value 8 holds deflated bytes. */\n readonly method: 0 | 8;\n /** This value is the CRC-32 of the bytes before compression. */\n readonly crc: number;\n /** This value is the count of bytes before compression. */\n readonly size: number;\n /** This value is the count of bytes in the ZIP file. */\n readonly compressedSize: number;\n /** This file holds the bytes as the ZIP stores them. */\n readonly file?: string | undefined;\n /** These bytes are the member as the ZIP stores them, when `file` is not given. */\n readonly data?: Uint8Array | undefined;\n}\n\n/** This function makes a member from bytes in memory. A member of method 8 holds the bytes deflated. */\nexport const memberOf = (name: string, bytes: Uint8Array, method: 0 | 8 = 8): ZipMember => {\n const data = method === 8 ? zlib.deflateRawSync(bytes) : bytes;\n return {\n name,\n method,\n crc: crc32(bytes),\n size: bytes.length,\n compressedSize: data.length,\n data,\n };\n};\n\n/** These options change a ZIP file. */\nexport interface ZipOptions {\n /** This time goes into each member, in the MS-DOS format of ZIP (UTC, to 2 seconds). */\n readonly date: Date;\n /** The value `auto` (the default) adds the Zip64 records only when they are necessary. */\n readonly zip64?: \"auto\" | \"always\" | undefined;\n}\n\nconst MAX32 = 0xffffffff;\nconst MAX16 = 0xffff;\nconst VERSION_ZIP = 20;\nconst VERSION_ZIP64 = 45;\n/** The member was made on Unix (3), with version 4.5 of the specification. */\nconst MADE_BY = (3 << 8) | VERSION_ZIP64;\n/** A plain file that its owner can read and write, and the others can read (`0o100644`). */\nconst FILE_MODE = (0o100644 << 16) >>> 0;\n/** Bit 11 of the flags tells that the name is UTF-8. */\nconst UTF8_NAMES = 0x0800;\n\nconst dosTime = (date: Date): { readonly time: number; readonly day: number } => {\n const year = Math.min(Math.max(date.getUTCFullYear(), 1980), 2107);\n return {\n time: (date.getUTCHours() << 11) | (date.getUTCMinutes() << 5) | (date.getUTCSeconds() >> 1),\n day: ((year - 1980) << 9) | ((date.getUTCMonth() + 1) << 5) | date.getUTCDate(),\n };\n};\n\n/** This function makes the Zip64 extra field (id 0x0001) with these values of 64 bits. */\nconst zip64Extra = (values: readonly number[]): Buffer => {\n const extra = Buffer.alloc(4 + 8 * values.length);\n extra.writeUInt16LE(0x0001, 0);\n extra.writeUInt16LE(8 * values.length, 2);\n values.forEach((value, at) => extra.writeBigUInt64LE(BigInt(value), 4 + 8 * at));\n return extra;\n};\n\n/**\n * This function writes a ZIP file with these members, in this sequence. It writes a new file and\n * fails when the file exists. It gives the size of the ZIP file.\n */\nexport const writeZip = async (\n target: string,\n members: readonly ZipMember[],\n options: ZipOptions,\n): Promise<number> => {\n const always = options.zip64 === \"always\";\n const { time, day } = dosTime(options.date);\n const handle = await open(target, \"wx\", 0o600);\n let offset = 0;\n const put = async (bytes: Uint8Array): Promise<void> => {\n await writeAll(handle, bytes);\n offset += bytes.length;\n };\n try {\n const central: Buffer[] = [];\n for (const member of members) {\n const name = Buffer.from(member.name, \"utf8\");\n const start = offset;\n const bigSizes = always || member.size >= MAX32 || member.compressedSize >= MAX32;\n const localExtra = bigSizes\n ? zip64Extra([member.size, member.compressedSize])\n : Buffer.alloc(0);\n const local = Buffer.alloc(30);\n local.writeUInt32LE(0x04034b50, 0);\n local.writeUInt16LE(bigSizes ? VERSION_ZIP64 : VERSION_ZIP, 4);\n local.writeUInt16LE(UTF8_NAMES, 6);\n local.writeUInt16LE(member.method, 8);\n local.writeUInt16LE(time, 10);\n local.writeUInt16LE(day, 12);\n local.writeUInt32LE(member.crc >>> 0, 14);\n local.writeUInt32LE(bigSizes ? MAX32 : member.compressedSize, 18);\n local.writeUInt32LE(bigSizes ? MAX32 : member.size, 22);\n local.writeUInt16LE(name.length, 26);\n local.writeUInt16LE(localExtra.length, 28);\n await put(local);\n await put(name);\n await put(localExtra);\n const before = offset;\n if (member.file !== undefined) {\n for await (const chunk of createReadStream(member.file) as AsyncIterable<Buffer>)\n await put(chunk);\n } else await put(member.data ?? new Uint8Array());\n if (offset - before !== member.compressedSize)\n throw new Error(\n `the member ${member.name} has ${String(offset - before)} bytes, not ${String(member.compressedSize)}`,\n );\n\n // the central header names only the values that are too large, in this sequence\n const bigSize = always || member.size >= MAX32;\n const bigCompressed = always || member.compressedSize >= MAX32;\n const bigOffset = always || start >= MAX32;\n const values = [\n ...(bigSize ? [member.size] : []),\n ...(bigCompressed ? [member.compressedSize] : []),\n ...(bigOffset ? [start] : []),\n ];\n const extra = values.length > 0 ? zip64Extra(values) : Buffer.alloc(0);\n const header = Buffer.alloc(46);\n header.writeUInt32LE(0x02014b50, 0);\n header.writeUInt16LE(MADE_BY, 4);\n header.writeUInt16LE(values.length > 0 ? VERSION_ZIP64 : VERSION_ZIP, 6);\n header.writeUInt16LE(UTF8_NAMES, 8);\n header.writeUInt16LE(member.method, 10);\n header.writeUInt16LE(time, 12);\n header.writeUInt16LE(day, 14);\n header.writeUInt32LE(member.crc >>> 0, 16);\n header.writeUInt32LE(bigCompressed ? MAX32 : member.compressedSize, 20);\n header.writeUInt32LE(bigSize ? MAX32 : member.size, 24);\n header.writeUInt16LE(name.length, 28);\n header.writeUInt16LE(extra.length, 30);\n header.writeUInt16LE(0, 32);\n header.writeUInt16LE(0, 34);\n header.writeUInt16LE(0, 36);\n header.writeUInt32LE(FILE_MODE, 38);\n header.writeUInt32LE(bigOffset ? MAX32 : start, 42);\n central.push(header, name, extra);\n }\n\n const centralStart = offset;\n for (const part of central) await put(part);\n const centralSize = offset - centralStart;\n const count = members.length;\n const zip64End = always || count >= MAX16 || centralStart >= MAX32 || centralSize >= MAX32;\n if (zip64End) {\n const recordAt = offset;\n const record = Buffer.alloc(56);\n record.writeUInt32LE(0x06064b50, 0);\n record.writeBigUInt64LE(44n, 4);\n record.writeUInt16LE(MADE_BY, 12);\n record.writeUInt16LE(VERSION_ZIP64, 14);\n record.writeUInt32LE(0, 16);\n record.writeUInt32LE(0, 20);\n record.writeBigUInt64LE(BigInt(count), 24);\n record.writeBigUInt64LE(BigInt(count), 32);\n record.writeBigUInt64LE(BigInt(centralSize), 40);\n record.writeBigUInt64LE(BigInt(centralStart), 48);\n await put(record);\n const locator = Buffer.alloc(20);\n locator.writeUInt32LE(0x07064b50, 0);\n locator.writeUInt32LE(0, 4);\n locator.writeBigUInt64LE(BigInt(recordAt), 8);\n locator.writeUInt32LE(1, 16);\n await put(locator);\n }\n const end = Buffer.alloc(22);\n end.writeUInt32LE(0x06054b50, 0);\n end.writeUInt16LE(0, 4);\n end.writeUInt16LE(0, 6);\n end.writeUInt16LE(zip64End ? MAX16 : count, 8);\n end.writeUInt16LE(zip64End ? MAX16 : count, 10);\n end.writeUInt32LE(zip64End ? MAX32 : centralSize, 12);\n end.writeUInt32LE(zip64End ? MAX32 : centralStart, 16);\n end.writeUInt16LE(0, 20);\n await put(end);\n } finally {\n await handle.close();\n }\n return offset;\n};\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { rename, rm } from \"node:fs/promises\";\nimport { STATUS_CODES } from \"node:http\";\nimport { basename, join, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gzip } from \"node:zlib\";\nimport type { BlobStore } from \"./blobs.ts\";\nimport { FileBlobStore } from \"./blobs.ts\";\nimport type { CaptureReader } from \"./log.ts\";\nimport { CaptureLog } from \"./log.ts\";\nimport type { CaptureRecord } from \"./record.ts\";\nimport { BOT_PAGE, VERSION } from \"./version.ts\";\nimport { TalliedFile } from \"./zip.ts\";\n\n/*\n * This module writes the capture log as WARC/1.1 (ISO 28500:2017). The README tells what goes into\n * the archive and why. These are the records:\n *\n * - One `warcinfo` record names the software and the filters of the export.\n * - A capture with a body gives a `response` record. Its HTTP header block is rebuilt from the\n * headers that the capture kept, and its payload is the stored body.\n * - A 304 gives a `revisit` record with the profile `server-not-modified`.\n * - A page that the headless browser rendered gives a `conversion` record: the page after\n * JavaScript, not the body that the server sent.\n * - Each of them has a `metadata` record (`WARC-Concurrent-To`) with the JSON of the capture.\n *\n * Each record is one gzip member. The export reads the log as a stream and holds one body at a time.\n */\n\nconst gzipAsync = promisify(gzip);\n\nconst HOME = new URL(\"../\", BOT_PAGE).href;\nconst CRLF = \"\\r\\n\";\nconst END = Buffer.from(\"\\r\\n\\r\\n\", \"latin1\");\nconst KINDS: ReadonlySet<string> = new Set([\"capture\", \"revisit\", \"skipped\"]);\nconst HASH = /^[0-9a-f]{64}$/;\n/** The revisit records name their original from this count of recent responses. */\nconst ORIGINALS = 65_536;\nconst SERVER_NOT_MODIFIED = \"http://netpreserve.org/warc/1.1/revisit/server-not-modified\";\nconst HTTP_RESPONSE = \"application/http; msgtype=response\";\n\n/** The source of an export: the folder of a store, or the capture log and the blob store of a runtime. */\nexport type ArchiveSource =\n string | { readonly captures: CaptureReader; readonly blobs: BlobStore };\n\n/** These filters select the captures of an export. Each filter that you give makes the selection smaller. */\nexport interface ArchiveFilter {\n /** The export holds the captures received at this time or later. */\n readonly since?: string | Date | undefined;\n /** The export holds the captures received before this time. */\n readonly until?: string | Date | undefined;\n /** The export holds the captures of this host and of its subdomains, for example `example.com`. */\n readonly host?: string | undefined;\n /** The export holds the captures whose URL starts with this text. */\n readonly urlPrefix?: string | undefined;\n /** The export holds only the captures with these ids. */\n readonly ids?: readonly string[] | undefined;\n}\n\n/** These options control an export. Only `out` is necessary. */\nexport interface ArchiveOptions extends ArchiveFilter {\n /** This file gets the archive. The export writes a temporary file and gives it this name at the end. */\n readonly out: string;\n /**\n * When this value is true, each capture with no body (a refusal, a skip of robots.txt, an error, a\n * redirect) gets a `metadata` record. The default is false: the export leaves them out.\n */\n readonly includeRefusals?: boolean | undefined;\n /** When this value is true, the export replaces a file that exists. The default is false: the export fails. */\n readonly overwrite?: boolean | undefined;\n}\n\n/** These counts tell what an export wrote. */\nexport interface ArchiveCounts {\n /** This value is the count of capture records that the filters selected. */\n readonly captures: number;\n readonly responses: number;\n readonly revisits: number;\n /** This value is the count of rendered pages (`conversion` records). */\n readonly conversions: number;\n readonly metadata: number;\n /** This value is the count of captures with no body: refusals, skips, errors and redirects. */\n readonly bodiless: number;\n /** This value is the count of captures whose body is not in the blob store, or does not agree with its hash. */\n readonly missing: number;\n /** This value is the count of damaged lines of the capture log. */\n readonly damaged: number;\n}\n\n/** This is the result of `exportWarc`. */\nexport interface WarcResult extends ArchiveCounts {\n readonly format: \"warc\";\n /** This value is the absolute path of the archive. */\n readonly out: string;\n readonly bytes: number;\n}\n\n/** These are the facts of a `response` or `revisit` record that the index of a WACZ file needs. */\nexport interface ArchivedRecord {\n readonly type: \"response\" | \"revisit\";\n readonly url: string;\n readonly date: string;\n readonly status: number;\n readonly mime: string;\n readonly digest: string;\n readonly offset: number;\n readonly length: number;\n readonly capture: string;\n /** This value is true for a page of the page list: a 200 response that is not a robots.txt file. */\n readonly page: boolean;\n}\n\n/** A plan is a valid filter and an open source. An export makes it before it writes a file. */\nexport interface ArchivePlan {\n readonly captures: CaptureReader;\n readonly blobs: BlobStore;\n readonly filter: ArchiveSelection;\n readonly includeRefusals: boolean;\n}\n\n/** This is a filter after the checks: times in ISO 8601, a lowercase host and a set of ids. */\nexport interface ArchiveSelection {\n readonly since?: string | undefined;\n readonly until?: string | undefined;\n readonly host?: string | undefined;\n readonly urlPrefix?: string | undefined;\n readonly ids?: ReadonlySet<string> | undefined;\n}\n\nconst RFC4648 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n\n/** This function writes bytes in base 32 (RFC 4648), with capitals and padding. WARC tools write SHA-256 digests in this form. */\nexport const base32 = (bytes: Uint8Array): string => {\n let out = \"\";\n let value = 0;\n let bits = 0;\n for (const byte of bytes) {\n value = ((value << 8) | byte) & 0xffff;\n bits += 8;\n while (bits >= 5) {\n out += RFC4648[(value >>> (bits - 5)) & 31]!;\n bits -= 5;\n }\n }\n if (bits > 0) out += RFC4648[(value << (5 - bits)) & 31]!;\n while (out.length % 8 !== 0) out += \"=\";\n return out;\n};\n\nconst digestOf = (bytes: Uint8Array): string => `sha256:${base32(bytes)}`;\n\nconst sha256Of = (...parts: readonly Uint8Array[]): Buffer => {\n const hash = createHash(\"sha256\");\n for (const part of parts) hash.update(part);\n return hash.digest();\n};\n\n/** This function gives a version 5 UUID (RFC 9562): the SHA-1 of a namespace and a name. */\nconst uuidV5 = (namespace: string, name: string): string => {\n const hash = createHash(\"sha1\")\n .update(Buffer.from(namespace.replace(/-/g, \"\"), \"hex\"))\n .update(name, \"utf8\")\n .digest();\n hash[6] = (hash[6]! & 0x0f) | 0x50;\n hash[8] = (hash[8]! & 0x3f) | 0x80;\n const hex = hash.subarray(0, 16).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n};\n\n/** The namespace of the record ids: a UUID of the URL of the site, in the URL namespace of RFC 9562. */\nconst NAMESPACE = uuidV5(\"6ba7b811-9dad-11d1-80b4-00c04fd430c8\", HOME);\n\n/** The id of a record of a capture is the same at each export: it comes from the hash of the capture. */\nconst recordId = (record: CaptureRecord, type: string): string =>\n `<urn:uuid:${uuidV5(NAMESPACE, `${record.content_hash || `${record.id}@${record.received_at}`}/${type}`)}>`;\n\n/** A field of a header holds no line break. */\nconst clean = (value: string): string => value.replace(/[\\r\\n]+/g, \" \").trim();\n\n/** This function gives one record: the WARC header, the block and the two line breaks at the end. */\nconst recordBytes = (\n fields: ReadonlyArray<readonly [string, string]>,\n block: readonly Uint8Array[],\n): Buffer => {\n const length = block.reduce((sum, part) => sum + part.length, 0);\n const head = [\n \"WARC/1.1\",\n ...fields.map(([name, value]) => `${name}: ${clean(value)}`),\n `Content-Length: ${String(length)}`,\n \"\",\n \"\",\n ].join(CRLF);\n return Buffer.concat([Buffer.from(head, \"utf8\"), ...block, END]);\n};\n\n/**\n * This function gives an HTTP status line and header block. HTTP headers are Latin-1 bytes, and\n * undici gives each byte as one character. Thus the block gives back the bytes that the server sent.\n */\nconst httpHead = (status: number, headers: ReadonlyArray<readonly [string, string]>): Buffer =>\n Buffer.from(\n [\n `HTTP/1.1 ${String(status)} ${STATUS_CODES[status] ?? \"Unknown\"}`,\n ...headers.map(([name, value]) => `${name}: ${clean(value)}`),\n \"\",\n \"\",\n ].join(CRLF),\n \"latin1\",\n );\n\n/** These fields of a capture keep a header of the response. */\nconst KEPT_HEADERS: ReadonlyArray<readonly [string, string]> = [\n [\"etag\", \"ETag\"],\n [\"last_modified\", \"Last-Modified\"],\n [\"cache_control\", \"Cache-Control\"],\n [\"expires\", \"Expires\"],\n [\"age\", \"Age\"],\n [\"date\", \"Date\"],\n [\"vary\", \"Vary\"],\n];\n\n/** These are the facts of a fetch record that the export reads. */\ninterface Facts {\n readonly url: string;\n readonly date: string;\n readonly status: number | undefined;\n readonly blob: string | undefined;\n readonly contentType: string | undefined;\n readonly rendered: boolean;\n readonly truncated: boolean;\n readonly cut: boolean;\n readonly revisitOf: string | undefined;\n readonly recipe: string | undefined;\n readonly headers: ReadonlyArray<readonly [string, string]>;\n}\n\nconst text = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/** This function gives the time of a capture in ISO 8601, with milliseconds. WARC/1.1 permits them. */\nconst isoOf = (value: unknown, fallback: string): string => {\n const ms = typeof value === \"string\" ? Date.parse(value) : Number.NaN;\n if (Number.isFinite(ms)) return new Date(ms).toISOString();\n const other = Date.parse(fallback);\n return Number.isFinite(other) ? new Date(other).toISOString() : fallback;\n};\n\nconst factsOf = (record: CaptureRecord): Facts | undefined => {\n const payload = record.payload;\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const fields = payload as Readonly<Record<string, unknown>>;\n const url = text(fields[\"url\"]) ?? text(record.external_id);\n if (url === undefined) return undefined;\n const blob = text(fields[\"blob\"]);\n const status = fields[\"status\"];\n return {\n url,\n date: isoOf(fields[\"fetched_at\"], record.received_at),\n status: typeof status === \"number\" && Number.isInteger(status) ? status : undefined,\n blob: blob !== undefined && HASH.test(blob) ? blob : undefined,\n contentType: text(fields[\"content_type\"]),\n rendered: fields[\"rendered\"] === true,\n truncated: fields[\"truncated\"] === true,\n cut: fields[\"cut\"] === true,\n revisitOf: text(fields[\"revisit_of\"]),\n recipe: text(fields[\"recipe\"]),\n headers: KEPT_HEADERS.flatMap(([field, name]) => {\n const value = text(fields[field]);\n return value === undefined ? [] : [[name, value] as const];\n }),\n };\n};\n\nconst timeOf = (name: string, value: string | Date | undefined): string | undefined => {\n if (value === undefined) return undefined;\n const ms = value instanceof Date ? value.getTime() : Date.parse(value);\n if (!Number.isFinite(ms)) throw new RangeError(`${name} is not a time: \"${String(value)}\"`);\n return new Date(ms).toISOString();\n};\n\nconst hostName = (value: string): string | undefined => {\n try {\n return new URL(value).hostname.toLowerCase().replace(/\\.$/, \"\");\n } catch {\n return undefined;\n }\n};\n\nconst filterOf = (options: ArchiveFilter): ArchiveSelection => {\n const since = timeOf(\"since\", options.since);\n const until = timeOf(\"until\", options.until);\n let host: string | undefined;\n if (options.host !== undefined) {\n host = options.host.trim().toLowerCase().replace(/^\\*\\./, \"\").replace(/\\.$/, \"\");\n if (host === \"\" || /[/:@\\s]/.test(host))\n throw new RangeError(`host is a host name, for example example.com, not \"${options.host}\"`);\n }\n return {\n since,\n until,\n host,\n urlPrefix: options.urlPrefix === \"\" ? undefined : options.urlPrefix,\n ids: options.ids === undefined ? undefined : new Set(options.ids),\n };\n};\n\nconst selected = (record: CaptureRecord, facts: Facts, filter: ArchiveSelection): boolean => {\n if (filter.since !== undefined && record.received_at < filter.since) return false;\n if (filter.until !== undefined && record.received_at >= filter.until) return false;\n if (filter.urlPrefix !== undefined && !facts.url.startsWith(filter.urlPrefix)) return false;\n if (filter.ids !== undefined && !filter.ids.has(record.id)) return false;\n if (filter.host !== undefined) {\n const host = hostName(facts.url);\n if (host === undefined || (host !== filter.host && !host.endsWith(`.${filter.host}`)))\n return false;\n }\n return true;\n};\n\n/**\n * This function checks the filters and opens the source. It writes nothing. A folder must hold a\n * capture log, and the export does not make a store.\n */\nexport const planArchive = (source: ArchiveSource, options: ArchiveOptions): ArchivePlan => {\n const filter = filterOf(options);\n const includeRefusals = options.includeRefusals === true;\n if (typeof source !== \"string\") {\n return { captures: source.captures, blobs: source.blobs, filter, includeRefusals };\n }\n const dir = resolve(source);\n if (!existsSync(join(dir, \"captures\")))\n throw new Error(`the store ${dir} has no capture log (captures/)`);\n return {\n captures: new CaptureLog(join(dir, \"captures\"), { sync: false }),\n blobs: new FileBlobStore(join(dir, \"blobs\"), { sync: false }),\n filter,\n includeRefusals,\n };\n};\n\n/** This function gives the path of the archive and of its temporary file. It fails when the archive exists, unless `overwrite` is true. */\nexport const outputOf = (\n options: ArchiveOptions,\n): { readonly target: string; readonly temporary: string } => {\n if (typeof options.out !== \"string\" || options.out.trim() === \"\")\n throw new Error(\"an export needs out: the file of the archive\");\n const target = resolve(options.out);\n if (options.overwrite !== true && existsSync(target))\n throw new Error(`${target} exists: give a different file, or set overwrite`);\n return { target, temporary: `${target}.${randomUUID()}.tmp` };\n};\n\n/** This function reads a body from the blob store. It gives no body when the bytes do not agree with the hash. */\nconst bodyOf = async (\n blobs: BlobStore,\n hash: string,\n): Promise<{ readonly bytes: Uint8Array; readonly digest: Buffer } | undefined> => {\n let bytes: Uint8Array | undefined;\n try {\n bytes = await blobs.get(hash);\n } catch {\n return undefined;\n }\n if (bytes === undefined) return undefined;\n const digest = sha256Of(bytes);\n return digest.toString(\"hex\") === hash ? { bytes, digest } : undefined;\n};\n\nconst mimeOf = (contentType: string | undefined): string =>\n contentType?.split(\";\")[0]?.trim().toLowerCase() || \"-\";\n\n/** This function gives the JSON of the metadata record of a capture. The labels and the scope of the application stay out. */\nconst metadataOf = (record: CaptureRecord, written: Readonly<Record<string, string>>): Buffer =>\n Buffer.from(\n `${JSON.stringify({\n capture: {\n id: record.id,\n source: record.source,\n kind: record.kind,\n ...(record.external_id !== undefined ? { external_id: record.external_id } : {}),\n ...(record.occurred_at !== undefined ? { occurred_at: record.occurred_at } : {}),\n received_at: record.received_at,\n content_hash: record.content_hash,\n payload: record.payload,\n },\n export: written,\n })}\\n`,\n \"utf8\",\n );\n\n/**\n * This function writes the records of an archive into a file: the `warcinfo` record, then the\n * records of each capture that the plan selects. It gives the facts of each `response` and\n * `revisit` record to `onRecord`, for the index of a WACZ file.\n */\nexport const writeArchive = async (\n plan: ArchivePlan,\n file: TalliedFile,\n filename: string,\n onRecord?: (record: ArchivedRecord) => Promise<void>,\n): Promise<ArchiveCounts> => {\n const counts = {\n captures: 0,\n responses: 0,\n revisits: 0,\n conversions: 0,\n metadata: 0,\n bodiless: 0,\n missing: 0,\n damaged: 0,\n };\n const { filter } = plan;\n const put = async (\n bytes: Buffer,\n ): Promise<{ readonly offset: number; readonly length: number }> => {\n const member = await gzipAsync(bytes);\n const offset = file.size;\n await file.write(member);\n return { offset, length: member.length };\n };\n\n const info = `<urn:uuid:${randomUUID()}>`;\n const shown = Object.fromEntries(\n Object.entries({\n since: filter.since,\n until: filter.until,\n host: filter.host,\n url_prefix: filter.urlPrefix,\n ids: filter.ids === undefined ? undefined : filter.ids.size,\n include_refusals: plan.includeRefusals,\n }).filter(([, value]) => value !== undefined),\n );\n const fields = [\n `software: polite-crawler/${VERSION} (+${HOME})`,\n \"format: WARC File Format 1.1\",\n \"conformsTo: https://iipc.github.io/warc-specifications/specifications/warc-format/warc-1.1/\",\n \"robots: obey\",\n \"description: An export of the capture log of polite-crawler. The HTTP headers of each response are rebuilt from the headers that the capture kept.\",\n `polite-crawler-filter: ${JSON.stringify(shown)}`,\n ];\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"warcinfo\"],\n [\"WARC-Record-ID\", info],\n [\"WARC-Date\", new Date().toISOString()],\n [\"WARC-Filename\", filename],\n [\"Content-Type\", \"application/warc-fields\"],\n ],\n [Buffer.from(`${fields.join(CRLF)}${CRLF}`, \"utf8\")],\n ),\n );\n\n // a revisit names its original when the original is one of the recent responses of the export\n const originals = new Map<\n string,\n { readonly id: string; readonly date: string; readonly url: string }\n >();\n const remember = (\n capture: string,\n original: { readonly id: string; readonly date: string; readonly url: string },\n ): void => {\n originals.delete(capture);\n originals.set(capture, original);\n if (originals.size > ORIGINALS) originals.delete(originals.keys().next().value!);\n };\n\n const scan = plan.captures.scan(\n { source: \"fetch\", since: filter.since },\n { onDamaged: () => void (counts.damaged += 1) },\n );\n for await (const record of scan) {\n if (record.source !== \"fetch\" || !KINDS.has(record.kind)) continue;\n const facts = factsOf(record);\n if (facts === undefined || !selected(record, facts, filter)) continue;\n counts.captures += 1;\n const common: Array<readonly [string, string]> = [\n [\"WARC-Date\", facts.date],\n [\"WARC-Target-URI\", facts.url],\n [\"WARC-Warcinfo-ID\", info],\n ];\n const vendor: Array<readonly [string, string]> = [[\"WARC-Polite-Crawler-Capture\", record.id]];\n let main: string | undefined;\n let written: Record<string, string> = { record: \"none\", reason: \"no body\" };\n\n if (record.kind === \"revisit\" && facts.blob !== undefined) {\n // the 304 confirmed the stored body, so the payload digest is the digest of that body\n const original = facts.revisitOf === undefined ? undefined : originals.get(facts.revisitOf);\n const head = httpHead(304, [\n ...(facts.contentType !== undefined ? [[\"Content-Type\", facts.contentType] as const] : []),\n ...facts.headers,\n ]);\n const digest = digestOf(Buffer.from(facts.blob, \"hex\"));\n main = recordId(record, \"revisit\");\n const at = await put(\n recordBytes(\n [\n [\"WARC-Type\", \"revisit\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Profile\", SERVER_NOT_MODIFIED],\n ...(original !== undefined ? [[\"WARC-Refers-To\", original.id] as const] : []),\n [\"WARC-Refers-To-Target-URI\", original?.url ?? facts.url],\n ...(original !== undefined ? [[\"WARC-Refers-To-Date\", original.date] as const] : []),\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digestOf(sha256Of(head))],\n ...vendor,\n [\"WARC-Polite-Crawler-Headers\", \"rebuilt\"],\n [\"Content-Type\", HTTP_RESPONSE],\n ],\n [head],\n ),\n );\n counts.revisits += 1;\n written = { record: \"revisit\", http_headers: \"rebuilt\" };\n await onRecord?.({\n type: \"revisit\",\n url: facts.url,\n date: facts.date,\n status: 304,\n mime: \"warc/revisit\",\n digest,\n ...at,\n capture: record.id,\n page: false,\n });\n } else if (record.kind === \"capture\" && facts.blob !== undefined) {\n const body = await bodyOf(plan.blobs, facts.blob);\n if (body === undefined) {\n counts.missing += 1;\n written = { record: \"none\", reason: \"body missing\" };\n } else if (facts.rendered) {\n // the page after JavaScript is a conversion of the page, not the body that the server sent\n const digest = digestOf(body.digest);\n main = recordId(record, \"conversion\");\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"conversion\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digest],\n ...vendor,\n [\"Content-Type\", facts.contentType ?? \"text/html; charset=utf-8\"],\n ],\n [body.bytes],\n ),\n );\n counts.conversions += 1;\n written = { record: \"conversion\", body: \"rendered\" };\n } else if (facts.status !== undefined && facts.status >= 100 && facts.status <= 999) {\n const head = httpHead(facts.status, [\n ...(facts.contentType !== undefined\n ? [[\"Content-Type\", facts.contentType] as const]\n : []),\n [\"Content-Length\", String(body.bytes.length)],\n ...facts.headers,\n ]);\n const digest = digestOf(body.digest);\n main = recordId(record, \"response\");\n // a body that the crawler cut at its limit, or that ended early, says so\n const truncated = facts.cut ? \"disconnect\" : facts.truncated ? \"length\" : undefined;\n const at = await put(\n recordBytes(\n [\n [\"WARC-Type\", \"response\"],\n [\"WARC-Record-ID\", main],\n ...common,\n [\"WARC-Payload-Digest\", digest],\n [\"WARC-Block-Digest\", digestOf(sha256Of(head, body.bytes))],\n ...(truncated !== undefined ? [[\"WARC-Truncated\", truncated] as const] : []),\n ...vendor,\n [\"WARC-Polite-Crawler-Headers\", \"rebuilt\"],\n [\"Content-Type\", HTTP_RESPONSE],\n ],\n [head, body.bytes],\n ),\n );\n counts.responses += 1;\n written = { record: \"response\", http_headers: \"rebuilt\", body: \"decoded\" };\n remember(record.id, { id: main, date: facts.date, url: facts.url });\n await onRecord?.({\n type: \"response\",\n url: facts.url,\n date: facts.date,\n status: facts.status,\n mime: mimeOf(facts.contentType),\n digest,\n ...at,\n capture: record.id,\n page: facts.status === 200 && facts.recipe !== \"robots.txt\",\n });\n }\n }\n\n if (main === undefined) {\n if (written[\"reason\"] === \"no body\") counts.bodiless += 1;\n if (!plan.includeRefusals) continue;\n }\n const block = metadataOf(record, written);\n await put(\n recordBytes(\n [\n [\"WARC-Type\", \"metadata\"],\n [\"WARC-Record-ID\", recordId(record, \"metadata\")],\n ...common,\n ...(main !== undefined ? [[\"WARC-Concurrent-To\", main] as const] : []),\n [\"WARC-Block-Digest\", digestOf(sha256Of(block))],\n ...vendor,\n [\"Content-Type\", \"application/json\"],\n ],\n [block],\n ),\n );\n counts.metadata += 1;\n }\n return counts;\n};\n\n/**\n * This function gives the SURT key of a URL, as `pywb` and the `surt` library make it with their\n * defaults. The host is reversed with commas and has no `www.` and no default port. The path\n * and the query are lowercase, the path has no slash at the end, and the parts of the query are\n * sorted.\n */\nexport const surt = (value: string): string => {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return value.toLowerCase();\n }\n const host = url.hostname\n .toLowerCase()\n .replace(/\\.$/, \"\")\n .replace(/^www\\d*\\./, \"\");\n const key = host.startsWith(\"[\") ? host : host.split(\".\").reverse().join(\",\");\n let path = url.pathname.toLowerCase();\n if (path.length > 1 && path.endsWith(\"/\")) path = path.slice(0, -1);\n const query = url.search.slice(1).toLowerCase().split(\"&\").filter(Boolean).sort().join(\"&\");\n return `${key}${url.port === \"\" ? \"\" : `:${url.port}`})${path}${query === \"\" ? \"\" : `?${query}`}`;\n};\n\n/** This function gives the line of a record in a CDXJ index: the SURT key, the time to the second, and JSON. */\nexport const cdxjLine = (record: ArchivedRecord, filename: string): string =>\n `${surt(record.url)} ${record.date.slice(0, 19).replace(/\\D/g, \"\")} ${JSON.stringify({\n url: record.url,\n mime: record.mime,\n status: String(record.status),\n digest: record.digest,\n length: String(record.length),\n offset: String(record.offset),\n filename,\n })}`;\n\n/**\n * This function writes the captures of a store as a WARC/1.1 file, with one gzip member for each\n * record (`.warc.gz`). It reads the capture log as a stream, so its memory does not grow with the\n * store. It writes a temporary file and gives it the name `out` at the end, so a failed export\n * leaves no part of a file.\n *\n * The source is the folder of a store, or the capture log and the blob store of a runtime\n * (`crawler.runtime`). The export only reads the store.\n */\nexport const exportWarc = async (\n source: ArchiveSource,\n options: ArchiveOptions,\n): Promise<WarcResult> => {\n const plan = planArchive(source, options);\n const { target, temporary } = outputOf(options);\n const file = await TalliedFile.create(temporary);\n try {\n const counts = await writeArchive(plan, file, basename(target));\n const done = await file.close();\n await rename(temporary, target);\n return { format: \"warc\", out: target, bytes: done.size, ...counts };\n } catch (error) {\n await file.abandon();\n await rm(temporary, { force: true }).catch(() => undefined);\n throw error;\n }\n};\n"],"mappings":";;;;;;;;;;;;;AAkBA,MAAM,eAA4B;CAChC,MAAM,wBAAQ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 +1,11 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
2
2
  import { createHash, createPrivateKey, createPublicKey, randomBytes, sign, verify } from "node:crypto";
3
- //#region src/webbotauth.ts
3
+ // src/webbotauth.ts
4
4
  var webbotauth_exports = /* @__PURE__ */ __exportAll({
5
5
  KEY_DIRECTORY_PATH: () => KEY_DIRECTORY_PATH,
6
6
  KEY_DIRECTORY_TYPE: () => KEY_DIRECTORY_TYPE,
7
- WEB_BOT_AUTH_TAG: () => WEB_BOT_AUTH_TAG,
8
7
  createWebBotAuthSigner: () => createWebBotAuthSigner,
9
- isRequestSigner: () => isRequestSigner,
10
- keyDirectory: () => keyDirectory,
11
- signParts: () => signParts,
12
- signatureBase: () => signatureBase,
13
- signerOf: () => signerOf,
14
- verifySignature: () => verifySignature
8
+ keyDirectory: () => keyDirectory
15
9
  });
16
10
  /**
17
11
  * Signed requests: HTTP Message Signatures (RFC 9421), as the IETF Web Bot Auth profile tells
@@ -562,7 +556,6 @@ const verifySignature = (request, directory, options = {}) => {
562
556
  }
563
557
  return last;
564
558
  };
565
- //#endregion
566
559
  export { signerOf as a, keyDirectory as i, KEY_DIRECTORY_TYPE as n, verifySignature as o, createWebBotAuthSigner as r, webbotauth_exports as s, KEY_DIRECTORY_PATH as t };
567
560
 
568
- //# sourceMappingURL=webbotauth-Dq_dA_u3.mjs.map
561
+ //# sourceMappingURL=webbotauth-W3GXY3dy.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"webbotauth-Dq_dA_u3.mjs","names":["signBytes","verifyBytes"],"sources":["../src/webbotauth.ts"],"sourcesContent":["import type { JsonWebKeyInput, KeyObject } from \"node:crypto\";\nimport {\n createHash,\n createPrivateKey,\n createPublicKey,\n randomBytes,\n sign as signBytes,\n verify as verifyBytes,\n} from \"node:crypto\";\n\n/**\n * Signed requests: HTTP Message Signatures (RFC 9421), as the IETF Web Bot Auth profile tells\n * (`draft-ietf-webbotauth-httpsig-protocol-00`, 1 September 2026). A signature lets a site verify that\n * a request comes from the holder of a key that the operator publishes.\n *\n * - Each request gets three headers: `Signature-Agent`, `Signature-Input` and `Signature`.\n * - `Signature-Agent` is a dictionary. Its member names the key directory of the operator.\n * - The signature covers `@authority` and that member of `Signature-Agent`.\n * - The parameters are `created`, `keyid` (the JWK thumbprint of the key), `alg=\"ed25519\"`,\n * `expires`, a random `nonce` and `tag=\"web-bot-auth\"`.\n * - The key is an Ed25519 key, and `node:crypto` signs. The package adds no dependency.\n *\n * A signature adds an identity. It does not replace the `User-Agent` header, which stays honest.\n */\n\n/** The path of the key directory on the host of the operator (the well-known URI of the draft). */\nexport const KEY_DIRECTORY_PATH = \"/.well-known/http-message-signatures-directory\";\n\n/** The media type of the key directory. The host of the directory sends it as `Content-Type`. */\nexport const KEY_DIRECTORY_TYPE = \"application/http-message-signatures-directory+json\";\n\n/** The value of the `tag` parameter of a Web Bot Auth signature. */\nexport const WEB_BOT_AUTH_TAG = \"web-bot-auth\";\n\n/**\n * This value tells how a site finds the keys from the URL of `Signature-Agent`:\n *\n * - `directory` (the default): the URL is an origin, and the keys are at `KEY_DIRECTORY_PATH` on it.\n * - `jwks_uri`: the URL is the address of a JSON Web Key Set, on any path.\n */\nexport type SignatureAgentType = \"directory\" | \"jwks_uri\";\n\n/** A key in one of the forms that `node:crypto` reads: a `KeyObject`, PEM text, DER bytes (PKCS#8 or SPKI) or a JWK. */\n/**\n * This type is a JSON Web Key, as `createPrivateKey` of `node:crypto` reads it. The type comes from `JsonWebKeyInput`, which\n * `@types/node` 22 and 26 both have: version 26 has no `JsonWebKey` export in `node:crypto`.\n */\nexport type JwkInput = JsonWebKeyInput[\"key\"];\n\nexport type KeyInput = KeyObject | string | Uint8Array | JwkInput;\n\n/** These options make a signer for Web Bot Auth. */\nexport interface WebBotAuthOptions {\n /** This key signs. It is an Ed25519 private key: a `KeyObject`, PKCS#8 (PEM text or DER bytes) or a JWK with `d`. */\n readonly privateKey: KeyInput;\n /**\n * This text is the `keyid` of each signature: the JWK thumbprint of the key (RFC 8037). The signer\n * calculates it. A value that is not the thumbprint of the key throws an error.\n */\n readonly keyId?: string | undefined;\n /**\n * This URL tells a site where the keys are. For the type `directory`, it is an https origin, for\n * example `https://bot.example.com`. For `jwks_uri`, it is the https URL of a JSON Web Key Set.\n */\n readonly signatureAgent: string;\n /** This value tells how a site finds the keys from `signatureAgent`. The default is `directory`. */\n readonly agentType?: SignatureAgentType | undefined;\n /** This value is the time that a signature stays valid, in milliseconds. The default is 5 minutes, and the maximum is 24 hours. */\n readonly lifetimeMs?: number | undefined;\n /** This text is the label of the signature, and the key of the member of `Signature-Agent`. The default is `sig1`. */\n readonly label?: string | undefined;\n}\n\n/**\n * A request signer gives the signature headers of one request. The crawler uses it for each\n * request, robots.txt too. `createWebBotAuthSigner` makes one. A signer of your own can sign with a\n * key in a hardware module, for example.\n */\nexport interface RequestSigner {\n /** This text is the `keyid` of the signatures. */\n readonly keyId: string;\n /** This URL is the value of the member of `Signature-Agent`: where a site finds the keys. */\n readonly signatureAgent: string;\n /** This method gives the headers that sign a request to `url` at the time `now` (milliseconds since the epoch). */\n sign(url: URL, now: number): Readonly<Record<string, string>>;\n}\n\n/** The signer that `createWebBotAuthSigner` makes. It also gives its public key for the key directory. */\nexport interface WebBotAuthSigner extends RequestSigner {\n /** This JWK is the public key of the signer, with no private part. Give it to `keyDirectory`. */\n readonly publicKey: JwkInput;\n}\n\n/** One key of a key directory: an Ed25519 public key as a JWK, with its thumbprint as `kid`. */\nexport interface DirectoryKey {\n readonly kty: \"OKP\";\n readonly crv: \"Ed25519\";\n readonly kid: string;\n readonly x: string;\n readonly use: \"sig\";\n}\n\n/** A key directory: a JSON Web Key Set. The operator serves it as JSON at `KEY_DIRECTORY_PATH`, with the type `KEY_DIRECTORY_TYPE`. */\nexport interface KeyDirectory {\n readonly keys: readonly DirectoryKey[];\n}\n\n/** The parts of a request that `verifySignature` reads. */\nexport interface SignedRequest {\n readonly url: string;\n /** The default is `GET`. */\n readonly method?: string | undefined;\n /** These are the headers of the request. A name can be in any case, and a header can have more than one line. */\n readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;\n}\n\n/** The result of `verifySignature`. */\nexport interface SignatureCheck {\n /** This value is true when a Web Bot Auth signature of the request verifies with a key of the directory. */\n readonly verified: boolean;\n /** This text is the label of the signature that the check examined last, or null. */\n readonly label: string | null;\n readonly keyId: string | null;\n /** This URL is the member of `Signature-Agent` that the signature covers, or null. */\n readonly agent: string | null;\n /** This text tells why the request does not verify. It is null when it verifies. */\n readonly reason: string | null;\n}\n\n// ── structured fields (RFC 9651): the parts that the signature headers use ──\n\n/** A token of a structured field, for example `ed25519` in `alg=ed25519`. */\nclass Token {\n constructor(readonly value: string) {}\n}\n\ntype BareItem = string | number | boolean | Uint8Array | Token;\ntype Params = ReadonlyArray<readonly [string, BareItem]>;\n\ninterface Item {\n readonly value: BareItem;\n readonly params: Params;\n}\n\ninterface InnerList {\n readonly items: readonly Item[];\n readonly params: Params;\n}\n\ntype Member = Item | InnerList;\n\nconst isInnerList = (member: Member): member is InnerList => \"items\" in member;\n\n/** This error tells that a structured field does not parse. */\nclass FieldError extends Error {}\n\nconst KEY_START = /[a-z*]/;\nconst KEY_CHAR = /[a-z0-9_\\-.*]/;\nconst TOKEN_START = /[A-Za-z*]/;\nconst TOKEN_CHAR = /[!#$%&'*+\\-.^_`|~0-9A-Za-z:/]/;\nconst BASE64 = /^[A-Za-z0-9+/=]*$/;\n\n/** This class reads one structured field from its text. */\nclass FieldParser {\n private at = 0;\n constructor(private readonly text: string) {}\n\n private peek(): string {\n return this.text[this.at] ?? \"\";\n }\n\n private spaces(): void {\n while (this.peek() === \" \") this.at += 1;\n }\n\n private ows(): void {\n while (this.peek() === \" \" || this.peek() === \"\\t\") this.at += 1;\n }\n\n dictionary(): Map<string, Member> {\n const out = new Map<string, Member>();\n this.spaces();\n while (this.at < this.text.length) {\n const key = this.key();\n let member: Member;\n if (this.peek() === \"=\") {\n this.at += 1;\n member = this.peek() === \"(\" ? this.innerList() : this.item();\n } else {\n member = { value: true, params: this.params() };\n }\n out.set(key, member);\n this.ows();\n if (this.at >= this.text.length) break;\n if (this.peek() !== \",\") throw new FieldError(`a \",\" is necessary at ${String(this.at)}`);\n this.at += 1;\n this.ows();\n if (this.at >= this.text.length) throw new FieldError(\"the field ends with a comma\");\n }\n return out;\n }\n\n /** This method reads one item and checks that the field has nothing after it. */\n wholeItem(): Item {\n this.spaces();\n const item = this.item();\n this.spaces();\n if (this.at < this.text.length) throw new FieldError(\"text after the item\");\n return item;\n }\n\n private key(): string {\n if (!KEY_START.test(this.peek())) throw new FieldError(`no key at ${String(this.at)}`);\n const start = this.at;\n while (KEY_CHAR.test(this.peek()) && this.at < this.text.length) this.at += 1;\n return this.text.slice(start, this.at);\n }\n\n private innerList(): InnerList {\n this.at += 1;\n const items: Item[] = [];\n for (;;) {\n this.spaces();\n if (this.peek() === \")\") {\n this.at += 1;\n return { items, params: this.params() };\n }\n if (this.at >= this.text.length) throw new FieldError(\"an inner list has no end\");\n items.push(this.item());\n if (this.peek() !== \" \" && this.peek() !== \")\")\n throw new FieldError(`a space or \")\" is necessary at ${String(this.at)}`);\n }\n }\n\n private item(): Item {\n const value = this.bare();\n return { value, params: this.params() };\n }\n\n private params(): Params {\n const out: Array<readonly [string, BareItem]> = [];\n while (this.peek() === \";\") {\n this.at += 1;\n this.spaces();\n const key = this.key();\n let value: BareItem = true;\n if (this.peek() === \"=\") {\n this.at += 1;\n value = this.bare();\n }\n const known = out.findIndex(([name]) => name === key);\n if (known === -1) out.push([key, value]);\n else out[known] = [key, value];\n }\n return out;\n }\n\n private bare(): BareItem {\n const char = this.peek();\n if (char === \"-\" || /[0-9]/.test(char)) return this.number();\n if (char === '\"') return this.string();\n if (char === \":\") return this.bytes();\n if (char === \"?\") return this.boolean();\n if (TOKEN_START.test(char)) return this.token();\n throw new FieldError(`no item at ${String(this.at)}`);\n }\n\n private number(): number {\n const match = /^-?(\\d{1,15})(\\.\\d{1,3})?/.exec(this.text.slice(this.at));\n if (match === null || (match[2] !== undefined && match[1]!.length > 12))\n throw new FieldError(`not a number at ${String(this.at)}`);\n this.at += match[0].length;\n return Number(match[0]);\n }\n\n private string(): string {\n this.at += 1;\n let out = \"\";\n for (;;) {\n const char = this.peek();\n if (char === \"\") throw new FieldError(\"a string has no end\");\n this.at += 1;\n if (char === \"\\\\\") {\n const next = this.peek();\n if (next !== '\"' && next !== \"\\\\\") throw new FieldError(\"a bad escape in a string\");\n out += next;\n this.at += 1;\n } else if (char === '\"') {\n return out;\n } else {\n const code = char.charCodeAt(0);\n if (code < 0x20 || code > 0x7e)\n throw new FieldError(\"a string holds a character that is not printable ASCII\");\n out += char;\n }\n }\n }\n\n private bytes(): Uint8Array {\n this.at += 1;\n const end = this.text.indexOf(\":\", this.at);\n if (end === -1) throw new FieldError(\"a byte sequence has no end\");\n const text = this.text.slice(this.at, end);\n if (!BASE64.test(text)) throw new FieldError(\"a byte sequence is not base64\");\n this.at = end + 1;\n return new Uint8Array(Buffer.from(text, \"base64\"));\n }\n\n private boolean(): boolean {\n const value = this.text.slice(this.at, this.at + 2);\n if (value !== \"?1\" && value !== \"?0\") throw new FieldError(\"not a boolean\");\n this.at += 2;\n return value === \"?1\";\n }\n\n private token(): Token {\n const start = this.at;\n this.at += 1;\n while (TOKEN_CHAR.test(this.peek()) && this.at < this.text.length) this.at += 1;\n return new Token(this.text.slice(start, this.at));\n }\n}\n\nconst serializeBare = (value: BareItem): string => {\n if (value instanceof Token) return value.value;\n if (value instanceof Uint8Array) return `:${Buffer.from(value).toString(\"base64\")}:`;\n if (typeof value === \"boolean\") return value ? \"?1\" : \"?0\";\n if (typeof value === \"number\")\n return Number.isInteger(value) ? String(value) : String(Math.round(value * 1000) / 1000);\n return `\"${value.replace(/[\"\\\\]/g, (char) => `\\\\${char}`)}\"`;\n};\n\nconst serializeParams = (params: Params): string =>\n params\n .map(([key, value]) => (value === true ? `;${key}` : `;${key}=${serializeBare(value)}`))\n .join(\"\");\n\nconst serializeItem = (item: Item): string =>\n `${serializeBare(item.value)}${serializeParams(item.params)}`;\n\nconst serializeMember = (member: Member): string =>\n isInnerList(member)\n ? `(${member.items.map(serializeItem).join(\" \")})${serializeParams(member.params)}`\n : serializeItem(member);\n\n/** This function tells if a text is a key of a structured field: a label of a signature, for example. */\nconst isKey = (text: string): boolean => /^[a-z*][a-z0-9_\\-.*]*$/.test(text);\n\n// ── keys ──\n\nconst base64url = (bytes: Uint8Array): string => Buffer.from(bytes).toString(\"base64url\");\n\nconst isKeyObject = (key: KeyInput): key is KeyObject =>\n typeof key === \"object\" && key !== null && \"asymmetricKeyType\" in key && \"export\" in key;\n\n/** This function reads a private key. Its errors do not hold the key. */\nconst privateKeyOf = (input: KeyInput): KeyObject => {\n let key: KeyObject;\n try {\n if (isKeyObject(input)) key = input;\n else if (typeof input === \"string\")\n key = input.trim().startsWith(\"{\")\n ? createPrivateKey({ key: JSON.parse(input) as JwkInput, format: \"jwk\" })\n : createPrivateKey(input);\n else if (input instanceof Uint8Array)\n key = createPrivateKey({ key: Buffer.from(input), format: \"der\", type: \"pkcs8\" });\n else key = createPrivateKey({ key: input, format: \"jwk\" });\n } catch (cause) {\n throw new Error(\n \"the private key of the signer does not parse: give an Ed25519 key as PKCS#8 (PEM or DER) or as a JWK\",\n { cause },\n );\n }\n if (key.type !== \"private\")\n throw new Error(\"the key of the signer is not a private key: give the Ed25519 private key\");\n if (key.asymmetricKeyType !== \"ed25519\")\n throw new Error(\n `the key of the signer is ${key.asymmetricKeyType ?? \"not an asymmetric key\"}, not ed25519: Web Bot Auth here uses Ed25519 keys`,\n );\n return key;\n};\n\n/** This function reads a public key, or the public part of a private key. Its errors do not hold the key. */\nconst publicKeyOf = (input: KeyInput): KeyObject => {\n let key: KeyObject;\n try {\n if (isKeyObject(input)) key = input.type === \"private\" ? createPublicKey(input) : input;\n else if (typeof input === \"string\")\n key = input.trim().startsWith(\"{\")\n ? createPublicKey({ key: JSON.parse(input) as JwkInput, format: \"jwk\" })\n : createPublicKey(input);\n else if (input instanceof Uint8Array) {\n const bytes = Buffer.from(input);\n try {\n key = createPublicKey({ key: bytes, format: \"der\", type: \"spki\" });\n } catch {\n key = createPublicKey(createPrivateKey({ key: bytes, format: \"der\", type: \"pkcs8\" }));\n }\n } else key = createPublicKey({ key: input, format: \"jwk\" });\n } catch (cause) {\n throw new Error(\"a key of the directory does not parse: give an Ed25519 key\", { cause });\n }\n if (key.asymmetricKeyType !== \"ed25519\")\n throw new Error(\n `a key of the directory is ${key.asymmetricKeyType ?? \"not an asymmetric key\"}, not ed25519`,\n );\n return key;\n};\n\n/** This function gives the JWK thumbprint of an Ed25519 public key (RFC 7638, RFC 8037 appendix A.3). */\nconst thumbprintOf = (x: string): string =>\n base64url(\n createHash(\"sha256\")\n .update(JSON.stringify({ crv: \"Ed25519\", kty: \"OKP\", x }), \"utf8\")\n .digest(),\n );\n\nconst directoryKeyOf = (key: KeyObject): DirectoryKey => {\n const jwk = key.export({ format: \"jwk\" });\n const x = typeof jwk.x === \"string\" ? jwk.x : \"\";\n return { kty: \"OKP\", crv: \"Ed25519\", kid: thumbprintOf(x), x, use: \"sig\" };\n};\n\n/**\n * This function makes the key directory for the operator to host: a JSON Web Key Set with each\n * public key and its thumbprint as `kid`. It takes public keys, or private keys, and it writes only\n * their public parts. Serve the JSON at `KEY_DIRECTORY_PATH` with the type `KEY_DIRECTORY_TYPE`.\n */\nexport const keyDirectory = (publicKeys: readonly KeyInput[]): KeyDirectory => {\n const keys = new Map<string, DirectoryKey>();\n for (const input of publicKeys) {\n const key = directoryKeyOf(publicKeyOf(input));\n keys.set(key.kid, key);\n }\n return { keys: [...keys.values()] };\n};\n\n// ── signing ──\n\n/** The parts of one signature. The signer and the tests use this function. */\nexport interface SignatureParts {\n /** The value of `@authority`: the host and a port that is not the default port, in lowercase. */\n readonly authority: string;\n readonly label: string;\n /** The key of the member of `Signature-Agent`. The draft uses the label of the signature. */\n readonly agentKey: string;\n /** The serialized value of the member: a string, and its parameters. */\n readonly agentValue: string;\n readonly keyId: string;\n readonly created: number;\n readonly expires: number;\n readonly nonce?: string | undefined;\n}\n\n/** This function gives the `@signature-params` value: the covered components and the parameters, in the order of the draft. */\nconst signatureParams = (parts: SignatureParts): string =>\n `(\"@authority\" \"signature-agent\";key=${serializeBare(parts.agentKey)});created=${String(parts.created)};keyid=${serializeBare(parts.keyId)};alg=\"ed25519\";expires=${String(parts.expires)}${parts.nonce === undefined ? \"\" : `;nonce=${serializeBare(parts.nonce)}`};tag=\"${WEB_BOT_AUTH_TAG}\"`;\n\n/** This function gives the signature base of RFC 9421, section 2.5, for the components of Web Bot Auth. */\nexport const signatureBase = (parts: SignatureParts): string =>\n [\n `\"@authority\": ${parts.authority}`,\n `\"signature-agent\";key=${serializeBare(parts.agentKey)}: ${parts.agentValue}`,\n `\"@signature-params\": ${signatureParams(parts)}`,\n ].join(\"\\n\");\n\n/** This function signs the parts with an Ed25519 key, and gives the three headers. */\nexport const signParts = (\n parts: SignatureParts,\n key: KeyObject,\n): {\n readonly \"signature-agent\": string;\n readonly \"signature-input\": string;\n readonly signature: string;\n} => {\n const signature = signBytes(null, Buffer.from(signatureBase(parts), \"utf8\"), key);\n return {\n \"signature-agent\": `${parts.agentKey}=${parts.agentValue}`,\n \"signature-input\": `${parts.label}=${signatureParams(parts)}`,\n signature: `${parts.label}=:${signature.toString(\"base64\")}:`,\n };\n};\n\nconst DEFAULT_LIFETIME_MS = 5 * 60_000;\nconst MAX_LIFETIME_MS = 24 * 60 * 60_000;\n\n/** This function checks the URL of `Signature-Agent`, and gives the URL and the serialized value of the member. */\nconst agentOf = (\n url: string,\n type: SignatureAgentType,\n): { readonly url: string; readonly value: string } => {\n let target: URL;\n try {\n target = new URL(url);\n } catch {\n throw new Error(\n `signatureAgent \"${url}\" is not a URL: give the https URL of the key directory`,\n );\n }\n if (target.protocol !== \"https:\")\n throw new Error(`signatureAgent \"${url}\" is not an https URL: the draft permits only https`);\n if (target.username !== \"\" || target.password !== \"\" || target.hash !== \"\")\n throw new Error(`signatureAgent \"${url}\" has a user name, a password or a fragment`);\n if (type === \"directory\") {\n if (target.pathname !== \"/\" || target.search !== \"\")\n throw new Error(\n `signatureAgent \"${url}\" is not an origin: the type directory takes only an origin, such as https://bot.example.com. For a key set on a path, set agentType to jwks_uri`,\n );\n return { url: target.origin, value: serializeBare(target.origin) };\n }\n return { url: target.href, value: `${serializeBare(target.href)};type=${type}` };\n};\n\n/**\n * This function makes a signer for Web Bot Auth with an Ed25519 key. Each signature covers\n * `@authority` and the member of `Signature-Agent`. It has a new random nonce, and it expires after\n * `lifetimeMs`. The signer keeps the private key in a closure: no property of the signer holds it.\n */\nexport const createWebBotAuthSigner = (options: WebBotAuthOptions): WebBotAuthSigner => {\n const key = privateKeyOf(options.privateKey);\n const publicKey = directoryKeyOf(createPublicKey(key));\n if (options.keyId !== undefined && options.keyId !== publicKey.kid)\n throw new Error(\n `keyId \"${options.keyId}\" is not the JWK thumbprint of the key (${publicKey.kid}): Web Bot Auth uses the thumbprint as keyid`,\n );\n const agent = agentOf(options.signatureAgent, options.agentType ?? \"directory\");\n const label = options.label ?? \"sig1\";\n if (!isKey(label))\n throw new Error(\n `label \"${label}\" is not a key of a structured field: use lowercase letters, digits, \"_\", \"-\", \".\" and \"*\"`,\n );\n const lifetimeMs = options.lifetimeMs ?? DEFAULT_LIFETIME_MS;\n if (!Number.isFinite(lifetimeMs) || lifetimeMs < 1000 || lifetimeMs > MAX_LIFETIME_MS)\n throw new RangeError(\n `lifetimeMs must be from 1000 (1 second) to ${String(MAX_LIFETIME_MS)} (24 hours), not ${String(lifetimeMs)}`,\n );\n const { kty, crv, x } = publicKey;\n return {\n keyId: publicKey.kid,\n signatureAgent: agent.url,\n publicKey: { kty, crv, x },\n sign(url, now) {\n const created = Math.floor(now / 1000);\n return signParts(\n {\n authority: url.host.toLowerCase(),\n label,\n agentKey: label,\n agentValue: agent.value,\n keyId: publicKey.kid,\n created,\n expires: created + Math.ceil(lifetimeMs / 1000),\n nonce: randomBytes(32).toString(\"base64\"),\n },\n key,\n );\n },\n };\n};\n\n/** This function tells if a value is a request signer, not the options of one. */\nexport const isRequestSigner = (value: RequestSigner | WebBotAuthOptions): value is RequestSigner =>\n typeof (value as Partial<RequestSigner>).sign === \"function\";\n\n/** This function gives a request signer: the signer itself, or a new signer from its options. */\nexport const signerOf = (\n value: RequestSigner | WebBotAuthOptions | undefined,\n): RequestSigner | undefined =>\n value === undefined ? undefined : isRequestSigner(value) ? value : createWebBotAuthSigner(value);\n\n// ── verification ──\n\n/** A signature can start this long before the clock of the verifier, for a small difference of the clocks. */\nconst CLOCK_SKEW_S = 60;\n\nconst headerLines = (\n headers: SignedRequest[\"headers\"],\n name: string,\n): readonly string[] | undefined => {\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== name || value === undefined) continue;\n return typeof value === \"string\" ? [value] : value;\n }\n return undefined;\n};\n\n/** This function gives the value of a header as RFC 9421 section 2.1 combines it: each line without its outer spaces, with \", \" between. */\nconst fieldValue = (headers: SignedRequest[\"headers\"], name: string): string | undefined =>\n headerLines(headers, name)\n ?.map((line) => line.replace(/\\r?\\n[ \\t]+/g, \" \").trim())\n .join(\", \");\n\n/** This function gives the value of one component of a request, or an error text. */\nconst componentValue = (\n component: Item,\n request: SignedRequest,\n target: URL,\n): { readonly value: string } | { readonly error: string } => {\n const name = component.value;\n if (typeof name !== \"string\") return { error: \"a component is not a string\" };\n const params = new Map(component.params);\n if (name.startsWith(\"@\")) {\n if (params.size > 0) return { error: `the parameters of ${name} are not supported` };\n switch (name) {\n case \"@method\":\n return { value: (request.method ?? \"GET\").toUpperCase() };\n case \"@authority\":\n return { value: target.host.toLowerCase() };\n case \"@scheme\":\n return { value: target.protocol.slice(0, -1).toLowerCase() };\n case \"@target-uri\":\n return { value: target.href };\n case \"@path\":\n return { value: target.pathname === \"\" ? \"/\" : target.pathname };\n case \"@query\":\n return { value: target.search === \"\" ? \"?\" : target.search };\n case \"@request-target\":\n return { value: `${target.pathname}${target.search}` };\n default:\n return { error: `the component ${name} is not supported` };\n }\n }\n const value = fieldValue(request.headers, name);\n if (value === undefined) return { error: `the request has no ${name} header` };\n if ([...params.keys()].some((param) => param !== \"key\"))\n return { error: `the parameters of ${name} are not supported` };\n const key = params.get(\"key\");\n if (key === undefined) return { value };\n if (typeof key !== \"string\") return { error: `the key of ${name} is not a string` };\n let member: Member | undefined;\n try {\n member = new FieldParser(value).dictionary().get(key);\n } catch (error) {\n return { error: `the ${name} header is not a dictionary: ${(error as Error).message}` };\n }\n if (member === undefined) return { error: `the ${name} header has no member ${key}` };\n return { value: serializeMember(member) };\n};\n\nconst failed = (\n reason: string,\n facts: { label?: string | null; keyId?: string | null; agent?: string | null } = {},\n): SignatureCheck => ({\n verified: false,\n label: facts.label ?? null,\n keyId: facts.keyId ?? null,\n agent: facts.agent ?? null,\n reason,\n});\n\n/**\n * This function verifies the Web Bot Auth signatures of a request with the keys of a directory. It\n * applies RFC 9421 section 3.2 and the profile of the draft. The profile asks for the tag\n * `web-bot-auth`, `created`, `expires` and `@authority`. It also asks for the member of\n * `Signature-Agent`, and a key with the thumbprint of `keyid`. The tests use it, and an operator can check a setup with it. It sends no request.\n */\nexport const verifySignature = (\n request: SignedRequest,\n directory: KeyDirectory,\n options: { readonly now?: number | undefined } = {},\n): SignatureCheck => {\n let target: URL;\n try {\n target = new URL(request.url);\n } catch {\n return failed(\"the URL of the request is not a URL\");\n }\n const inputText = fieldValue(request.headers, \"signature-input\");\n const signatureText = fieldValue(request.headers, \"signature\");\n if (inputText === undefined || signatureText === undefined)\n return failed(\"the request has no Signature-Input or no Signature header\");\n let inputs: Map<string, Member>;\n let signatures: Map<string, Member>;\n try {\n inputs = new FieldParser(inputText).dictionary();\n signatures = new FieldParser(signatureText).dictionary();\n } catch (error) {\n return failed(`a signature header does not parse: ${(error as Error).message}`);\n }\n const now = Math.floor((options.now ?? Date.now()) / 1000);\n const keys = new Map<string, KeyObject>();\n for (const entry of directory.keys) {\n try {\n const key = createPublicKey({\n key: { kty: entry.kty, crv: entry.crv, x: entry.x },\n format: \"jwk\",\n });\n keys.set(thumbprintOf(entry.x), key);\n } catch {\n // a key that does not parse verifies nothing\n }\n }\n let last: SignatureCheck = failed(\"the request has no Web Bot Auth signature\");\n for (const [label, input] of inputs) {\n if (!isInnerList(input)) continue;\n const params = new Map(input.params);\n if (params.get(\"tag\") !== WEB_BOT_AUTH_TAG) continue;\n const keyId = typeof params.get(\"keyid\") === \"string\" ? (params.get(\"keyid\") as string) : null;\n const covered = input.items;\n const names = covered.map((item) => serializeItem(item));\n const agentItem = covered.find((item) => item.value === \"signature-agent\");\n let agent: string | null = null;\n if (agentItem !== undefined) {\n const value = componentValue(agentItem, request, target);\n if (\"value\" in value) {\n try {\n const member = new FieldParser(value.value).wholeItem().value;\n agent = typeof member === \"string\" ? member : null;\n } catch {\n agent = null;\n }\n }\n }\n const facts = { label, keyId, agent };\n if (new Set(names).size !== names.length) {\n last = failed(\"a component is covered two times\", facts);\n continue;\n }\n if (!names.includes('\"@authority\"') && !names.includes('\"@target-uri\"')) {\n last = failed(\"the signature does not cover @authority or @target-uri\", facts);\n continue;\n }\n if (agentItem === undefined) {\n last = failed(\"the signature does not cover Signature-Agent\", facts);\n continue;\n }\n const created = params.get(\"created\");\n const expires = params.get(\"expires\");\n if (typeof created !== \"number\" || typeof expires !== \"number\") {\n last = failed(\"the signature has no created or no expires\", facts);\n continue;\n }\n if (expires <= now) {\n last = failed(\"the signature expired\", facts);\n continue;\n }\n if (created > now + CLOCK_SKEW_S) {\n last = failed(\"the signature was created in the future\", facts);\n continue;\n }\n const alg = params.get(\"alg\");\n if (alg !== undefined && alg !== \"ed25519\") {\n last = failed(`the algorithm ${serializeBare(alg)} is not ed25519`, facts);\n continue;\n }\n const key = keyId === null ? undefined : keys.get(keyId);\n if (key === undefined) {\n last = failed(\"no key of the directory has the thumbprint of keyid\", facts);\n continue;\n }\n const lines: string[] = [];\n let error: string | undefined;\n for (const item of covered) {\n const value = componentValue(item, request, target);\n if (\"error\" in value) {\n error = value.error;\n break;\n }\n lines.push(`${serializeItem(item)}: ${value.value}`);\n }\n if (error !== undefined) {\n last = failed(error, facts);\n continue;\n }\n lines.push(`\"@signature-params\": ${serializeMember(input)}`);\n const signature = signatures.get(label);\n if (\n signature === undefined ||\n isInnerList(signature) ||\n !(signature.value instanceof Uint8Array)\n ) {\n last = failed(`the Signature header has no byte sequence for ${label}`, facts);\n continue;\n }\n const good = verifyBytes(null, Buffer.from(lines.join(\"\\n\"), \"utf8\"), key, signature.value);\n if (good) return { verified: true, label, keyId, agent, reason: null };\n last = failed(\"the signature does not match the signature base\", facts);\n }\n return last;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,qBAAqB;;AAGlC,MAAa,qBAAqB;;AAGlC,MAAa,mBAAmB;;AAoGhC,IAAM,QAAN,MAAY;CACW;CAArB,YAAY,OAAwB;EAAf,KAAA,QAAA;CAAgB;AACvC;AAiBA,MAAM,eAAe,WAAwC,WAAW;;AAGxE,IAAM,aAAN,cAAyB,MAAM,CAAC;AAEhC,MAAM,YAAY;AAClB,MAAM,WAAW;AACjB,MAAM,cAAc;AACpB,MAAM,aAAa;AACnB,MAAM,SAAS;;AAGf,IAAM,cAAN,MAAkB;CAEa;CAD7B,KAAa;CACb,YAAY,MAA+B;EAAd,KAAA,OAAA;CAAe;CAE5C,OAAuB;EACrB,OAAO,KAAK,KAAK,KAAK,OAAO;CAC/B;CAEA,SAAuB;EACrB,OAAO,KAAK,KAAK,MAAM,KAAK,KAAK,MAAM;CACzC;CAEA,MAAoB;EAClB,OAAO,KAAK,KAAK,MAAM,OAAO,KAAK,KAAK,MAAM,KAAM,KAAK,MAAM;CACjE;CAEA,aAAkC;EAChC,MAAM,sBAAM,IAAI,IAAoB;EACpC,KAAK,OAAO;EACZ,OAAO,KAAK,KAAK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,QAAQ,KAAA,KAAa,QAAQ,WAAW;GAC1C,OAAO,OAAO,iBAAiB,cAAc,GAAG,EAAE,kBAAkB,KAAK;GACzE;EACF;EACA,MAAM,MAAM,UAAU,OAAO,KAAA,IAAY,KAAK,IAAI,KAAK;EACvD,IAAI,QAAQ,KAAA,GAAW;GACrB,OAAO,OAAO,uDAAuD,KAAK;GAC1E;EACF;EACA,MAAM,QAAkB,CAAC;EACzB,IAAI;EACJ,KAAK,MAAM,QAAQ,SAAS;GAC1B,MAAM,QAAQ,eAAe,MAAM,SAAS,MAAM;GAClD,IAAI,WAAW,OAAO;IACpB,QAAQ,MAAM;IACd;GACF;GACA,MAAM,KAAK,GAAG,cAAc,IAAI,EAAE,IAAI,MAAM,OAAO;EACrD;EACA,IAAI,UAAU,KAAA,GAAW;GACvB,OAAO,OAAO,OAAO,KAAK;GAC1B;EACF;EACA,MAAM,KAAK,wBAAwB,gBAAgB,KAAK,GAAG;EAC3D,MAAM,YAAY,WAAW,IAAI,KAAK;EACtC,IACE,cAAc,KAAA,KACd,YAAY,SAAS,KACrB,EAAE,UAAU,iBAAiB,aAC7B;GACA,OAAO,OAAO,iDAAiD,SAAS,KAAK;GAC7E;EACF;EAEA,IADaC,OAAY,MAAM,OAAO,KAAK,MAAM,KAAK,IAAI,GAAG,MAAM,GAAG,KAAK,UAAU,KAC9E,GAAG,OAAO;GAAE,UAAU;GAAM;GAAO;GAAO;GAAO,QAAQ;EAAK;EACrE,OAAO,OAAO,mDAAmD,KAAK;CACxE;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"webbotauth-W3GXY3dy.mjs","names":["signBytes","verifyBytes"],"sources":["../src/webbotauth.ts"],"sourcesContent":["import type { JsonWebKeyInput, KeyObject } from \"node:crypto\";\nimport {\n createHash,\n createPrivateKey,\n createPublicKey,\n randomBytes,\n sign as signBytes,\n verify as verifyBytes,\n} from \"node:crypto\";\n\n/**\n * Signed requests: HTTP Message Signatures (RFC 9421), as the IETF Web Bot Auth profile tells\n * (`draft-ietf-webbotauth-httpsig-protocol-00`, 1 September 2026). A signature lets a site verify that\n * a request comes from the holder of a key that the operator publishes.\n *\n * - Each request gets three headers: `Signature-Agent`, `Signature-Input` and `Signature`.\n * - `Signature-Agent` is a dictionary. Its member names the key directory of the operator.\n * - The signature covers `@authority` and that member of `Signature-Agent`.\n * - The parameters are `created`, `keyid` (the JWK thumbprint of the key), `alg=\"ed25519\"`,\n * `expires`, a random `nonce` and `tag=\"web-bot-auth\"`.\n * - The key is an Ed25519 key, and `node:crypto` signs. The package adds no dependency.\n *\n * A signature adds an identity. It does not replace the `User-Agent` header, which stays honest.\n */\n\n/** The path of the key directory on the host of the operator (the well-known URI of the draft). */\nexport const KEY_DIRECTORY_PATH = \"/.well-known/http-message-signatures-directory\";\n\n/** The media type of the key directory. The host of the directory sends it as `Content-Type`. */\nexport const KEY_DIRECTORY_TYPE = \"application/http-message-signatures-directory+json\";\n\n/** The value of the `tag` parameter of a Web Bot Auth signature. */\nexport const WEB_BOT_AUTH_TAG = \"web-bot-auth\";\n\n/**\n * This value tells how a site finds the keys from the URL of `Signature-Agent`:\n *\n * - `directory` (the default): the URL is an origin, and the keys are at `KEY_DIRECTORY_PATH` on it.\n * - `jwks_uri`: the URL is the address of a JSON Web Key Set, on any path.\n */\nexport type SignatureAgentType = \"directory\" | \"jwks_uri\";\n\n/** A key in one of the forms that `node:crypto` reads: a `KeyObject`, PEM text, DER bytes (PKCS#8 or SPKI) or a JWK. */\n/**\n * This type is a JSON Web Key, as `createPrivateKey` of `node:crypto` reads it. The type comes from `JsonWebKeyInput`, which\n * `@types/node` 22 and 26 both have: version 26 has no `JsonWebKey` export in `node:crypto`.\n */\nexport type JwkInput = JsonWebKeyInput[\"key\"];\n\nexport type KeyInput = KeyObject | string | Uint8Array | JwkInput;\n\n/** These options make a signer for Web Bot Auth. */\nexport interface WebBotAuthOptions {\n /** This key signs. It is an Ed25519 private key: a `KeyObject`, PKCS#8 (PEM text or DER bytes) or a JWK with `d`. */\n readonly privateKey: KeyInput;\n /**\n * This text is the `keyid` of each signature: the JWK thumbprint of the key (RFC 8037). The signer\n * calculates it. A value that is not the thumbprint of the key throws an error.\n */\n readonly keyId?: string | undefined;\n /**\n * This URL tells a site where the keys are. For the type `directory`, it is an https origin, for\n * example `https://bot.example.com`. For `jwks_uri`, it is the https URL of a JSON Web Key Set.\n */\n readonly signatureAgent: string;\n /** This value tells how a site finds the keys from `signatureAgent`. The default is `directory`. */\n readonly agentType?: SignatureAgentType | undefined;\n /** This value is the time that a signature stays valid, in milliseconds. The default is 5 minutes, and the maximum is 24 hours. */\n readonly lifetimeMs?: number | undefined;\n /** This text is the label of the signature, and the key of the member of `Signature-Agent`. The default is `sig1`. */\n readonly label?: string | undefined;\n}\n\n/**\n * A request signer gives the signature headers of one request. The crawler uses it for each\n * request, robots.txt too. `createWebBotAuthSigner` makes one. A signer of your own can sign with a\n * key in a hardware module, for example.\n */\nexport interface RequestSigner {\n /** This text is the `keyid` of the signatures. */\n readonly keyId: string;\n /** This URL is the value of the member of `Signature-Agent`: where a site finds the keys. */\n readonly signatureAgent: string;\n /** This method gives the headers that sign a request to `url` at the time `now` (milliseconds since the epoch). */\n sign(url: URL, now: number): Readonly<Record<string, string>>;\n}\n\n/** The signer that `createWebBotAuthSigner` makes. It also gives its public key for the key directory. */\nexport interface WebBotAuthSigner extends RequestSigner {\n /** This JWK is the public key of the signer, with no private part. Give it to `keyDirectory`. */\n readonly publicKey: JwkInput;\n}\n\n/** One key of a key directory: an Ed25519 public key as a JWK, with its thumbprint as `kid`. */\nexport interface DirectoryKey {\n readonly kty: \"OKP\";\n readonly crv: \"Ed25519\";\n readonly kid: string;\n readonly x: string;\n readonly use: \"sig\";\n}\n\n/** A key directory: a JSON Web Key Set. The operator serves it as JSON at `KEY_DIRECTORY_PATH`, with the type `KEY_DIRECTORY_TYPE`. */\nexport interface KeyDirectory {\n readonly keys: readonly DirectoryKey[];\n}\n\n/** The parts of a request that `verifySignature` reads. */\nexport interface SignedRequest {\n readonly url: string;\n /** The default is `GET`. */\n readonly method?: string | undefined;\n /** These are the headers of the request. A name can be in any case, and a header can have more than one line. */\n readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;\n}\n\n/** The result of `verifySignature`. */\nexport interface SignatureCheck {\n /** This value is true when a Web Bot Auth signature of the request verifies with a key of the directory. */\n readonly verified: boolean;\n /** This text is the label of the signature that the check examined last, or null. */\n readonly label: string | null;\n readonly keyId: string | null;\n /** This URL is the member of `Signature-Agent` that the signature covers, or null. */\n readonly agent: string | null;\n /** This text tells why the request does not verify. It is null when it verifies. */\n readonly reason: string | null;\n}\n\n// ── structured fields (RFC 9651): the parts that the signature headers use ──\n\n/** A token of a structured field, for example `ed25519` in `alg=ed25519`. */\nclass Token {\n constructor(readonly value: string) {}\n}\n\ntype BareItem = string | number | boolean | Uint8Array | Token;\ntype Params = ReadonlyArray<readonly [string, BareItem]>;\n\ninterface Item {\n readonly value: BareItem;\n readonly params: Params;\n}\n\ninterface InnerList {\n readonly items: readonly Item[];\n readonly params: Params;\n}\n\ntype Member = Item | InnerList;\n\nconst isInnerList = (member: Member): member is InnerList => \"items\" in member;\n\n/** This error tells that a structured field does not parse. */\nclass FieldError extends Error {}\n\nconst KEY_START = /[a-z*]/;\nconst KEY_CHAR = /[a-z0-9_\\-.*]/;\nconst TOKEN_START = /[A-Za-z*]/;\nconst TOKEN_CHAR = /[!#$%&'*+\\-.^_`|~0-9A-Za-z:/]/;\nconst BASE64 = /^[A-Za-z0-9+/=]*$/;\n\n/** This class reads one structured field from its text. */\nclass FieldParser {\n private at = 0;\n constructor(private readonly text: string) {}\n\n private peek(): string {\n return this.text[this.at] ?? \"\";\n }\n\n private spaces(): void {\n while (this.peek() === \" \") this.at += 1;\n }\n\n private ows(): void {\n while (this.peek() === \" \" || this.peek() === \"\\t\") this.at += 1;\n }\n\n dictionary(): Map<string, Member> {\n const out = new Map<string, Member>();\n this.spaces();\n while (this.at < this.text.length) {\n const key = this.key();\n let member: Member;\n if (this.peek() === \"=\") {\n this.at += 1;\n member = this.peek() === \"(\" ? this.innerList() : this.item();\n } else {\n member = { value: true, params: this.params() };\n }\n out.set(key, member);\n this.ows();\n if (this.at >= this.text.length) break;\n if (this.peek() !== \",\") throw new FieldError(`a \",\" is necessary at ${String(this.at)}`);\n this.at += 1;\n this.ows();\n if (this.at >= this.text.length) throw new FieldError(\"the field ends with a comma\");\n }\n return out;\n }\n\n /** This method reads one item and checks that the field has nothing after it. */\n wholeItem(): Item {\n this.spaces();\n const item = this.item();\n this.spaces();\n if (this.at < this.text.length) throw new FieldError(\"text after the item\");\n return item;\n }\n\n private key(): string {\n if (!KEY_START.test(this.peek())) throw new FieldError(`no key at ${String(this.at)}`);\n const start = this.at;\n while (KEY_CHAR.test(this.peek()) && this.at < this.text.length) this.at += 1;\n return this.text.slice(start, this.at);\n }\n\n private innerList(): InnerList {\n this.at += 1;\n const items: Item[] = [];\n for (;;) {\n this.spaces();\n if (this.peek() === \")\") {\n this.at += 1;\n return { items, params: this.params() };\n }\n if (this.at >= this.text.length) throw new FieldError(\"an inner list has no end\");\n items.push(this.item());\n if (this.peek() !== \" \" && this.peek() !== \")\")\n throw new FieldError(`a space or \")\" is necessary at ${String(this.at)}`);\n }\n }\n\n private item(): Item {\n const value = this.bare();\n return { value, params: this.params() };\n }\n\n private params(): Params {\n const out: Array<readonly [string, BareItem]> = [];\n while (this.peek() === \";\") {\n this.at += 1;\n this.spaces();\n const key = this.key();\n let value: BareItem = true;\n if (this.peek() === \"=\") {\n this.at += 1;\n value = this.bare();\n }\n const known = out.findIndex(([name]) => name === key);\n if (known === -1) out.push([key, value]);\n else out[known] = [key, value];\n }\n return out;\n }\n\n private bare(): BareItem {\n const char = this.peek();\n if (char === \"-\" || /[0-9]/.test(char)) return this.number();\n if (char === '\"') return this.string();\n if (char === \":\") return this.bytes();\n if (char === \"?\") return this.boolean();\n if (TOKEN_START.test(char)) return this.token();\n throw new FieldError(`no item at ${String(this.at)}`);\n }\n\n private number(): number {\n const match = /^-?(\\d{1,15})(\\.\\d{1,3})?/.exec(this.text.slice(this.at));\n if (match === null || (match[2] !== undefined && match[1]!.length > 12))\n throw new FieldError(`not a number at ${String(this.at)}`);\n this.at += match[0].length;\n return Number(match[0]);\n }\n\n private string(): string {\n this.at += 1;\n let out = \"\";\n for (;;) {\n const char = this.peek();\n if (char === \"\") throw new FieldError(\"a string has no end\");\n this.at += 1;\n if (char === \"\\\\\") {\n const next = this.peek();\n if (next !== '\"' && next !== \"\\\\\") throw new FieldError(\"a bad escape in a string\");\n out += next;\n this.at += 1;\n } else if (char === '\"') {\n return out;\n } else {\n const code = char.charCodeAt(0);\n if (code < 0x20 || code > 0x7e)\n throw new FieldError(\"a string holds a character that is not printable ASCII\");\n out += char;\n }\n }\n }\n\n private bytes(): Uint8Array {\n this.at += 1;\n const end = this.text.indexOf(\":\", this.at);\n if (end === -1) throw new FieldError(\"a byte sequence has no end\");\n const text = this.text.slice(this.at, end);\n if (!BASE64.test(text)) throw new FieldError(\"a byte sequence is not base64\");\n this.at = end + 1;\n return new Uint8Array(Buffer.from(text, \"base64\"));\n }\n\n private boolean(): boolean {\n const value = this.text.slice(this.at, this.at + 2);\n if (value !== \"?1\" && value !== \"?0\") throw new FieldError(\"not a boolean\");\n this.at += 2;\n return value === \"?1\";\n }\n\n private token(): Token {\n const start = this.at;\n this.at += 1;\n while (TOKEN_CHAR.test(this.peek()) && this.at < this.text.length) this.at += 1;\n return new Token(this.text.slice(start, this.at));\n }\n}\n\nconst serializeBare = (value: BareItem): string => {\n if (value instanceof Token) return value.value;\n if (value instanceof Uint8Array) return `:${Buffer.from(value).toString(\"base64\")}:`;\n if (typeof value === \"boolean\") return value ? \"?1\" : \"?0\";\n if (typeof value === \"number\")\n return Number.isInteger(value) ? String(value) : String(Math.round(value * 1000) / 1000);\n return `\"${value.replace(/[\"\\\\]/g, (char) => `\\\\${char}`)}\"`;\n};\n\nconst serializeParams = (params: Params): string =>\n params\n .map(([key, value]) => (value === true ? `;${key}` : `;${key}=${serializeBare(value)}`))\n .join(\"\");\n\nconst serializeItem = (item: Item): string =>\n `${serializeBare(item.value)}${serializeParams(item.params)}`;\n\nconst serializeMember = (member: Member): string =>\n isInnerList(member)\n ? `(${member.items.map(serializeItem).join(\" \")})${serializeParams(member.params)}`\n : serializeItem(member);\n\n/** This function tells if a text is a key of a structured field: a label of a signature, for example. */\nconst isKey = (text: string): boolean => /^[a-z*][a-z0-9_\\-.*]*$/.test(text);\n\n// ── keys ──\n\nconst base64url = (bytes: Uint8Array): string => Buffer.from(bytes).toString(\"base64url\");\n\nconst isKeyObject = (key: KeyInput): key is KeyObject =>\n typeof key === \"object\" && key !== null && \"asymmetricKeyType\" in key && \"export\" in key;\n\n/** This function reads a private key. Its errors do not hold the key. */\nconst privateKeyOf = (input: KeyInput): KeyObject => {\n let key: KeyObject;\n try {\n if (isKeyObject(input)) key = input;\n else if (typeof input === \"string\")\n key = input.trim().startsWith(\"{\")\n ? createPrivateKey({ key: JSON.parse(input) as JwkInput, format: \"jwk\" })\n : createPrivateKey(input);\n else if (input instanceof Uint8Array)\n key = createPrivateKey({ key: Buffer.from(input), format: \"der\", type: \"pkcs8\" });\n else key = createPrivateKey({ key: input, format: \"jwk\" });\n } catch (cause) {\n throw new Error(\n \"the private key of the signer does not parse: give an Ed25519 key as PKCS#8 (PEM or DER) or as a JWK\",\n { cause },\n );\n }\n if (key.type !== \"private\")\n throw new Error(\"the key of the signer is not a private key: give the Ed25519 private key\");\n if (key.asymmetricKeyType !== \"ed25519\")\n throw new Error(\n `the key of the signer is ${key.asymmetricKeyType ?? \"not an asymmetric key\"}, not ed25519: Web Bot Auth here uses Ed25519 keys`,\n );\n return key;\n};\n\n/** This function reads a public key, or the public part of a private key. Its errors do not hold the key. */\nconst publicKeyOf = (input: KeyInput): KeyObject => {\n let key: KeyObject;\n try {\n if (isKeyObject(input)) key = input.type === \"private\" ? createPublicKey(input) : input;\n else if (typeof input === \"string\")\n key = input.trim().startsWith(\"{\")\n ? createPublicKey({ key: JSON.parse(input) as JwkInput, format: \"jwk\" })\n : createPublicKey(input);\n else if (input instanceof Uint8Array) {\n const bytes = Buffer.from(input);\n try {\n key = createPublicKey({ key: bytes, format: \"der\", type: \"spki\" });\n } catch {\n key = createPublicKey(createPrivateKey({ key: bytes, format: \"der\", type: \"pkcs8\" }));\n }\n } else key = createPublicKey({ key: input, format: \"jwk\" });\n } catch (cause) {\n throw new Error(\"a key of the directory does not parse: give an Ed25519 key\", { cause });\n }\n if (key.asymmetricKeyType !== \"ed25519\")\n throw new Error(\n `a key of the directory is ${key.asymmetricKeyType ?? \"not an asymmetric key\"}, not ed25519`,\n );\n return key;\n};\n\n/** This function gives the JWK thumbprint of an Ed25519 public key (RFC 7638, RFC 8037 appendix A.3). */\nconst thumbprintOf = (x: string): string =>\n base64url(\n createHash(\"sha256\")\n .update(JSON.stringify({ crv: \"Ed25519\", kty: \"OKP\", x }), \"utf8\")\n .digest(),\n );\n\nconst directoryKeyOf = (key: KeyObject): DirectoryKey => {\n const jwk = key.export({ format: \"jwk\" });\n const x = typeof jwk.x === \"string\" ? jwk.x : \"\";\n return { kty: \"OKP\", crv: \"Ed25519\", kid: thumbprintOf(x), x, use: \"sig\" };\n};\n\n/**\n * This function makes the key directory for the operator to host: a JSON Web Key Set with each\n * public key and its thumbprint as `kid`. It takes public keys, or private keys, and it writes only\n * their public parts. Serve the JSON at `KEY_DIRECTORY_PATH` with the type `KEY_DIRECTORY_TYPE`.\n */\nexport const keyDirectory = (publicKeys: readonly KeyInput[]): KeyDirectory => {\n const keys = new Map<string, DirectoryKey>();\n for (const input of publicKeys) {\n const key = directoryKeyOf(publicKeyOf(input));\n keys.set(key.kid, key);\n }\n return { keys: [...keys.values()] };\n};\n\n// ── signing ──\n\n/** The parts of one signature. The signer and the tests use this function. */\nexport interface SignatureParts {\n /** The value of `@authority`: the host and a port that is not the default port, in lowercase. */\n readonly authority: string;\n readonly label: string;\n /** The key of the member of `Signature-Agent`. The draft uses the label of the signature. */\n readonly agentKey: string;\n /** The serialized value of the member: a string, and its parameters. */\n readonly agentValue: string;\n readonly keyId: string;\n readonly created: number;\n readonly expires: number;\n readonly nonce?: string | undefined;\n}\n\n/** This function gives the `@signature-params` value: the covered components and the parameters, in the order of the draft. */\nconst signatureParams = (parts: SignatureParts): string =>\n `(\"@authority\" \"signature-agent\";key=${serializeBare(parts.agentKey)});created=${String(parts.created)};keyid=${serializeBare(parts.keyId)};alg=\"ed25519\";expires=${String(parts.expires)}${parts.nonce === undefined ? \"\" : `;nonce=${serializeBare(parts.nonce)}`};tag=\"${WEB_BOT_AUTH_TAG}\"`;\n\n/** This function gives the signature base of RFC 9421, section 2.5, for the components of Web Bot Auth. */\nexport const signatureBase = (parts: SignatureParts): string =>\n [\n `\"@authority\": ${parts.authority}`,\n `\"signature-agent\";key=${serializeBare(parts.agentKey)}: ${parts.agentValue}`,\n `\"@signature-params\": ${signatureParams(parts)}`,\n ].join(\"\\n\");\n\n/** This function signs the parts with an Ed25519 key, and gives the three headers. */\nexport const signParts = (\n parts: SignatureParts,\n key: KeyObject,\n): {\n readonly \"signature-agent\": string;\n readonly \"signature-input\": string;\n readonly signature: string;\n} => {\n const signature = signBytes(null, Buffer.from(signatureBase(parts), \"utf8\"), key);\n return {\n \"signature-agent\": `${parts.agentKey}=${parts.agentValue}`,\n \"signature-input\": `${parts.label}=${signatureParams(parts)}`,\n signature: `${parts.label}=:${signature.toString(\"base64\")}:`,\n };\n};\n\nconst DEFAULT_LIFETIME_MS = 5 * 60_000;\nconst MAX_LIFETIME_MS = 24 * 60 * 60_000;\n\n/** This function checks the URL of `Signature-Agent`, and gives the URL and the serialized value of the member. */\nconst agentOf = (\n url: string,\n type: SignatureAgentType,\n): { readonly url: string; readonly value: string } => {\n let target: URL;\n try {\n target = new URL(url);\n } catch {\n throw new Error(\n `signatureAgent \"${url}\" is not a URL: give the https URL of the key directory`,\n );\n }\n if (target.protocol !== \"https:\")\n throw new Error(`signatureAgent \"${url}\" is not an https URL: the draft permits only https`);\n if (target.username !== \"\" || target.password !== \"\" || target.hash !== \"\")\n throw new Error(`signatureAgent \"${url}\" has a user name, a password or a fragment`);\n if (type === \"directory\") {\n if (target.pathname !== \"/\" || target.search !== \"\")\n throw new Error(\n `signatureAgent \"${url}\" is not an origin: the type directory takes only an origin, such as https://bot.example.com. For a key set on a path, set agentType to jwks_uri`,\n );\n return { url: target.origin, value: serializeBare(target.origin) };\n }\n return { url: target.href, value: `${serializeBare(target.href)};type=${type}` };\n};\n\n/**\n * This function makes a signer for Web Bot Auth with an Ed25519 key. Each signature covers\n * `@authority` and the member of `Signature-Agent`. It has a new random nonce, and it expires after\n * `lifetimeMs`. The signer keeps the private key in a closure: no property of the signer holds it.\n */\nexport const createWebBotAuthSigner = (options: WebBotAuthOptions): WebBotAuthSigner => {\n const key = privateKeyOf(options.privateKey);\n const publicKey = directoryKeyOf(createPublicKey(key));\n if (options.keyId !== undefined && options.keyId !== publicKey.kid)\n throw new Error(\n `keyId \"${options.keyId}\" is not the JWK thumbprint of the key (${publicKey.kid}): Web Bot Auth uses the thumbprint as keyid`,\n );\n const agent = agentOf(options.signatureAgent, options.agentType ?? \"directory\");\n const label = options.label ?? \"sig1\";\n if (!isKey(label))\n throw new Error(\n `label \"${label}\" is not a key of a structured field: use lowercase letters, digits, \"_\", \"-\", \".\" and \"*\"`,\n );\n const lifetimeMs = options.lifetimeMs ?? DEFAULT_LIFETIME_MS;\n if (!Number.isFinite(lifetimeMs) || lifetimeMs < 1000 || lifetimeMs > MAX_LIFETIME_MS)\n throw new RangeError(\n `lifetimeMs must be from 1000 (1 second) to ${String(MAX_LIFETIME_MS)} (24 hours), not ${String(lifetimeMs)}`,\n );\n const { kty, crv, x } = publicKey;\n return {\n keyId: publicKey.kid,\n signatureAgent: agent.url,\n publicKey: { kty, crv, x },\n sign(url, now) {\n const created = Math.floor(now / 1000);\n return signParts(\n {\n authority: url.host.toLowerCase(),\n label,\n agentKey: label,\n agentValue: agent.value,\n keyId: publicKey.kid,\n created,\n expires: created + Math.ceil(lifetimeMs / 1000),\n nonce: randomBytes(32).toString(\"base64\"),\n },\n key,\n );\n },\n };\n};\n\n/** This function tells if a value is a request signer, not the options of one. */\nexport const isRequestSigner = (value: RequestSigner | WebBotAuthOptions): value is RequestSigner =>\n typeof (value as Partial<RequestSigner>).sign === \"function\";\n\n/** This function gives a request signer: the signer itself, or a new signer from its options. */\nexport const signerOf = (\n value: RequestSigner | WebBotAuthOptions | undefined,\n): RequestSigner | undefined =>\n value === undefined ? undefined : isRequestSigner(value) ? value : createWebBotAuthSigner(value);\n\n// ── verification ──\n\n/** A signature can start this long before the clock of the verifier, for a small difference of the clocks. */\nconst CLOCK_SKEW_S = 60;\n\nconst headerLines = (\n headers: SignedRequest[\"headers\"],\n name: string,\n): readonly string[] | undefined => {\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== name || value === undefined) continue;\n return typeof value === \"string\" ? [value] : value;\n }\n return undefined;\n};\n\n/** This function gives the value of a header as RFC 9421 section 2.1 combines it: each line without its outer spaces, with \", \" between. */\nconst fieldValue = (headers: SignedRequest[\"headers\"], name: string): string | undefined =>\n headerLines(headers, name)\n ?.map((line) => line.replace(/\\r?\\n[ \\t]+/g, \" \").trim())\n .join(\", \");\n\n/** This function gives the value of one component of a request, or an error text. */\nconst componentValue = (\n component: Item,\n request: SignedRequest,\n target: URL,\n): { readonly value: string } | { readonly error: string } => {\n const name = component.value;\n if (typeof name !== \"string\") return { error: \"a component is not a string\" };\n const params = new Map(component.params);\n if (name.startsWith(\"@\")) {\n if (params.size > 0) return { error: `the parameters of ${name} are not supported` };\n switch (name) {\n case \"@method\":\n return { value: (request.method ?? \"GET\").toUpperCase() };\n case \"@authority\":\n return { value: target.host.toLowerCase() };\n case \"@scheme\":\n return { value: target.protocol.slice(0, -1).toLowerCase() };\n case \"@target-uri\":\n return { value: target.href };\n case \"@path\":\n return { value: target.pathname === \"\" ? \"/\" : target.pathname };\n case \"@query\":\n return { value: target.search === \"\" ? \"?\" : target.search };\n case \"@request-target\":\n return { value: `${target.pathname}${target.search}` };\n default:\n return { error: `the component ${name} is not supported` };\n }\n }\n const value = fieldValue(request.headers, name);\n if (value === undefined) return { error: `the request has no ${name} header` };\n if ([...params.keys()].some((param) => param !== \"key\"))\n return { error: `the parameters of ${name} are not supported` };\n const key = params.get(\"key\");\n if (key === undefined) return { value };\n if (typeof key !== \"string\") return { error: `the key of ${name} is not a string` };\n let member: Member | undefined;\n try {\n member = new FieldParser(value).dictionary().get(key);\n } catch (error) {\n return { error: `the ${name} header is not a dictionary: ${(error as Error).message}` };\n }\n if (member === undefined) return { error: `the ${name} header has no member ${key}` };\n return { value: serializeMember(member) };\n};\n\nconst failed = (\n reason: string,\n facts: { label?: string | null; keyId?: string | null; agent?: string | null } = {},\n): SignatureCheck => ({\n verified: false,\n label: facts.label ?? null,\n keyId: facts.keyId ?? null,\n agent: facts.agent ?? null,\n reason,\n});\n\n/**\n * This function verifies the Web Bot Auth signatures of a request with the keys of a directory. It\n * applies RFC 9421 section 3.2 and the profile of the draft. The profile asks for the tag\n * `web-bot-auth`, `created`, `expires` and `@authority`. It also asks for the member of\n * `Signature-Agent`, and a key with the thumbprint of `keyid`. The tests use it, and an operator can check a setup with it. It sends no request.\n */\nexport const verifySignature = (\n request: SignedRequest,\n directory: KeyDirectory,\n options: { readonly now?: number | undefined } = {},\n): SignatureCheck => {\n let target: URL;\n try {\n target = new URL(request.url);\n } catch {\n return failed(\"the URL of the request is not a URL\");\n }\n const inputText = fieldValue(request.headers, \"signature-input\");\n const signatureText = fieldValue(request.headers, \"signature\");\n if (inputText === undefined || signatureText === undefined)\n return failed(\"the request has no Signature-Input or no Signature header\");\n let inputs: Map<string, Member>;\n let signatures: Map<string, Member>;\n try {\n inputs = new FieldParser(inputText).dictionary();\n signatures = new FieldParser(signatureText).dictionary();\n } catch (error) {\n return failed(`a signature header does not parse: ${(error as Error).message}`);\n }\n const now = Math.floor((options.now ?? Date.now()) / 1000);\n const keys = new Map<string, KeyObject>();\n for (const entry of directory.keys) {\n try {\n const key = createPublicKey({\n key: { kty: entry.kty, crv: entry.crv, x: entry.x },\n format: \"jwk\",\n });\n keys.set(thumbprintOf(entry.x), key);\n } catch {\n // a key that does not parse verifies nothing\n }\n }\n let last: SignatureCheck = failed(\"the request has no Web Bot Auth signature\");\n for (const [label, input] of inputs) {\n if (!isInnerList(input)) continue;\n const params = new Map(input.params);\n if (params.get(\"tag\") !== WEB_BOT_AUTH_TAG) continue;\n const keyId = typeof params.get(\"keyid\") === \"string\" ? (params.get(\"keyid\") as string) : null;\n const covered = input.items;\n const names = covered.map((item) => serializeItem(item));\n const agentItem = covered.find((item) => item.value === \"signature-agent\");\n let agent: string | null = null;\n if (agentItem !== undefined) {\n const value = componentValue(agentItem, request, target);\n if (\"value\" in value) {\n try {\n const member = new FieldParser(value.value).wholeItem().value;\n agent = typeof member === \"string\" ? member : null;\n } catch {\n agent = null;\n }\n }\n }\n const facts = { label, keyId, agent };\n if (new Set(names).size !== names.length) {\n last = failed(\"a component is covered two times\", facts);\n continue;\n }\n if (!names.includes('\"@authority\"') && !names.includes('\"@target-uri\"')) {\n last = failed(\"the signature does not cover @authority or @target-uri\", facts);\n continue;\n }\n if (agentItem === undefined) {\n last = failed(\"the signature does not cover Signature-Agent\", facts);\n continue;\n }\n const created = params.get(\"created\");\n const expires = params.get(\"expires\");\n if (typeof created !== \"number\" || typeof expires !== \"number\") {\n last = failed(\"the signature has no created or no expires\", facts);\n continue;\n }\n if (expires <= now) {\n last = failed(\"the signature expired\", facts);\n continue;\n }\n if (created > now + CLOCK_SKEW_S) {\n last = failed(\"the signature was created in the future\", facts);\n continue;\n }\n const alg = params.get(\"alg\");\n if (alg !== undefined && alg !== \"ed25519\") {\n last = failed(`the algorithm ${serializeBare(alg)} is not ed25519`, facts);\n continue;\n }\n const key = keyId === null ? undefined : keys.get(keyId);\n if (key === undefined) {\n last = failed(\"no key of the directory has the thumbprint of keyid\", facts);\n continue;\n }\n const lines: string[] = [];\n let error: string | undefined;\n for (const item of covered) {\n const value = componentValue(item, request, target);\n if (\"error\" in value) {\n error = value.error;\n break;\n }\n lines.push(`${serializeItem(item)}: ${value.value}`);\n }\n if (error !== undefined) {\n last = failed(error, facts);\n continue;\n }\n lines.push(`\"@signature-params\": ${serializeMember(input)}`);\n const signature = signatures.get(label);\n if (\n signature === undefined ||\n isInnerList(signature) ||\n !(signature.value instanceof Uint8Array)\n ) {\n last = failed(`the Signature header has no byte sequence for ${label}`, facts);\n continue;\n }\n const good = verifyBytes(null, Buffer.from(lines.join(\"\\n\"), \"utf8\"), key, signature.value);\n if (good) return { verified: true, label, keyId, agent, reason: null };\n last = failed(\"the signature does not match the signature base\", facts);\n }\n return last;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,qBAAqB;;AAGlC,MAAa,qBAAqB;;AAGlC,MAAa,mBAAmB;;AAoGhC,IAAM,QAAN,MAAY;CACW;CAArB,YAAY,OAAwB;EAAf,KAAA,QAAA;CAAgB;AACvC;AAiBA,MAAM,eAAe,WAAwC,WAAW;;AAGxE,IAAM,aAAN,cAAyB,MAAM,CAAC;AAEhC,MAAM,YAAY;AAClB,MAAM,WAAW;AACjB,MAAM,cAAc;AACpB,MAAM,aAAa;AACnB,MAAM,SAAS;;AAGf,IAAM,cAAN,MAAkB;CAEa;CAD7B,KAAa;CACb,YAAY,MAA+B;EAAd,KAAA,OAAA;CAAe;CAE5C,OAAuB;EACrB,OAAO,KAAK,KAAK,KAAK,OAAO;CAC/B;CAEA,SAAuB;EACrB,OAAO,KAAK,KAAK,MAAM,KAAK,KAAK,MAAM;CACzC;CAEA,MAAoB;EAClB,OAAO,KAAK,KAAK,MAAM,OAAO,KAAK,KAAK,MAAM,KAAM,KAAK,MAAM;CACjE;CAEA,aAAkC;EAChC,MAAM,sBAAM,IAAI,IAAoB;EACpC,KAAK,OAAO;EACZ,OAAO,KAAK,KAAK,KAAK,KAA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AA,KAAa,QAAQ,WAAW;GAC1C,OAAO,OAAO,iBAAiB,cAAc,GAAG,EAAE,kBAAkB,KAAK;GACzE;EACF;EACA,MAAM,MAAM,UAAU,OAAO,KAAA,IAAY,KAAK,IAAI,KAAK;EACvD,IAAI,QAAQ,KAAA,GAAW;GACrB,OAAO,OAAO,uDAAuD,KAAK;GAC1E;EACF;EACA,MAAM,QAAkB,CAAC;EACzB,IAAI;EACJ,KAAK,MAAM,QAAQ,SAAS;GAC1B,MAAM,QAAQ,eAAe,MAAM,SAAS,MAAM;GAClD,IAAI,WAAW,OAAO;IACpB,QAAQ,MAAM;IACd;GACF;GACA,MAAM,KAAK,GAAG,cAAc,IAAI,EAAE,IAAI,MAAM,OAAO;EACrD;EACA,IAAI,UAAU,KAAA,GAAW;GACvB,OAAO,OAAO,OAAO,KAAK;GAC1B;EACF;EACA,MAAM,KAAK,wBAAwB,gBAAgB,KAAK,GAAG;EAC3D,MAAM,YAAY,WAAW,IAAI,KAAK;EACtC,IACE,cAAc,KAAA,KACd,YAAY,SAAS,KACrB,EAAE,UAAU,iBAAiB,aAC7B;GACA,OAAO,OAAO,iDAAiD,SAAS,KAAK;GAC7E;EACF;EAEA,IADaC,OAAY,MAAM,OAAO,KAAK,MAAM,KAAK,IAAI,GAAG,MAAM,GAAG,KAAK,UAAU,KAC9E,GAAG,OAAO;GAAE,UAAU;GAAM;GAAO;GAAO;GAAO,QAAQ;EAAK;EACrE,OAAO,OAAO,mDAAmD,KAAK;CACxE;CACA,OAAO;AACT"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "polite-crawler",
4
- "version": "0.5.0",
4
+ "version": "0.5.1",
5
5
  "description": "A polite web crawler for research and AI agents. It fetches a source once, keeps it, and reads it many times: robots.txt obeyed, one request per site, full-text search. The MCP server is the package polite-crawler-mcp.",
6
6
  "keywords": [
7
7
  "crawler",
@@ -72,6 +72,10 @@
72
72
  "types": "./build/signals.d.mts",
73
73
  "default": "./build/signals.mjs"
74
74
  },
75
+ "./urls": {
76
+ "types": "./build/urls.d.mts",
77
+ "default": "./build/urls.mjs"
78
+ },
75
79
  "./record.schema.json": "./record.schema.json",
76
80
  "./package.json": "./package.json"
77
81
  },
@@ -1 +0,0 @@
1
- {"version":3,"file":"urls-BHFeSyEK.mjs","names":[],"sources":["../src/urls.ts"],"sourcesContent":["/**\n * This module gives the canonical form of a URL. The document id of a page and the cache key of the\n * crawler use it. Thus two spellings of one page are one document and one cached answer.\n */\n\nconst TRACKING =\n /^(utm_[a-z_]+|fbclid|gclid|gclsrc|dclid|gbraid|wbraid|msclkid|yclid|ttclid|twclid|li_fat_id|srsltid|mc_[a-z]+|_ga|_gl|_hsenc|_hsmi|__hstc|__hssc|__hsfp|mkt_tok|ref_src|igshid)$/i;\n\n/** This function decodes the escapes of unreserved characters (`%7E` is `~`), and writes the other escapes in capitals. */\nconst normalizeEscapes = (value: string): string =>\n value.replace(/%[0-9a-f]{2}/gi, (escape) => {\n const char = String.fromCharCode(Number.parseInt(escape.slice(1), 16));\n return /^[A-Za-z0-9\\-._~]$/.test(char) ? char : escape.toUpperCase();\n });\n\n/**\n * This function gives one URL for each page: a lowercase host, and no fragment, tracking\n * parameters, empty query or default port. It decodes the escapes of unreserved characters.\n */\nexport const canonicalUrl = (value: string): string => {\n const url = new URL(value);\n url.hash = \"\";\n url.hostname = url.hostname.toLowerCase();\n if (\n (url.protocol === \"https:\" && url.port === \"443\") ||\n (url.protocol === \"http:\" && url.port === \"80\")\n ) {\n url.port = \"\";\n }\n // a copy of the keys, because the loop deletes from the live list\n for (const key of Array.from(url.searchParams.keys())) {\n if (TRACKING.test(key)) url.searchParams.delete(key);\n }\n if (url.pathname.includes(\"%\")) url.pathname = normalizeEscapes(url.pathname);\n // \"/p?\" is \"/p\"\n url.search = url.search.includes(\"%\") ? normalizeEscapes(url.search) : url.search;\n return url.href;\n};\n\n/**\n * This function gives the cache key of a URL: its canonical form. A text that is not a URL stays as\n * it is. The crawler and `reindex` use the same key, so a rebuilt index answers the same requests.\n */\nexport const cacheKeyOf = (value: string): string => {\n try {\n return canonicalUrl(value);\n } catch {\n return value;\n }\n};\n\n/**\n * This function gives the site of a host name: the name in lowercase, with no final dot and no\n * `www.` at the start. Thus `www.example.com` and `example.com` are one site.\n */\nexport const siteOf = (host: string): string =>\n host\n .toLowerCase()\n .replace(/\\.$/, \"\")\n .replace(/^www\\./, \"\");\n\n/** These options set the hosts that a crawl or a discovery keeps. */\nexport interface ScopeOptions {\n /** With the default value true, the URLs on the sites of the start URLs are in scope. */\n readonly sameSite?: boolean | undefined;\n /** The URLs on these hosts are in scope too. A name that starts with `*.` names the hosts under it. */\n readonly allowHosts?: readonly string[] | undefined;\n}\n\n/**\n * This function gives the test of the scope of a crawl or a discovery. With `sameSite: false`\n * and no `allowHosts`, each http(s) URL is in scope.\n */\nexport const scopeTest = (\n starts: readonly URL[],\n options: ScopeOptions,\n): ((url: URL) => boolean) => {\n const sameSite = options.sameSite !== false;\n const sites = new Set(starts.map((start) => siteOf(start.hostname)));\n const hosts = (options.allowHosts ?? []).map((host) =>\n host.trim().toLowerCase().replace(/\\.$/, \"\"),\n );\n const any = !sameSite && options.allowHosts === undefined;\n return (url) => {\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return false;\n if (any) return true;\n const name = url.hostname.toLowerCase().replace(/\\.$/, \"\");\n if (sameSite && sites.has(siteOf(name))) return true;\n return hosts.some((host) =>\n host.startsWith(\"*.\") ? name.endsWith(host.slice(1)) : name === host,\n );\n };\n};\n"],"mappings":";;;;;AAKA,MAAM,WACJ;;AAGF,MAAM,oBAAoB,UACxB,MAAM,QAAQ,mBAAmB,WAAW;CAC1C,MAAM,OAAO,OAAO,aAAa,OAAO,SAAS,OAAO,MAAM,CAAC,GAAG,EAAE,CAAC;CACrE,OAAO,qBAAqB,KAAK,IAAI,IAAI,OAAO,OAAO,YAAY;AACrE,CAAC;;;;;AAMH,MAAa,gB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