polite-crawler 0.7.9 → 0.7.11

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 (33) hide show
  1. package/README.md +35 -1
  2. package/build/api.d.mts +55 -1
  3. package/build/api.mjs +160 -1
  4. package/build/api.mjs.map +1 -1
  5. package/build/{cli-daemon-CAgWpFlR.mjs → cli-daemon-CX276Rtz.mjs} +2 -2
  6. package/build/{cli-daemon-CAgWpFlR.mjs.map → cli-daemon-CX276Rtz.mjs.map} +1 -1
  7. package/build/{cli-recipes-C_EdrADI.mjs → cli-recipes-DBZzjwDF.mjs} +2 -2
  8. package/build/{cli-recipes-C_EdrADI.mjs.map → cli-recipes-DBZzjwDF.mjs.map} +1 -1
  9. package/build/cli.mjs +7 -7
  10. package/build/{daemon-CV0QsAVj.mjs → daemon-Ds_tQTbe.mjs} +3 -3
  11. package/build/{daemon-CV0QsAVj.mjs.map → daemon-Ds_tQTbe.mjs.map} +1 -1
  12. package/build/{diff-CNfNHuXy.mjs → diff-CedQOqWF.mjs} +2 -2
  13. package/build/{diff-CNfNHuXy.mjs.map → diff-CedQOqWF.mjs.map} +1 -1
  14. package/build/{extract-B8hHBo8E.mjs → extract-BaYDYK4l.mjs} +2 -2
  15. package/build/{extract-B8hHBo8E.mjs.map → extract-BaYDYK4l.mjs.map} +1 -1
  16. package/build/index.d.mts +39 -2
  17. package/build/index.mjs +11 -11
  18. package/build/{open-BcalDbaa.mjs → open-B-VbHm5U.mjs} +10 -6
  19. package/build/{open-BcalDbaa.mjs.map → open-B-VbHm5U.mjs.map} +1 -1
  20. package/build/{recipe-BZB54swk.mjs → recipe-BbavaUG2.mjs} +3 -3
  21. package/build/{recipe-BZB54swk.mjs.map → recipe-BbavaUG2.mjs.map} +1 -1
  22. package/build/{recipe-product-BAccdfw7.mjs → recipe-product-CpQl83YU.mjs} +4 -4
  23. package/build/{recipe-product-BAccdfw7.mjs.map → recipe-product-CpQl83YU.mjs.map} +1 -1
  24. package/build/{runtime-CDJUCDB6.mjs → runtime-tMl2now7.mjs} +43 -3
  25. package/build/runtime-tMl2now7.mjs.map +1 -0
  26. package/build/{version-DXlmwMT5.mjs → version-B1sAEHHw.mjs} +2 -2
  27. package/build/{version-DXlmwMT5.mjs.map → version-B1sAEHHw.mjs.map} +1 -1
  28. package/build/{wacz-T_8QbgMZ.mjs → wacz-ZXgVsmzT.mjs} +3 -3
  29. package/build/{wacz-T_8QbgMZ.mjs.map → wacz-ZXgVsmzT.mjs.map} +1 -1
  30. package/build/{warc-Brpd-pQg.mjs → warc-6l_5qZF-.mjs} +2 -2
  31. package/build/{warc-Brpd-pQg.mjs.map → warc-6l_5qZF-.mjs.map} +1 -1
  32. package/package.json +1 -1
  33. package/build/runtime-CDJUCDB6.mjs.map +0 -1
package/README.md CHANGED
@@ -1333,7 +1333,27 @@ const nextRun = JSON.stringify(store.used());
1333
1333
  - **A store keeps text only.** It keeps an answer 200, 203 or 204 with an `ETag` or a `Last-Modified` date. The answer needs a text, JSON or XML type in UTF-8, and a body of at most `KEPT_BODY_MAX` UTF-16 code units. Each other answer goes to the client as it is. A binary body is not read, so an exchange with `read: "bytes"` gets its bytes.
1334
1334
  - **Your request stays yours.** A request with its own `If-None-Match`, `If-Modified-Since`, other `If-` header or `Range` goes to the server as it is. So does each request that is not a GET with no body.
1335
1335
  - **The store stays small.** `used()` gives only the entries that the run read or wrote. Save these, and an answer that no run asks for again goes away. `readKept` drops each entry with a bad shape, so a damaged file gives fewer kept answers and no error.
