@crabcrop/url 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @crabcrop/url
2
2
 
3
- Build and sign [crabcrop](https://github.com/dayvson/crabcrop) URLs from TypeScript or JavaScript, on Node or in the browser. No dependencies: Node signs and seals with `node:crypto`, and browser bundles get a built-in TypeScript implementation of the same functions (see [Browsers and bundlers](#browsers-and-bundlers)). The signing scheme is specified in [`spec/url-signing.md`](../../spec/url-signing.md). Signing is pinned by the canonical [`spec/test-vectors.json`](../../spec/test-vectors.json), which this package runs as tests, and the explainer's verdicts and the typed builders are pinned by the shared grammar corpora in [`spec/explain-verdicts.json`](../../spec/explain-verdicts.json) and [`spec/operation-vectors.json`](../../spec/operation-vectors.json), which the playground's suite and the server crate's differential tests run as well.
3
+ Build and sign [crabcrop](https://github.com/dayvson/crabcrop) URLs from TypeScript or JavaScript, on Node or in the browser. No dependencies: Node signs and seals with `node:crypto`, and browser bundles get a built-in TypeScript implementation of the same functions (see [Browsers and bundlers](#browsers-and-bundlers)). The signing scheme is specified in [`spec/url-signing.md`](../../spec/url-signing.md). Signing is pinned by the canonical [`spec/test-vectors.json`](../../spec/test-vectors.json), which this package runs as tests, and the explainer's verdicts and the typed builders are pinned by the shared grammar corpora in [`spec/explain-verdicts.json`](../../spec/explain-verdicts.json) and [`spec/operation-vectors.json`](../../spec/operation-vectors.json), which the playground's suite, the Python SDK's suite and the server crate's differential tests run as well.
4
4
 
5
5
  ## Usage
6
6
 
@@ -46,9 +46,14 @@ const ok = verifyUrlSignature("your-secret", url);
46
46
 
47
47
  // Purge signatures for the server's /purge and /purge-group endpoints
48
48
  // are domain-separated under a derived subkey; the helpers sign the
49
- // right strings so callers never assemble them by hand.
49
+ // right strings so callers never assemble them by hand. Pass an
50
+ // expiry (unix seconds) for a purge URL that stops working then;
51
+ // its path is /purge/<signature>/exp:<expiry>/<path> (or
52
+ // /purge-group/<signature>/exp:<expiry>/<group>).
50
53
  const purge = purgeSignature("your-secret", "300x200/https://example.com/photo.jpg");
51
54
  const group = purgeGroupSignature("your-secret", "thumb");
55
+ const expiringPurge = purgeSignature("your-secret", "300x200/https://example.com/photo.jpg", 1893456000);
56
+ const expiringGroup = purgeGroupSignature("your-secret", "thumb", 1893456000);
52
57
 
53
58
  // Upload signatures for the server's PUT /upload/<signature>/<name>
54
59
  // endpoint live in a third domain, under their own derived subkey.
@@ -73,7 +78,7 @@ const remainder = unseal("your-secret", seal("your-secret", "300x200/https://exa
73
78
 
74
79
  Pass `null` as the secret to produce the literal `unsafe` signature segment, for servers running with `CRABCROP_ALLOW_UNSAFE` or in presets-only mode.
75
80
 
76
- `explainUrl(url)` parses a URL back into its signature, its explained segments and its source, and lists every error. It reads at most 64 KiB (65,536 bytes of UTF-8), which bounds the time one call takes. A longer input gets a single error and no signature, so `verifyUrlSignature` returns null for it.
81
+ `explainUrl(url)` parses a URL back into its signature, its explained segments and its source, and lists every error. Its verdict is the server's: it reads each number as the server's types read it (a decimal as the 32-bit float the server reads, or the 64-bit one for a `convolution` value or a `frame:` selector, its range applied to the rounded value), and it reports what the server refuses before and after the parse: a remainder that begins with `crabcrop`, `purge`, `purge-group` or `upload`, more than 100 operations, and more than 16 distinct watermark and overlay URLs. It cannot see preset definitions or the server's default operations, so it counts each `preset:` reference as one operation. It reads at most 64 KiB (65,536 bytes of UTF-8), which bounds the time one call takes. A longer input gets a single error and no signature, so `verifyUrlSignature` returns null for it.
77
82
 
78
83
  The builders throw on operations or a source that can never verify: `?`, `#`, whitespace, control and non-ASCII characters, and `"` `<` `>` `\` `^` `` ` `` `{` `|` `}`, which a browser rewrites before an `<img src>` or `fetch()` request leaves the page (`\` becomes `/`, the rest are percent-encoded). Percent-encode those in the source first (`x{y}.jpg` as `x%7By%7D.jpg`); the error names the encoding. The full rules are in [`spec/url-signing.md`](../../spec/url-signing.md#building-urls).
79
84
 
package/dist/explain.d.ts CHANGED
@@ -90,7 +90,12 @@ export declare function trimLikeServer(text: string): string;
90
90
  * A detection class name as the server's parse_class_name
91
91
  * takes it, already trimmed: 1 to 64 UTF-8 bytes (bytes, not
92
92
  * UTF-16 code units, as on the server) of letters, digits,
93
- * space, `_`, `.`, `-`, `/`.
93
+ * space, `_`, `.`, `-`, `/`. A letter or digit is what Rust's
94
+ * `char::is_alphanumeric` calls one: the Unicode Alphabetic
95
+ * property, or a number category. Alphabetic holds more than
96
+ * the letter categories: the vowel signs of Indic scripts
97
+ * (`हिंदी`), combining marks such as U+0345, and circled
98
+ * letters such as `Ⓐ` (issue #712).
94
99
  */
95
100
  export declare function isClassName(name: string): boolean;
96
101
  /**
@@ -101,6 +106,31 @@ export declare function isClassName(name: string): boolean;
101
106
  * (issue #482).
102
107
  */
103
108
  export declare function classFoldKey(name: string): string;
109
+ /**
110
+ * The float a decimal argument reads as on the server (issue
111
+ * #712): Rust's `f32` or `f64` `FromStr`, which takes an
112
+ * optional sign, digits with an optional fraction (`2`, `2.`,
113
+ * `.5`), and an optional exponent (`e` or `E`, an optional
114
+ * sign, digits), and rounds the decimal to the nearest float of
115
+ * `bits` bits, a tie to the even one. Past the float's range the
116
+ * value is an infinity, and below half its smallest step it is
117
+ * zero, signed as the decimal is. Returns null for any other
118
+ * text, Rust's `inf` and `NaN` spellings included: no range the
119
+ * grammar checks admits them.
120
+ *
121
+ * The rounding is exact, in BigInt arithmetic. Rounding to a
122
+ * double first and then to 32 bits (`Math.fround(Number(s))`)
123
+ * rounds twice, and gets a decimal near the midpoint between
124
+ * two 32-bit floats wrong.
125
+ */
126
+ export declare function readDecimal(text: string, bits: 32 | 64): number | null;
127
+ /** The most operations one request runs (url.rs MAX_OPERATIONS). */
128
+ export declare const MAX_OPERATIONS = 100;
129
+ /**
130
+ * The most distinct watermark and overlay URLs one request
131
+ * names (url.rs MAX_WATERMARK_URLS, issue #613).
132
+ */
133
+ export declare const MAX_WATERMARK_URLS = 16;
104
134
  /**
105
135
  * Parse a crabcrop URL (or bare path) back into its pieces,
106
136
  * explaining each segment. Mirrors the server's dispatch:
package/dist/explain.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * surface is pinned to the same verdict corpora (audit PL-10,
10
10
  * P-3).
11
11
  */
12
- import { MAX_DIMENSION } from "./limits.js";
12
+ import { isReservedRemainder, MAX_DIMENSION } from "./limits.js";
13
13
  export const FILTER_DESCRIPTIONS = {
14
14
  grayscale: "convert to grayscale",
15
15
  invert: "invert the colors",
@@ -228,12 +228,17 @@ export function trimLikeServer(text) {
228
228
  * A detection class name as the server's parse_class_name
229
229
  * takes it, already trimmed: 1 to 64 UTF-8 bytes (bytes, not
230
230
  * UTF-16 code units, as on the server) of letters, digits,
231
- * space, `_`, `.`, `-`, `/`.
231
+ * space, `_`, `.`, `-`, `/`. A letter or digit is what Rust's
232
+ * `char::is_alphanumeric` calls one: the Unicode Alphabetic
233
+ * property, or a number category. Alphabetic holds more than
234
+ * the letter categories: the vowel signs of Indic scripts
235
+ * (`हिंदी`), combining marks such as U+0345, and circled
236
+ * letters such as `Ⓐ` (issue #712).
232
237
  */
233
238
  export function isClassName(name) {
234
239
  return (name.length >= 1 &&
235
240
  new TextEncoder().encode(name).length <= 64 &&
236
- /^[\p{L}\p{N} _.\-/]+$/u.test(name));
241
+ /^[\p{Alphabetic}\p{N} _.\-/]+$/u.test(name));
237
242
  }
238
243
  /**
239
244
  * The key a class name folds to when the objects crop drops
@@ -259,35 +264,164 @@ const NO_ARG_FILTERS = new Set([
259
264
  ]);
260
265
  const FORMAT_NAMES = new Set(IMAGE_FORMATS);
261
266
  const ANCHOR_NAMES = new Set(TEXT_ANCHORS);
267
+ // Numbers (issue #712). The server reads every numeric
268
+ // argument with its Rust type's `FromStr`, and the explainer
269
+ // reads each one the same way, so the two give one verdict on
270
+ // every spelling. spec/url-signing.md (Argument spellings)
271
+ // states the rules for every implementation.
272
+ /**
273
+ * Whether `s` is an integer in `min..=max` as Rust's unsigned
274
+ * `FromStr` reads one: an optional `+`, then ASCII digits,
275
+ * leading zeros allowed. A `-` is refused, even in `-0`.
276
+ */
277
+ function isUintIn(s, min, max) {
278
+ return s !== null && /^\+?\d+$/.test(s) && integerIn(s, min, max);
279
+ }
280
+ /**
281
+ * Whether `s` is an integer in `min..=max` as Rust's signed
282
+ * `FromStr` reads one: an optional `+` or `-`, then ASCII
283
+ * digits. `-0` is 0.
284
+ */
262
285
  function isIntIn(s, min, max) {
263
- // Rust's integer from_str syntax: an optional sign (the
264
- // unsigned parsers accept '+' too), then digits.
265
- return /^[+-]?\d+$/.test(s) && BigInt(s) >= BigInt(min) && BigInt(s) <= BigInt(max);
286
+ return s !== null && /^[+-]?\d+$/.test(s) && integerIn(s, min, max);
266
287
  }
267
- // The fraction digits can only follow a literal dot, so a run
268
- // of digits has one way to match and a long run costs linear
269
- // time. The older `\d+\.?\d*` could split one run at any point
270
- // and took quadratic time when the match failed (issue #594).
271
- // Both accept the same strings.
272
- const RUST_FLOAT = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
273
- function isFloat(s) {
274
- // Rust's f32::from_str syntax (AP-23): plain decimal with
275
- // an optional exponent; no hex, no surrounding whitespace,
276
- // both of which Number() would otherwise accept. The
277
- // inf/nan spellings Rust also parses are non-finite, and
278
- // every caller rejects non-finite values, so the verdicts
279
- // agree without them.
280
- return RUST_FLOAT.test(s) && Number.isFinite(Number(s));
288
+ function integerIn(s, min, max) {
289
+ // Past 20 significant digits a value is outside every
290
+ // integer type the grammar reads, and BigInt need not read
291
+ // a digit run as long as the URL.
292
+ if (s.replace(/^[+-]?0*/, "").length > 20)
293
+ return false;
294
+ const value = BigInt(s);
295
+ return value >= BigInt(min) && value <= BigInt(max);
281
296
  }
282
- const KERNEL_VALUE = /^-?\d+(\.\d+)?$/;
297
+ /**
298
+ * Rust's float syntax: an optional sign, digits with an
299
+ * optional fraction (`2`, `2.`, `.5`), and an optional
300
+ * exponent. Each part matches one way, so a long run of
301
+ * digits costs linear time, matched or not (issue #594).
302
+ */
303
+ const DECIMAL = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?)(\d+))?$/;
304
+ /**
305
+ * The most significant digits {@link readDecimal} keeps. Every
306
+ * midpoint between two 64-bit floats has at most 767
307
+ * significant digits, so a decimal cut to this many, with one
308
+ * nonzero digit appended when any cut digit is nonzero, rounds
309
+ * to the float the whole decimal rounds to.
310
+ */
311
+ const KEPT_DIGITS = 1000;
312
+ /** The precision and range of the two binary float formats. */
313
+ const BINARY = {
314
+ 32: { mantissa: 24, minExponent: -126, maxExponent: 127, overflow: 39, underflow: -46 },
315
+ 64: { mantissa: 53, minExponent: -1022, maxExponent: 1023, overflow: 309, underflow: -325 },
316
+ };
317
+ /** The largest finite 32-bit float, Rust's `f32::MAX`. */
318
+ const F32_MAX = (2 - 2 ** -23) * 2 ** 127;
319
+ /**
320
+ * The float a decimal argument reads as on the server (issue
321
+ * #712): Rust's `f32` or `f64` `FromStr`, which takes an
322
+ * optional sign, digits with an optional fraction (`2`, `2.`,
323
+ * `.5`), and an optional exponent (`e` or `E`, an optional
324
+ * sign, digits), and rounds the decimal to the nearest float of
325
+ * `bits` bits, a tie to the even one. Past the float's range the
326
+ * value is an infinity, and below half its smallest step it is
327
+ * zero, signed as the decimal is. Returns null for any other
328
+ * text, Rust's `inf` and `NaN` spellings included: no range the
329
+ * grammar checks admits them.
330
+ *
331
+ * The rounding is exact, in BigInt arithmetic. Rounding to a
332
+ * double first and then to 32 bits (`Math.fround(Number(s))`)
333
+ * rounds twice, and gets a decimal near the midpoint between
334
+ * two 32-bit floats wrong.
335
+ */
336
+ export function readDecimal(text, bits) {
337
+ const match = DECIMAL.exec(text);
338
+ if (match === null)
339
+ return null;
340
+ const [, sign, whole, fraction = "", expSign = "", expDigits = "0"] = match;
341
+ if (whole === "" && fraction === "")
342
+ return null;
343
+ const negative = sign === "-";
344
+ const zero = negative ? -0 : 0;
345
+ const infinity = negative ? -Infinity : Infinity;
346
+ const format = BINARY[bits];
347
+ // value = digits * 10^e10. The exponent stays a safe integer:
348
+ // past nine digits it only has to stay past both pre-screens.
349
+ let digits = (whole + fraction).replace(/^0+/, "");
350
+ const expTrimmed = expDigits.replace(/^0+/, "");
351
+ const magnitude = expTrimmed.length > 9 ? 1e9 : Number(expTrimmed || "0");
352
+ let e10 = (expSign === "-" ? -magnitude : magnitude) - fraction.length;
353
+ let end = digits.length;
354
+ while (end > 0 && digits.charCodeAt(end - 1) === 48)
355
+ end--;
356
+ e10 += digits.length - end;
357
+ digits = digits.slice(0, end);
358
+ if (digits === "")
359
+ return zero;
360
+ const n = digits.length;
361
+ if (n - 1 + e10 >= format.overflow)
362
+ return infinity;
363
+ if (n + e10 <= format.underflow)
364
+ return zero;
365
+ if (n > KEPT_DIGITS) {
366
+ const sticky = /[1-9]/.test(digits.slice(KEPT_DIGITS));
367
+ e10 += n - KEPT_DIGITS - (sticky ? 1 : 0);
368
+ digits = digits.slice(0, KEPT_DIGITS) + (sticky ? "1" : "");
369
+ }
370
+ const d = BigInt(digits);
371
+ const num = e10 >= 0 ? d * 10n ** BigInt(e10) : d;
372
+ const den = e10 >= 0 ? 1n : 10n ** BigInt(-e10);
373
+ // e = floor(log2(num / den)), from the bit lengths.
374
+ let e = num.toString(2).length - den.toString(2).length;
375
+ if (e >= 0 ? num < den << BigInt(e) : num << BigInt(-e) < den)
376
+ e -= 1;
377
+ let q = Math.max(e, format.minExponent) - (format.mantissa - 1);
378
+ const top = q >= 0 ? num : num << BigInt(-q);
379
+ const bottom = q >= 0 ? den << BigInt(q) : den;
380
+ let mantissa = top / bottom;
381
+ const twice = 2n * (top - mantissa * bottom);
382
+ if (twice > bottom || (twice === bottom && (mantissa & 1n) === 1n))
383
+ mantissa += 1n;
384
+ if (mantissa === 1n << BigInt(format.mantissa)) {
385
+ mantissa >>= 1n;
386
+ q += 1;
387
+ }
388
+ if (q > format.maxExponent - (format.mantissa - 1))
389
+ return infinity;
390
+ const value = Number(mantissa) * 2 ** q;
391
+ return negative ? -value : value;
392
+ }
393
+ /**
394
+ * Whether `s` is a decimal whose 32-bit float is in
395
+ * `min..=max`, or above `min` with `above`: the bounds apply to
396
+ * the rounded value, as the server applies them, so
397
+ * `blur(512.00001)` is `blur(512)`.
398
+ */
399
+ function f32In(s, min, max, above = false) {
400
+ if (s === null)
401
+ return false;
402
+ const value = readDecimal(s, 32);
403
+ return value !== null && (above ? value > min : value >= min) && value <= max;
404
+ }
405
+ /**
406
+ * The strict decimal of the `rotate` angle, the `convolution`
407
+ * kernel and the `frame:` selector (url.rs parse_angle): an
408
+ * optional minus where the value may be negative, digits, an
409
+ * optional fraction; no `+`, no exponent, no leading or
410
+ * trailing dot.
411
+ */
412
+ const STRICT_DECIMAL = /^-?\d+(\.\d+)?$/;
283
413
  function isKernelValue(s) {
284
- // The server's kernel-value grammar (url.rs
285
- // parse_kernel_value): the rotate angle's strict decimal
286
- // form, no exponent and no leading dot, bounded to 1024
287
- // in absolute value.
288
- return KERNEL_VALUE.test(s) && Math.abs(Number(s)) <= 1024;
414
+ // url.rs parse_kernel_value: a strict decimal, read as an
415
+ // f64, at most 1024 in absolute value.
416
+ if (!STRICT_DECIMAL.test(s))
417
+ return false;
418
+ const value = readDecimal(s, 64);
419
+ return value !== null && Math.abs(value) <= 1024;
289
420
  }
290
421
  function percentDecodable(s) {
422
+ // The server's escapes (url.rs decode_arg): `%` and two hex
423
+ // digits, decoding to UTF-8. `decodeURIComponent` refuses
424
+ // the rest, `%+1` included, as the server does (issue #712).
291
425
  try {
292
426
  return decodeURIComponent(s);
293
427
  }
@@ -313,58 +447,45 @@ function validateFilter(name, args) {
313
447
  return null;
314
448
  const parts = args.split(",");
315
449
  if (parts.length === 1)
316
- return isIntIn(parts[0], 0, 255) ? null : bad;
450
+ return isUintIn(parts[0], 0, 255) ? null : bad;
317
451
  return parts.length === 5 &&
318
- isIntIn(parts[0], 0, 255) &&
319
- parts.slice(1).every((p) => isIntIn(p, 0, 4294967295))
452
+ isUintIn(parts[0], 0, 255) &&
453
+ parts.slice(1).every((p) => isUintIn(p, 0, 4294967295))
320
454
  ? null
321
455
  : bad;
322
456
  }
323
457
  case "blur":
324
- // The server's blur bound (url.rs MAX_BLUR_SIGMA):
325
- // positive and at most 512.
326
- return args !== null && isFloat(args) && Number(args) > 0 && Number(args) <= 512
327
- ? null
328
- : bad;
458
+ // The server's blur bound (url.rs MAX_BLUR_SIGMA): a
459
+ // normal f32, so at least 2^-126 (a subnormal sigma
460
+ // panics the image crate's Gaussian setup), and at most
461
+ // 512.
462
+ return f32In(args, 2 ** -126, 512) ? null : bad;
329
463
  case "sharpen":
330
- return args !== null && isFloat(args) && Number(args) > 0 ? null : bad;
464
+ return f32In(args, 0, F32_MAX, true) ? null : bad;
331
465
  case "brighten":
332
- return args !== null && isIntIn(args, -255, 255) ? null : bad;
466
+ return isIntIn(args, -255, 255) ? null : bad;
333
467
  case "huerotate":
334
- return args !== null && isIntIn(args, -2147483648, 2147483647) ? null : bad;
468
+ return isIntIn(args, -2147483648, 2147483647) ? null : bad;
335
469
  case "contrast":
336
- return args !== null && isFloat(args) && Number(args) >= -100 && Number(args) <= 100
337
- ? null
338
- : bad;
470
+ return f32In(args, -100, 100) ? null : bad;
339
471
  case "gamma":
340
- return args !== null && isFloat(args) && Number(args) > 0 && Number(args) <= 10
341
- ? null
342
- : bad;
472
+ return f32In(args, 0, 10, true) ? null : bad;
343
473
  case "exposure":
344
- return args !== null && isFloat(args) && Number(args) >= -10 && Number(args) <= 10
345
- ? null
346
- : bad;
474
+ return f32In(args, -10, 10) ? null : bad;
347
475
  case "highlights_shadows": {
348
476
  if (args === null)
349
477
  return bad;
350
478
  const parts = args.split(",");
351
- return parts.length === 2 &&
352
- parts.every((p) => isFloat(p) && Number(p) >= -100 && Number(p) <= 100)
353
- ? null
354
- : bad;
479
+ return parts.length === 2 && parts.every((p) => f32In(p, -100, 100)) ? null : bad;
355
480
  }
356
481
  case "vibrance":
357
- return args !== null && isFloat(args) && Number(args) >= -100 && Number(args) <= 100
358
- ? null
359
- : bad;
482
+ return f32In(args, -100, 100) ? null : bad;
360
483
  case "saturation":
361
- return args !== null && isFloat(args) && Number(args) >= 0 && Number(args) <= 255
362
- ? null
363
- : bad;
484
+ return f32In(args, 0, 255) ? null : bad;
364
485
  case "quality": {
365
486
  if (args === null)
366
487
  return bad;
367
- if (args === "auto" || isIntIn(args, 1, 100))
488
+ if (args === "auto" || isUintIn(args, 1, 100))
368
489
  return null;
369
490
  // Per-format list (issue #319): at most one bare
370
491
  // fallback, at most one entry per format, no video
@@ -374,7 +495,7 @@ function validateFilter(name, args) {
374
495
  for (const part of args.split(",")) {
375
496
  const colon = part.indexOf(":");
376
497
  if (colon === -1) {
377
- if (fallbackSeen || !(part === "auto" || isIntIn(part, 1, 100)))
498
+ if (fallbackSeen || !(part === "auto" || isUintIn(part, 1, 100)))
378
499
  return bad;
379
500
  fallbackSeen = true;
380
501
  }
@@ -387,14 +508,14 @@ function validateFilter(name, args) {
387
508
  if (seen.has(canonical))
388
509
  return bad;
389
510
  seen.add(canonical);
390
- if (!(value === "auto" || isIntIn(value, 1, 100)))
511
+ if (!(value === "auto" || isUintIn(value, 1, 100)))
391
512
  return bad;
392
513
  }
393
514
  }
394
515
  return seen.size + (fallbackSeen ? 1 : 0) > 0 ? null : bad;
395
516
  }
396
517
  case "palette":
397
- return args !== null && isIntIn(args, 2, 256) ? null : bad;
518
+ return isUintIn(args, 2, 256) ? null : bad;
398
519
  case "format": {
399
520
  if (args === null)
400
521
  return bad;
@@ -423,9 +544,12 @@ function validateFilter(name, args) {
423
544
  return bad;
424
545
  }
425
546
  if (name === "webp") {
426
- if (/^method:[0-6]$/.test(option))
547
+ // Each value is a u8 on the server (url.rs
548
+ // parse_format_spec), so `method:+6` and `sns:050`
549
+ // are spellings of 6 and 50.
550
+ if (key === "method" && isUintIn(option.slice(7), 0, 6))
427
551
  continue;
428
- if (/^sns:\d+$/.test(option) && isIntIn(option.slice(4), 0, 100))
552
+ if (key === "sns" && isUintIn(option.slice(4), 0, 100))
429
553
  continue;
430
554
  return bad;
431
555
  }
@@ -448,7 +572,7 @@ function validateFilter(name, args) {
448
572
  const coords = parts.slice(1);
449
573
  if (coords.length < 4 || coords.length > 32 || coords.length % 2 !== 0)
450
574
  return bad;
451
- if (!coords.every((p) => isIntIn(p, 0, 255)))
575
+ if (!coords.every((p) => isUintIn(p, 0, 255)))
452
576
  return bad;
453
577
  for (let i = 2; i < coords.length; i += 2) {
454
578
  if (Number(coords[i]) <= Number(coords[i - 2]))
@@ -468,13 +592,12 @@ function validateFilter(name, args) {
468
592
  return parts.slice(0, -1).every((p) => isKernelValue(p)) ? null : bad;
469
593
  }
470
594
  case "noise":
471
- return args !== null && isIntIn(args, 0, 100) ? null : bad;
595
+ return isUintIn(args, 0, 100) ? null : bad;
472
596
  case "facepad":
473
- return args !== null && isFloat(args) && Number(args) >= 0 && Number(args) <= 3
474
- ? null
475
- : bad;
597
+ return f32In(args, 0, 3) ? null : bad;
476
598
  case "upscale":
477
- return args !== null && /^[+-]?\d+$/.test(args) && isOneOf(UPSCALE_FACTORS, Number(args))
599
+ // A u32, then one of the factors.
600
+ return isUintIn(args, 0, 4294967295) && isOneOf(UPSCALE_FACTORS, Number(args))
478
601
  ? null
479
602
  : bad;
480
603
  case "studio": {
@@ -505,7 +628,7 @@ function validateFilter(name, args) {
505
628
  // The pad parses as a Rust u8 (an optional `+`,
506
629
  // then digits; no minus sign, not even `-0`) and
507
630
  // is bounded to 40.
508
- if (!/^\+?\d+$/.test(value) || BigInt(value) > 40n)
631
+ if (!isUintIn(value, 0, 40))
509
632
  return bad;
510
633
  }
511
634
  else if (mode === "product" && key === "bg") {
@@ -522,12 +645,16 @@ function validateFilter(name, args) {
522
645
  }
523
646
  return null;
524
647
  }
525
- case "dpr":
526
- return args !== null && isFloat(args) && isOneOf(DPR_FACTORS, Number(args))
527
- ? null
528
- : bad;
648
+ case "dpr": {
649
+ // An f32, then one of the factors: `dpr(1.50000001)`
650
+ // rounds to 1.5.
651
+ const factor = args === null ? null : readDecimal(args, 32);
652
+ return factor !== null && isOneOf(DPR_FACTORS, factor) ? null : bad;
653
+ }
529
654
  case "rotate":
530
- return args !== null && /^-?\d+(\.\d+)?$/.test(args) && Math.abs(Number(args)) <= 36000
655
+ // url.rs parse_angle: a strict decimal, read as an f32,
656
+ // at most 100 turns either way.
657
+ return args !== null && STRICT_DECIMAL.test(args) && f32In(args, -36000, 36000)
531
658
  ? null
532
659
  : bad;
533
660
  case "fill":
@@ -537,7 +664,7 @@ function validateFilter(name, args) {
537
664
  return bad;
538
665
  const parts = args.split(",");
539
666
  return (parts.length === 1 || parts.length === 4) &&
540
- parts.every((p) => isIntIn(p, 0, MAX_DIMENSION))
667
+ parts.every((p) => isUintIn(p, 0, MAX_DIMENSION))
541
668
  ? null
542
669
  : bad;
543
670
  }
@@ -546,7 +673,7 @@ function validateFilter(name, args) {
546
673
  return bad;
547
674
  const parts = args.split(",");
548
675
  return parts.length === 2 &&
549
- isIntIn(parts[0], 0, MAX_DIMENSION) &&
676
+ isUintIn(parts[0], 0, MAX_DIMENSION) &&
550
677
  /^[0-9a-fA-F]{6}$/.test(parts[1])
551
678
  ? null
552
679
  : bad;
@@ -562,7 +689,7 @@ function validateFilter(name, args) {
562
689
  case "monochrome":
563
690
  return args !== null && /^[0-9a-fA-F]{6}$/.test(args) ? null : bad;
564
691
  case "pixelate":
565
- return args !== null && isIntIn(args, 1, MAX_DIMENSION) ? null : bad;
692
+ return isUintIn(args, 1, MAX_DIMENSION) ? null : bad;
566
693
  case "flip":
567
694
  return isOneOf(FLIP_AXES, args) ? null : bad;
568
695
  case "overlay": {
@@ -577,14 +704,14 @@ function validateFilter(name, args) {
577
704
  return bad;
578
705
  let rest = fields;
579
706
  if (fields.length >= 6) {
580
- if (!isIntIn(fields[fields.length - 1], 1, 400))
707
+ if (!isUintIn(fields[fields.length - 1], 1, 400))
581
708
  return bad;
582
709
  rest = fields.slice(0, -1);
583
710
  }
584
711
  const blend = rest[rest.length - 1];
585
712
  if (!isOneOf(BLEND_MODES, blend))
586
713
  return bad;
587
- if (!isIntIn(rest[rest.length - 2], 0, 100))
714
+ if (!isUintIn(rest[rest.length - 2], 0, 100))
588
715
  return bad;
589
716
  if (!isIntIn(rest[rest.length - 3], -2147483648, 2147483647))
590
717
  return bad;
@@ -618,19 +745,15 @@ function validateFilter(name, args) {
618
745
  return bad;
619
746
  const parts = args.split(",");
620
747
  return parts.length === 4 &&
621
- parts.every((p) => isIntIn(p, 0, MAX_DIMENSION)) &&
622
- Number(parts[2]) >= 1 &&
623
- Number(parts[3]) >= 1
748
+ isUintIn(parts[0], 0, MAX_DIMENSION) &&
749
+ isUintIn(parts[1], 0, MAX_DIMENSION) &&
750
+ isUintIn(parts[2], 1, MAX_DIMENSION) &&
751
+ isUintIn(parts[3], 1, MAX_DIMENSION)
624
752
  ? null
625
753
  : bad;
626
754
  }
627
755
  case "max_bytes":
628
- return args !== null &&
629
- /^[+-]?\d+$/.test(args) &&
630
- BigInt(args) >= 1n &&
631
- BigInt(args) <= 18446744073709551615n
632
- ? null
633
- : bad;
756
+ return isUintIn(args, 1, 18446744073709551615n) ? null : bad;
634
757
  case "text": {
635
758
  if (args === null)
636
759
  return bad;
@@ -643,7 +766,7 @@ function validateFilter(name, args) {
643
766
  const text = percentDecodable(parts.slice(0, -3).join(","));
644
767
  return ANCHOR_NAMES.has(anchor) &&
645
768
  /^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(color) &&
646
- isIntIn(size, 1, 1000) &&
769
+ isUintIn(size, 1, 1000) &&
647
770
  text !== null &&
648
771
  text !== "" &&
649
772
  textLabelFits(text, Number(size))
@@ -660,7 +783,7 @@ function validateFilter(name, args) {
660
783
  const y = parts[parts.length - 2];
661
784
  const x = parts[parts.length - 3];
662
785
  const url = percentDecodable(parts.slice(0, -3).join(","));
663
- return isIntIn(alpha, 0, 100) &&
786
+ return isUintIn(alpha, 0, 100) &&
664
787
  isIntIn(y, -2147483648, 2147483647) &&
665
788
  isIntIn(x, -2147483648, 2147483647) &&
666
789
  url !== null &&
@@ -672,14 +795,16 @@ function validateFilter(name, args) {
672
795
  return `unknown filter: ${name}`;
673
796
  }
674
797
  }
675
- function explainFilters(rest) {
676
- // The server splits the list on the ':' separators that
677
- // sit outside parentheses (url.rs split_filter_chain):
678
- // an argument list may itself contain ':' (the studio
679
- // filter's named arguments are `key:value`), so a naive
680
- // split would cut those filters apart. Unbalanced
681
- // parentheses leave the tail in one part, which then
682
- // fails its own parse, as on the server.
798
+ /**
799
+ * The filters of a `filters:` segment's list. The server splits
800
+ * the list on the ':' separators that sit outside parentheses
801
+ * (url.rs split_filter_chain): an argument list may itself
802
+ * contain ':' (the studio filter's named arguments are
803
+ * `key:value`), so a naive split would cut those filters apart.
804
+ * Unbalanced parentheses leave the tail in one part, which then
805
+ * fails its own parse, as on the server.
806
+ */
807
+ function filterChain(rest) {
683
808
  const parts = [];
684
809
  let depth = 0;
685
810
  let start = 0;
@@ -697,8 +822,11 @@ function explainFilters(rest) {
697
822
  }
698
823
  }
699
824
  parts.push(rest.slice(start));
825
+ return parts;
826
+ }
827
+ function explainFilters(rest) {
700
828
  const blurbs = [];
701
- for (const part of parts) {
829
+ for (const part of filterChain(rest)) {
702
830
  const match = part.match(/^([a-z_0-9]+)(?:\((.*)\))?$/);
703
831
  if (!match) {
704
832
  return { error: `malformed filter: ${part}` };
@@ -717,6 +845,80 @@ function explainFilters(rest) {
717
845
  }
718
846
  return { detail: blurbs.join("; ") };
719
847
  }
848
+ /** The most operations one request runs (url.rs MAX_OPERATIONS). */
849
+ export const MAX_OPERATIONS = 100;
850
+ /**
851
+ * The most distinct watermark and overlay URLs one request
852
+ * names (url.rs MAX_WATERMARK_URLS, issue #613).
853
+ */
854
+ export const MAX_WATERMARK_URLS = 16;
855
+ /**
856
+ * The decoded image URL a valid `watermark(...)` or
857
+ * `overlay(...)` filter composites, or null for any other
858
+ * filter. Both split from the right, as validateFilter reads
859
+ * them.
860
+ */
861
+ function compositedUrl(filter) {
862
+ const match = filter.match(/^(watermark|overlay)\((.*)\)$/);
863
+ if (!match)
864
+ return null;
865
+ const fields = match[2].split(",");
866
+ const numeric = match[1] === "watermark" ? 3 : fields.length >= 6 ? 5 : 4;
867
+ return percentDecodable(fields.slice(0, -numeric).join(","));
868
+ }
869
+ /**
870
+ * The caps the server applies once a request parses (url.rs
871
+ * check_operation_count and check_watermark_count, issues #469
872
+ * and #613): at most {@link MAX_OPERATIONS} operations, each
873
+ * filter in a `filters:` segment counting once, and at most
874
+ * {@link MAX_WATERMARK_URLS} distinct watermark and overlay
875
+ * URLs, compared as decoded. A preset reference counts as one
876
+ * operation: its definition holds at least one, and the
877
+ * explainer sees neither the definition nor the server's
878
+ * default operations, so both counts are lower bounds, and a
879
+ * cap they pass is one the server refuses too.
880
+ */
881
+ function capErrors(segments) {
882
+ let operations = 0;
883
+ let presets = false;
884
+ const urls = new Set();
885
+ for (const { raw, kind } of segments) {
886
+ if (kind === "expiry" || kind === "maxage")
887
+ continue;
888
+ presets ||= kind === "preset";
889
+ if (kind === "operation" && raw.startsWith("filters:")) {
890
+ for (const filter of filterChain(raw.slice(8))) {
891
+ operations += 1;
892
+ const url = compositedUrl(filter);
893
+ if (url !== null)
894
+ urls.add(url);
895
+ }
896
+ }
897
+ else {
898
+ operations += 1;
899
+ }
900
+ }
901
+ const errors = [];
902
+ const atLeast = presets ? "at least " : "";
903
+ if (operations > MAX_OPERATIONS) {
904
+ errors.push(`the request has ${atLeast}${operations} operations, over the ${MAX_OPERATIONS} operation limit: the server answers 400 (unsupported_operation)`);
905
+ }
906
+ else if (urls.size > MAX_WATERMARK_URLS) {
907
+ errors.push(`the request names ${urls.size} distinct watermark and overlay URLs, over the ${MAX_WATERMARK_URLS} URL limit: the server answers 400 (unsupported_operation)`);
908
+ }
909
+ return errors;
910
+ }
911
+ /**
912
+ * `<left>x<top>:<right>x<bottom>` as url.rs parse_rect_points
913
+ * reads it (crop-rect and focal): four u32s, with the right
914
+ * edge past the left and the bottom past the top.
915
+ */
916
+ function isRectPoints(rest) {
917
+ const m = rest.match(/^(\+?\d+)x(\+?\d+):(\+?\d+)x(\+?\d+)$/);
918
+ if (!m || !m.slice(1).every((n) => isUintIn(n, 0, 4294967295)))
919
+ return false;
920
+ return BigInt(m[3]) > BigInt(m[1]) && BigInt(m[4]) > BigInt(m[2]);
921
+ }
720
922
  const ALIGN_NAMES = new Set(CROP_ALIGNS);
721
923
  const U64_MAX = 18446744073709551615n;
722
924
  /**
@@ -743,11 +945,11 @@ function parseObjectsAlign(align) {
743
945
  if (!tail.startsWith(":"))
744
946
  return null;
745
947
  const text = tail.slice(1);
746
- if (!isFloat(text))
948
+ // An f32 above 0 and at most 100, the bound applied to
949
+ // the rounded value, as on the server.
950
+ if (!f32In(text, 0, 100, true))
747
951
  return null;
748
952
  scale = Number(text);
749
- if (!(scale > 0) || scale > 100)
750
- return null;
751
953
  }
752
954
  const parts = list.split(",");
753
955
  const classes = [];
@@ -841,9 +1043,14 @@ function explainSegment(seg, nowSeconds) {
841
1043
  const rest = seg.slice(6);
842
1044
  // The server's frame grammar (url.rs parse_frame): the
843
1045
  // poster keyword, or a strict decimal (no sign, no
844
- // exponent, no leading dot) as seconds up to 86400 or,
845
- // with a % suffix, as a percent up to 100.
846
- const decimal = (text, max) => /^\d+(\.\d+)?$/.test(text) && Number(text) <= max;
1046
+ // exponent, no leading dot) read as an f64, as seconds up
1047
+ // to 86400 or, with a % suffix, as a percent up to 100.
1048
+ const decimal = (text, max) => {
1049
+ if (!/^\d+(\.\d+)?$/.test(text))
1050
+ return false;
1051
+ const value = readDecimal(text, 64);
1052
+ return value !== null && value <= max;
1053
+ };
847
1054
  if (rest === "poster") {
848
1055
  return { kind: "operation", title: "Frame", detail: "render the video source's poster frame" };
849
1056
  }
@@ -886,11 +1093,7 @@ function explainSegment(seg, nowSeconds) {
886
1093
  }
887
1094
  if (seg.startsWith("crop-rect:")) {
888
1095
  const rest = seg.slice(10);
889
- const m = rest.match(/^([+-]?\d+)x([+-]?\d+):([+-]?\d+)x([+-]?\d+)$/);
890
- if (!m ||
891
- m.slice(1).some((n) => BigInt(n) < 0n || BigInt(n) > 4294967295n) ||
892
- BigInt(m[3]) <= BigInt(m[1]) ||
893
- BigInt(m[4]) <= BigInt(m[2])) {
1096
+ if (!isRectPoints(rest)) {
894
1097
  return {
895
1098
  kind: "operation",
896
1099
  title: "Crop rectangle",
@@ -901,11 +1104,7 @@ function explainSegment(seg, nowSeconds) {
901
1104
  }
902
1105
  if (seg.startsWith("focal:")) {
903
1106
  const rest = seg.slice(6);
904
- const m = rest.match(/^([+-]?\d+)x([+-]?\d+):([+-]?\d+)x([+-]?\d+)$/);
905
- if (!m ||
906
- m.slice(1).some((n) => BigInt(n) < 0n || BigInt(n) > 4294967295n) ||
907
- BigInt(m[3]) <= BigInt(m[1]) ||
908
- BigInt(m[4]) <= BigInt(m[2])) {
1107
+ if (!isRectPoints(rest)) {
909
1108
  return {
910
1109
  kind: "operation",
911
1110
  title: "Focal rectangle",
@@ -920,15 +1119,12 @@ function explainSegment(seg, nowSeconds) {
920
1119
  const point = colon === -1 ? rest : rest.slice(0, colon);
921
1120
  const zoomText = colon === -1 ? null : rest.slice(colon + 1);
922
1121
  const xy = point.split("x");
1122
+ // Each number an f32, the bounds applied to the rounded
1123
+ // value (url.rs parse_focal_point).
923
1124
  const ok = xy.length === 2 &&
924
- isFloat(xy[0]) &&
925
- isFloat(xy[1]) &&
926
- Number(xy[0]) >= 0 &&
927
- Number(xy[0]) <= 1 &&
928
- Number(xy[1]) >= 0 &&
929
- Number(xy[1]) <= 1 &&
930
- (zoomText === null ||
931
- (isFloat(zoomText) && Number(zoomText) > 0 && Number(zoomText) <= 100));
1125
+ f32In(xy[0], 0, 1) &&
1126
+ f32In(xy[1], 0, 1) &&
1127
+ (zoomText === null || f32In(zoomText, 0, 100, true));
932
1128
  if (!ok) {
933
1129
  return {
934
1130
  kind: "operation",
@@ -1150,6 +1346,17 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
1150
1346
  signature = { kind: "invalid", value: signatureRaw, detail: "not `unsafe` and not lowercase hex: the server rejects it as malformed (400)" };
1151
1347
  errors.push("malformed signature segment");
1152
1348
  }
1349
+ // Remainders the server refuses before it reads an
1350
+ // operation, whatever the signature (server/admission.rs
1351
+ // resolve_request): the segment key derivation owns, and
1352
+ // the endpoints' own segments.
1353
+ const head = remainder.split("/", 1)[0];
1354
+ if (isReservedRemainder(remainder)) {
1355
+ errors.push("the remainder begins with the reserved segment crabcrop, which key derivation owns: the server answers 400 (reserved_segment)");
1356
+ }
1357
+ else if (head === "purge" || head === "purge-group" || head === "upload") {
1358
+ errors.push("an image URL may not begin with a purge or upload segment: the server answers 400 (reserved_segment)");
1359
+ }
1153
1360
  const segments = [];
1154
1361
  let rest = remainder;
1155
1362
  let source = "";
@@ -1186,5 +1393,9 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
1186
1393
  if (!source && rest) {
1187
1394
  source = rest;
1188
1395
  }
1396
+ // The caps apply to a request that parses, as on the server.
1397
+ if (errors.length === 0) {
1398
+ errors.push(...capErrors(segments));
1399
+ }
1189
1400
  return { signature, segments, source, remainder, errors };
1190
1401
  }
package/dist/index.d.ts CHANGED
@@ -1,21 +1,4 @@
1
- /**
2
- * The first remainder segment reserved for key derivation.
3
- * Every derived subkey (purge, purge-group, upload, seal, and
4
- * the server's cache entry key) is the HMAC of a label such as
5
- * `crabcrop/purge-key` under the secret, which is the image
6
- * signature of that label. No image URL may begin with this
7
- * segment (the server refuses one with `400 reserved_segment`),
8
- * and {@link sign} and every builder refuse a remainder that
9
- * does, so no image signature is ever a subkey.
10
- */
11
- export declare const RESERVED_SEGMENT = "crabcrop";
12
- /**
13
- * Whether `remainder` begins with {@link RESERVED_SEGMENT}: it
14
- * is that segment alone or starts with `crabcrop/`. The test is
15
- * on the text as written, as the HMAC is: `exp:1/crabcrop/x`
16
- * and `CRABCROP/x` are not reserved.
17
- */
18
- export declare function isReservedRemainder(remainder: string): boolean;
1
+ export { isReservedRemainder, RESERVED_SEGMENT } from "./limits.ts";
19
2
  /**
20
3
  * Compute the signature segment for a remainder: the lowercase
21
4
  * hex HMAC-SHA256 of `remainder` under `secret`. The remainder
@@ -34,8 +17,24 @@ export declare function sign(secret: string, remainder: string): string;
34
17
  * signature: no signer signs a label (see
35
18
  * {@link RESERVED_SEGMENT}). This is the signature segment
36
19
  * for `POST /purge/<signature>/<path>`.
20
+ *
21
+ * With `expires` (unix seconds), the signature covers
22
+ * `exp:<expires>/<path>` instead, and the request path is
23
+ * `POST /purge/<signature>/exp:<expires>/<path>`: the
24
+ * expiry sits inside the signed string, so it can neither
25
+ * be stripped nor extended, and the server refuses the
26
+ * purge once that second is reached. Without it the
27
+ * signature authorizes the purge until the secret rotates.
28
+ * An expiry that is not a non-negative integer throws.
29
+ *
30
+ * The server reads a leading `exp:` segment of the path as
31
+ * the purge's own expiry, so a target that opens with an
32
+ * image URL's `exp:` is refused from that second on. An
33
+ * image's `exp:` is not part of its cache key:
34
+ * drop it from the target and the purge evicts the same
35
+ * entries.
37
36
  */
38
- export declare function purgeSignature(secret: string, target: string): string;
37
+ export declare function purgeSignature(secret: string, target: string, expires?: number): string;
39
38
  /**
40
39
  * The purge-group signature for a cache group: HMAC-SHA256
41
40
  * of the group name under a subkey derived from the secret
@@ -46,8 +45,14 @@ export declare function purgeSignature(secret: string, target: string): string;
46
45
  * exists so nobody has to know the signed string. This is
47
46
  * the signature segment for
48
47
  * `POST /purge-group/<signature>/<group>`.
48
+ *
49
+ * With `expires` (unix seconds), the signature covers
50
+ * `exp:<expires>/<group>`, the request path is
51
+ * `POST /purge-group/<signature>/exp:<expires>/<group>`, and
52
+ * the server refuses the purge once that second is
53
+ * reached, as for {@link purgeSignature}.
49
54
  */
50
- export declare function purgeGroupSignature(secret: string, group: string): string;
55
+ export declare function purgeGroupSignature(secret: string, group: string, expires?: number): string;
51
56
  /**
52
57
  * The upload signature for an object name: HMAC-SHA256 of
53
58
  * the name under a subkey derived from the secret (the raw
package/dist/index.js CHANGED
@@ -7,27 +7,10 @@
7
7
  */
8
8
  import { aes256GcmOpen, aes256GcmSeal, hmacSha256, randomBytes, timingSafeEqual, } from "#crypto";
9
9
  import { fromBase64Url, toBase64Url, toHex, utf8, utf8Strict } from "./bytes.js";
10
- import { MAX_DIMENSION } from "./limits.js";
11
- /**
12
- * The first remainder segment reserved for key derivation.
13
- * Every derived subkey (purge, purge-group, upload, seal, and
14
- * the server's cache entry key) is the HMAC of a label such as
15
- * `crabcrop/purge-key` under the secret, which is the image
16
- * signature of that label. No image URL may begin with this
17
- * segment (the server refuses one with `400 reserved_segment`),
18
- * and {@link sign} and every builder refuse a remainder that
19
- * does, so no image signature is ever a subkey.
20
- */
21
- export const RESERVED_SEGMENT = "crabcrop";
22
- /**
23
- * Whether `remainder` begins with {@link RESERVED_SEGMENT}: it
24
- * is that segment alone or starts with `crabcrop/`. The test is
25
- * on the text as written, as the HMAC is: `exp:1/crabcrop/x`
26
- * and `CRABCROP/x` are not reserved.
27
- */
28
- export function isReservedRemainder(remainder) {
29
- return remainder === RESERVED_SEGMENT || remainder.startsWith(`${RESERVED_SEGMENT}/`);
30
- }
10
+ import { isReservedRemainder, MAX_DIMENSION, RESERVED_SEGMENT } from "./limits.js";
11
+ // Declared beside MAX_DIMENSION, where the explainer reads them
12
+ // too (issue #712).
13
+ export { isReservedRemainder, RESERVED_SEGMENT } from "./limits.js";
31
14
  function assertNotReserved(remainder) {
32
15
  if (isReservedRemainder(remainder)) {
33
16
  throw new Error(`remainder begins with the reserved segment "${RESERVED_SEGMENT}": it is kept for key derivation, and no image URL may begin with it`);
@@ -54,6 +37,18 @@ export function sign(secret, remainder) {
54
37
  function subkey(secret, label) {
55
38
  return hmacSha256(secret, label);
56
39
  }
40
+ /**
41
+ * The signed string of a purge or purge-group signature:
42
+ * the target, or `exp:<expires>/` and the target. It is also
43
+ * what follows the signature segment in the request path.
44
+ */
45
+ function purgeSignedString(target, expires) {
46
+ if (expires === undefined) {
47
+ return target;
48
+ }
49
+ assertExpires(expires);
50
+ return `exp:${expires}/${target}`;
51
+ }
57
52
  /**
58
53
  * The purge signature for a target path (the request
59
54
  * remainder without its signature): HMAC-SHA256 of the
@@ -63,9 +58,26 @@ function subkey(secret, label) {
63
58
  * signature: no signer signs a label (see
64
59
  * {@link RESERVED_SEGMENT}). This is the signature segment
65
60
  * for `POST /purge/<signature>/<path>`.
61
+ *
62
+ * With `expires` (unix seconds), the signature covers
63
+ * `exp:<expires>/<path>` instead, and the request path is
64
+ * `POST /purge/<signature>/exp:<expires>/<path>`: the
65
+ * expiry sits inside the signed string, so it can neither
66
+ * be stripped nor extended, and the server refuses the
67
+ * purge once that second is reached. Without it the
68
+ * signature authorizes the purge until the secret rotates.
69
+ * An expiry that is not a non-negative integer throws.
70
+ *
71
+ * The server reads a leading `exp:` segment of the path as
72
+ * the purge's own expiry, so a target that opens with an
73
+ * image URL's `exp:` is refused from that second on. An
74
+ * image's `exp:` is not part of its cache key:
75
+ * drop it from the target and the purge evicts the same
76
+ * entries.
66
77
  */
67
- export function purgeSignature(secret, target) {
68
- return toHex(hmacSha256(subkey(secret, "crabcrop/purge-key"), target));
78
+ export function purgeSignature(secret, target, expires) {
79
+ const signed = purgeSignedString(target, expires);
80
+ return toHex(hmacSha256(subkey(secret, "crabcrop/purge-key"), signed));
69
81
  }
70
82
  /**
71
83
  * The purge-group signature for a cache group: HMAC-SHA256
@@ -77,9 +89,16 @@ export function purgeSignature(secret, target) {
77
89
  * exists so nobody has to know the signed string. This is
78
90
  * the signature segment for
79
91
  * `POST /purge-group/<signature>/<group>`.
92
+ *
93
+ * With `expires` (unix seconds), the signature covers
94
+ * `exp:<expires>/<group>`, the request path is
95
+ * `POST /purge-group/<signature>/exp:<expires>/<group>`, and
96
+ * the server refuses the purge once that second is
97
+ * reached, as for {@link purgeSignature}.
80
98
  */
81
- export function purgeGroupSignature(secret, group) {
82
- return toHex(hmacSha256(subkey(secret, "crabcrop/purge-group-key"), group));
99
+ export function purgeGroupSignature(secret, group, expires) {
100
+ const signed = purgeSignedString(group, expires);
101
+ return toHex(hmacSha256(subkey(secret, "crabcrop/purge-group-key"), signed));
83
102
  }
84
103
  /**
85
104
  * The upload signature for an object name: HMAC-SHA256 of
package/dist/limits.d.ts CHANGED
@@ -7,3 +7,22 @@
7
7
  * integrations all check against this one constant.
8
8
  */
9
9
  export declare const MAX_DIMENSION = 16383;
10
+ /**
11
+ * The first remainder segment reserved for key derivation.
12
+ * Every derived subkey (purge, purge-group, upload, seal, and
13
+ * the server's cache entry key) is the HMAC of a label such as
14
+ * `crabcrop/purge-key` under the secret, which is the image
15
+ * signature of that label. No image URL may begin with this
16
+ * segment (the server refuses one with `400 reserved_segment`),
17
+ * and `sign` and every builder refuse a remainder that does,
18
+ * so no image signature is ever a subkey. The explainer reports
19
+ * such a remainder as the server answers it.
20
+ */
21
+ export declare const RESERVED_SEGMENT = "crabcrop";
22
+ /**
23
+ * Whether `remainder` begins with {@link RESERVED_SEGMENT}: it
24
+ * is that segment alone or starts with `crabcrop/`. The test is
25
+ * on the text as written, as the HMAC is: `exp:1/crabcrop/x`
26
+ * and `CRABCROP/x` are not reserved.
27
+ */
28
+ export declare function isReservedRemainder(remainder: string): boolean;
package/dist/limits.js CHANGED
@@ -7,3 +7,24 @@
7
7
  * integrations all check against this one constant.
8
8
  */
9
9
  export const MAX_DIMENSION = 16383;
10
+ /**
11
+ * The first remainder segment reserved for key derivation.
12
+ * Every derived subkey (purge, purge-group, upload, seal, and
13
+ * the server's cache entry key) is the HMAC of a label such as
14
+ * `crabcrop/purge-key` under the secret, which is the image
15
+ * signature of that label. No image URL may begin with this
16
+ * segment (the server refuses one with `400 reserved_segment`),
17
+ * and `sign` and every builder refuse a remainder that does,
18
+ * so no image signature is ever a subkey. The explainer reports
19
+ * such a remainder as the server answers it.
20
+ */
21
+ export const RESERVED_SEGMENT = "crabcrop";
22
+ /**
23
+ * Whether `remainder` begins with {@link RESERVED_SEGMENT}: it
24
+ * is that segment alone or starts with `crabcrop/`. The test is
25
+ * on the text as written, as the HMAC is: `exp:1/crabcrop/x`
26
+ * and `CRABCROP/x` are not reserved.
27
+ */
28
+ export function isReservedRemainder(remainder) {
29
+ return remainder === RESERVED_SEGMENT || remainder.startsWith(`${RESERVED_SEGMENT}/`);
30
+ }
package/package.json CHANGED
@@ -29,7 +29,7 @@
29
29
  "test": "node --test && node --conditions=browser --test"
30
30
  },
31
31
  "type": "module",
32
- "version": "0.13.1",
32
+ "version": "0.15.0",
33
33
  "devDependencies": {
34
34
  "@types/node": "^26.6.5",
35
35
  "typescript": "^7.0.2"