1336
- - **A file of answers holds data.** A file of the cache of a public repository can be read by others. Encrypt the file when the answers hold private data.
1336
+ - **A file of answers holds data.** A file of the cache of a public repository can be read by others. Seal the file when the answers hold private data, as the next section tells.
1337
+
1338
+ #### Seal a store
1339
+
1340
+ `sealKept` encrypts the entries of a store, and `openKept` gives them back. Use them for a place that others can read, for example the cache of a public repository in GitHub Actions.
1341
+
1342
+ ```ts
1343
+ import { keptStore, openKept, sealKept } from "polite-crawler/api";
1344
+
1345
+ // The secret is a random key of 16 bytes or more, for example a secret of the repository
1346
+ const opened = await openKept(sealedBytes, process.env.KEPT_KEY!, { label: "example-app" });
1347
+ const store = keptStore(opened.entries);
1348
+ // ... the run sends its requests ...
1349
+ const nextSeal = await sealKept(store.used(), process.env.KEPT_KEY!, { label: "example-app" });
1350
+ ```
1351
+
1352
+ - **The cipher.** AES-256-GCM. The key comes from the secret by HKDF-SHA-256, with a new random salt for each seal and the label as the info. Two labels give two keys from one secret. The format name `KEPT_SEAL_FORMAT` is the first line of the bytes and the associated data of the cipher.
1353
+ - **The secret must be a key.** HKDF does not slow a guess, so give a random key, not a password. A secret of fewer than `KEPT_SEAL_SECRET_MIN` bytes (16) throws a `RangeError`.
1354
+ - **A bad seal gives an empty store.** Another format, another secret, another label or damaged bytes give no entries and a `note`, and no error. The client then goes on with an empty store, and the server sends full answers.
1355
+ - **One compression for each entry.** Each entry is compressed alone before the encryption. So the size of the seal does not tell how the text of one answer matches the text of another answer.
1356
+ - **Web APIs only.** The functions use `crypto.subtle` and `CompressionStream`, so they run in Node.js and in a browser.
1337
1357
 
1338
1358
  ### Quotas of a key
1339
1359
 
@@ -1439,6 +1459,20 @@ A server examines `If-None-Match` first, and it ignores `If-Modified-Since` when
1439
1459
  3. When the date alone also fails 3 times in sequence, the crawler sends the two validators again, because they cost nothing. The memo records that neither validator works.
1440
1460
  4. A changed body tells nothing about a validator. The robots.txt of a host is not part of its memo, because it is often a static file with validators of its own.
1441
1461
 
1462
+ ### The body of a capture, and an unchanged page
1463
+
1464
+ The result of `fetch` tells if the page changed. `unchanged` is true for a 304 and for an answer of the stored copy (`from_cache`). It is also true when the new body is the same as the previous body of the document. `blob` is the SHA-256 hash of the body that the document shows. Thus a caller does not keep its own hash of each page.
1465
+
1466
+ `body(capture)` gives the bytes of the body of a capture, for example the `capture` of a page. It sends no request. It gives `undefined` for an unknown capture, for a capture with no body, and for a page that asked not to be AI input. Over a runtime of your own, `captureBody(runtime, capture)` does the same.
1467
+
1468
+ ```ts
1469
+ const page = await crawler.fetch("https://example.com/list", { maxAge: "0s" });
1470
+ if (!page.unchanged && page.capture !== null) {
1471
+ const bytes = await crawler.body(page.capture);
1472
+ // parse the bytes
1473
+ }
1474
+ ```
1475
+
1442
1476
  The memo is in the host state store. `openCrawler` keeps it in `hosts.sqlite`, so the processes on one store share it, and it stays after a restart. `MemoryHostStateStore` keeps it in memory. A `HostStateStore` of your own gets a memo when it has the optional methods `validators` and `noteValidators`. `nextValidatorMemo` and `VALIDATOR_MEMO` give the rules and the limits.
1443
1477
 
1444
1478
  ## The store
package/build/api.d.mts CHANGED
@@ -209,6 +209,60 @@ export declare const isApiError: (value: unknown) => value is ApiError;
209
209
  * @beta
210
210
  */
211
211
  export declare function freshUntil(header: (name: string) => string | undefined, status: number, fetchedAt: number, lastModified: string | undefined, capMs: number): number | undefined;
212
+ /**
213
+ * The name and the version of the sealed format. It is the first line of the sealed bytes.
214
+ *
215
+ * @beta
216
+ */
217
+ export declare const KEPT_SEAL_FORMAT = "polite-crawler-kept-sealed/1";
218
+ /**
219
+ * The smallest secret that `sealKept` and `openKept` take, in bytes. HKDF does not slow a guess, so
220
+ * the secret must be a random key, not a password.
221
+ *
222
+ * @beta
223
+ */
224
+ export declare const KEPT_SEAL_SECRET_MIN = 16;
225
+ /**
226
+ * The options of `sealKept` and `openKept`.
227
+ *
228
+ * @beta
229
+ */
230
+ interface SealOptions {
231
+ /**
232
+ * This value is the label of the use, for example the name of the client. A store opens only with
233
+ * the label that sealed it. Give a label when the secret has a second use. The default is "".
234
+ */
235
+ readonly label?: string | undefined;
236
+ }
237
+ /**
238
+ * The result of `openKept`.
239
+ *
240
+ * @beta
241
+ */
242
+ interface OpenedKept {
243
+ /** These values are the entries of the store. They are empty when the store does not open. */
244
+ readonly entries: [string, Kept][];
245
+ /** This value tells why the store gave fewer entries or none, when that occurs. */
246
+ readonly note?: string | undefined;
247
+ }
248
+ /**
249
+ * This function seals the entries of a store of kept answers, for example the `used` entries of a
250
+ * run. It compresses each entry alone, and it encrypts all of them with a key from the secret. It
251
+ * throws a `RangeError` when the secret has fewer than `KEPT_SEAL_SECRET_MIN` bytes.
252
+ *
253
+ * @beta
254
+ */
255
+ export declare function sealKept(entries: Iterable<readonly [string, Kept]>, secret: string | Uint8Array, options?: SealOptions): Promise<Uint8Array<ArrayBuffer>>;
256
+ /**
257
+ * This function opens a store that `sealKept` sealed, and gives its entries. Data that does not open
258
+ * (another format, another secret, another label, damaged bytes) gives no entries and a note, and no
259
+ * error, so a client goes on with an empty store. It throws a `RangeError` when the secret has fewer
260
+ * than `KEPT_SEAL_SECRET_MIN` bytes, as `sealKept` does. As `readKept` does, it drops each entry that
261
+ * does not have the shape of a kept answer.
262
+ *
263
+ * @beta
264
+ */
265
+ export declare function openKept(sealed: Uint8Array, secret: string | Uint8Array, options?: SealOptions): Promise<OpenedKept>;
212
266
  /**
213
267
  * These are the facts of one answer that set the reaction of its host. `classify` gives the
214
268
  * outcome and the wait that the server asked for.
@@ -862,4 +916,4 @@ export interface Polled extends Answer {
862
916
  * @beta
863
917
  */
864
918
  export declare function poll<S extends Signal = AbortSignal>(pace: Pace<S>, transport: Transport<S>, conditions: Conditions, input: Send, signal?: S): Promise<Polled>;
865
- export type { Classified, HostCounts, HostReaction, HostResult, HostStateStore, HostStop, KeepOptions, Kept, KeptAnswer, KeptMemory, KeptStore, Outcome, OutcomeFacts, Paced, PolicyOptions, PolitenessPolicy, Quota, QuotaGate, QuotaGateOptions, QuotaHeaders, QuotaReading, QuotaRecord, QuotaState, QuotaStore, QuotaWindow, ReactionContext, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict, WithQuotaOptions };
919
+ export type { Classified, HostCounts, HostReaction, HostResult, HostStateStore, HostStop, KeepOptions, Kept, KeptAnswer, KeptMemory, KeptStore, OpenedKept, Outcome, OutcomeFacts, Paced, PolicyOptions, PolitenessPolicy, Quota, QuotaGate, QuotaGateOptions, QuotaHeaders, QuotaReading, QuotaRecord, QuotaState, QuotaStore, QuotaWindow, ReactionContext, SealOptions, ValidatorAnswer, ValidatorMemo, ValidatorReport, ValidatorVerdict, WithQuotaOptions };
package/build/api.mjs CHANGED
@@ -563,6 +563,165 @@ function readKept(data) {
563
563
  }
564
564
  return out;
565
565
  }
566
+ // src/kept-seal.ts
567
+ /**
568
+ * The sealed form of a store of kept answers. Use it for a place that other people can read, for
569
+ * example the cache of a public repository in GitHub Actions. A kept answer of a private resource
570
+ * holds its body as text. Thus a client that saves its store in such a place seals it first.
571
+ *
572
+ * `sealKept` encrypts the entries with AES-256-GCM. The key comes from a secret by HKDF-SHA-256
573
+ * (RFC 5869). Each seal has a new random salt, and the label of the use is the info. Thus two labels
574
+ * give two keys from one secret. The format name is the first line of the bytes. It is also the
575
+ * associated data of the cipher, so a change of the format cannot go unseen.
576
+ *
577
+ * Each entry is compressed alone (gzip) before the encryption. A compression of all entries together
578
+ * puts the text of one answer in the window of another answer. Then the size of the sealed bytes can
579
+ * tell something of a private answer to a person who controls a public answer. With one compression
580
+ * for each entry, the text of an answer meets only its own text.
581
+ *
582
+ * The functions use only Web APIs (`crypto.subtle`, `CompressionStream`). Thus they operate in
583
+ * Node.js and in a browser.
584
+ */
585
+ /**
586
+ * The name and the version of the sealed format. It is the first line of the sealed bytes.
587
+ *
588
+ * @beta
589
+ */
590
+ const KEPT_SEAL_FORMAT = "polite-crawler-kept-sealed/1";
591
+ /**
592
+ * The smallest secret that `sealKept` and `openKept` take, in bytes. HKDF does not slow a guess, so
593
+ * the secret must be a random key, not a password.
594
+ *
595
+ * @beta
596
+ */
597
+ const KEPT_SEAL_SECRET_MIN = 16;
598
+ const SALT_BYTES = 16;
599
+ const IV_BYTES = 12;
600
+ const TAG_BYTES = 16;
601
+ const encoder = new TextEncoder();
602
+ const decoder = new TextDecoder("utf-8", { fatal: true });
603
+ const HEADER = encoder.encode(`${KEPT_SEAL_FORMAT}\n`);
604
+ /** This function gives the bytes of the secret, or throws when the secret is too short. */
605
+ const secretBytes = (secret) => {
606
+ const bytes = typeof secret === "string" ? encoder.encode(secret) : new Uint8Array(secret);
607
+ if (bytes.length < 16) throw new RangeError(`The secret of a sealed store needs 16 bytes or more, and it has ${bytes.length}. Give a random key.`);
608
+ return bytes;
609
+ };
610
+ /** This function gives the AES-GCM key of a seal from the secret, the salt and the label. */
611
+ const keyOf = async (secret, salt, label, use) => {
612
+ const base = await crypto.subtle.importKey("raw", secret, "HKDF", false, ["deriveKey"]);
613
+ const info = encoder.encode(`${KEPT_SEAL_FORMAT}\n${label}`);
614
+ return crypto.subtle.deriveKey({
615
+ name: "HKDF",
616
+ hash: "SHA-256",
617
+ salt,
618
+ info
619
+ }, base, {
620
+ name: "AES-GCM",
621
+ length: 256
622
+ }, false, [use]);
623
+ };
624
+ /** This function sends the bytes through a compression stream or a decompression stream. */
625
+ const through = async (bytes, stream) => new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer());
626
+ /** This function joins the parts into one array of bytes. */
627
+ const join = (parts) => {
628
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
629
+ let at = 0;
630
+ for (const part of parts) {
631
+ out.set(part, at);
632
+ at += part.length;
633
+ }
634
+ return out;
635
+ };
636
+ /**
637
+ * This function seals the entries of a store of kept answers, for example the `used` entries of a
638
+ * run. It compresses each entry alone, and it encrypts all of them with a key from the secret. It
639
+ * throws a `RangeError` when the secret has fewer than `KEPT_SEAL_SECRET_MIN` bytes.
640
+ *
641
+ * @beta
642
+ */
643
+ async function sealKept(entries, secret, options = {}) {
644
+ const key = secretBytes(secret);
645
+ const parts = [];
646
+ for (const entry of entries) {
647
+ const packed = await through(encoder.encode(JSON.stringify(entry)), new CompressionStream("gzip"));
648
+ const length = /* @__PURE__ */ new Uint8Array(4);
649
+ new DataView(length.buffer).setUint32(0, packed.length);
650
+ parts.push(length, packed);
651
+ }
652
+ const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
653
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
654
+ const cipherKey = await keyOf(key, salt, options.label ?? "", "encrypt");
655
+ const sealed = await crypto.subtle.encrypt({
656
+ name: "AES-GCM",
657
+ iv,
658
+ additionalData: HEADER
659
+ }, cipherKey, join(parts));
660
+ return join([
661
+ HEADER,
662
+ salt,
663
+ iv,
664
+ new Uint8Array(sealed)
665
+ ]);
666
+ }
667
+ /**
668
+ * This function opens a store that `sealKept` sealed, and gives its entries. Data that does not open
669
+ * (another format, another secret, another label, damaged bytes) gives no entries and a note, and no
670
+ * error, so a client goes on with an empty store. It throws a `RangeError` when the secret has fewer
671
+ * than `KEPT_SEAL_SECRET_MIN` bytes, as `sealKept` does. As `readKept` does, it drops each entry that
672
+ * does not have the shape of a kept answer.
673
+ *
674
+ * @beta
675
+ */
676
+ async function openKept(sealed, secret, options = {}) {
677
+ const key = secretBytes(secret);
678
+ const bytes = new Uint8Array(sealed);
679
+ if (bytes.length < HEADER.length || HEADER.some((byte, index) => bytes[index] !== byte)) return {
680
+ entries: [],
681
+ note: `The data is not a sealed store of the format ${KEPT_SEAL_FORMAT}.`
682
+ };
683
+ const start = HEADER.length;
684
+ if (bytes.length < start + SALT_BYTES + IV_BYTES + TAG_BYTES) return {
685
+ entries: [],
686
+ note: "The sealed store is too short, so it is damaged."
687
+ };
688
+ const salt = bytes.slice(start, start + SALT_BYTES);
689
+ const iv = bytes.slice(start + SALT_BYTES, start + SALT_BYTES + IV_BYTES);
690
+ let plain;
691
+ try {
692
+ const cipherKey = await keyOf(key, salt, options.label ?? "", "decrypt");
693
+ const opened = await crypto.subtle.decrypt({
694
+ name: "AES-GCM",
695
+ iv,
696
+ additionalData: HEADER
697
+ }, cipherKey, bytes.slice(start + SALT_BYTES + IV_BYTES));
698
+ plain = new Uint8Array(opened);
699
+ } catch {
700
+ return {
701
+ entries: [],
702
+ note: "The sealed store does not open: another secret, another label, or damaged bytes."
703
+ };
704
+ }
705
+ const read = [];
706
+ const view = new DataView(plain.buffer);
707
+ let at = 0;
708
+ try {
709
+ while (at < plain.length) {
710
+ if (at + 4 > plain.length) throw new Error("a length is cut");
711
+ const length = view.getUint32(at);
712
+ at += 4;
713
+ if (at + length > plain.length) throw new Error("an entry is cut");
714
+ read.push(JSON.parse(decoder.decode(await through(plain.slice(at, at + length), new DecompressionStream("gzip")))));
715
+ at += length;
716
+ }
717
+ } catch {
718
+ return {
719
+ entries: readKept(read),
720
+ note: "An entry of the sealed store does not read, so the store gives only the entries before it."
721
+ };
722
+ }
723
+ return { entries: readKept(read) };
724
+ }
566
725
  // src/api.ts
567
726
  /**
568
727
  * The polite send of a documented API. It keeps the pace of each host with the scheduler of the
@@ -957,6 +1116,6 @@ async function poll(pace, transport, conditions, input, signal) {
957
1116
  changed
958
1117
  };
959
1118
  }
960
- export { API_TIMEOUT_MS, ApiError, KEPT_BODY_MAX, KEPT_HEADERS, KEPT_STATUSES, QuotaError, TOKEN_MARGIN_MS, fetchTransport, freshUntil, hasValidator, isApiError, isQuotaError, isTextType, keepAnswer, keptFetch, keptKey, keptRequestHeaders, keptStore, memoryQuotaStore, outcomeResult, poll, quotaGate, reactToOutcome, readGrant, readKept, readQuotaHeaders, send, sendWithToken, statusLine, tokenStore, withQuota };
1119
+ export { API_TIMEOUT_MS, ApiError, KEPT_BODY_MAX, KEPT_HEADERS, KEPT_SEAL_FORMAT, KEPT_SEAL_SECRET_MIN, KEPT_STATUSES, QuotaError, TOKEN_MARGIN_MS, fetchTransport, freshUntil, hasValidator, isApiError, isQuotaError, isTextType, keepAnswer, keptFetch, keptKey, keptRequestHeaders, keptStore, memoryQuotaStore, openKept, outcomeResult, poll, quotaGate, reactToOutcome, readGrant, readKept, readQuotaHeaders, sealKept, send, sendWithToken, statusLine, tokenStore, withQuota };
961
1120
 
962
1121
  //# sourceMappingURL=api.mjs.map