@crabcrop/url 0.11.0 → 0.12.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
@@ -40,7 +40,8 @@ const srcset = buildSrcSet(
40
40
  const signature = sign("your-secret", "300x200/https://example.com/photo.jpg");
41
41
 
42
42
  // Verify a signed URL's signature locally, in constant time
43
- // (unsigned or malformed URLs return null).
43
+ // (unsigned or malformed URLs return null, and so do URLs longer
44
+ // than 64 KiB).
44
45
  const ok = verifyUrlSignature("your-secret", url);
45
46
 
46
47
  // Purge signatures for the server's /purge and /purge-group endpoints
@@ -72,6 +73,8 @@ const remainder = unseal("your-secret", seal("your-secret", "300x200/https://exa
72
73
 
73
74
  Pass `null` as the secret to produce the literal `unsafe` signature segment, for servers running with `CRABCROP_ALLOW_UNSAFE` or in presets-only mode.
74
75
 
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.
77
+
75
78
  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).
76
79
 
77
80
  ## Typed operations
package/dist/explain.d.ts CHANGED
@@ -27,6 +27,16 @@ export declare const FILTER_DESCRIPTIONS: Record<string, string>;
27
27
  export declare const CROP_ALIGNS: readonly ["center", "smart", "face", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"];
28
28
  /** Text overlay anchors (url.rs Anchor::parse). */
29
29
  export declare const TEXT_ANCHORS: readonly ["top-left", "top-center", "top-right", "center-left", "center", "center-right", "bottom-left", "bottom-center", "bottom-right"];
30
+ /** The most characters a `text` label may hold (url.rs MAX_TEXT_GLYPHS, issue #606). */
31
+ export declare const MAX_TEXT_GLYPHS = 1000;
32
+ /** The most a `text` label's character count times its size may come to (url.rs MAX_TEXT_EXTENT). */
33
+ export declare const MAX_TEXT_EXTENT = 100000;
34
+ /**
35
+ * Whether a decoded `text` label at `size` is within the
36
+ * server's caps. Characters are Unicode code points, as the
37
+ * server counts them, not bytes or UTF-16 code units.
38
+ */
39
+ export declare function textLabelFits(label: string, size: number): boolean;
30
40
  /** Output formats `format(...)` names; `jpg` is an input alias of `jpeg`. */
31
41
  export declare const IMAGE_FORMATS: readonly ["jpeg", "jpg", "png", "webp", "jxl", "avif", "gif", "mp4", "webm"];
32
42
  /**
@@ -63,6 +73,19 @@ export declare function isOneOf<T extends string | number>(list: readonly T[], v
63
73
  * MAX_OBJECTS_CLASSES).
64
74
  */
65
75
  export declare const MAX_OBJECTS_CLASSES = 32;
76
+ /**
77
+ * Trim like the server's Rust `str::trim`: exactly the
78
+ * Unicode White_Space set, from both ends. JavaScript's
79
+ * `String.prototype.trim` disagrees on two characters:
80
+ * it also strips U+FEFF, which the server keeps (so a
81
+ * class name wrapped in it is no class name), and it
82
+ * keeps U+0085, which the server strips (issue #537).
83
+ * Every place this package mirrors a server-side trim
84
+ * uses this instead of the built-in. It walks in from
85
+ * each end, so it takes time linear in the input, however
86
+ * long a run of white space is.
87
+ */
88
+ export declare function trimLikeServer(text: string): string;
66
89
  /**
67
90
  * A detection class name as the server's parse_class_name
68
91
  * takes it, already trimmed: 1 to 64 UTF-8 bytes (bytes, not
@@ -86,5 +109,9 @@ export declare function classFoldKey(name: string): string;
86
109
  *
87
110
  * Returns { signature, segments, source, remainder, errors }
88
111
  * where segments carry { raw, kind, title, detail?, error? }.
112
+ *
113
+ * Input longer than MAX_EXPLAIN_BYTES is not read: the answer
114
+ * is one error and no signature, so verifyUrlSignature returns
115
+ * null for it.
89
116
  */
90
117
  export declare function explainUrl(input: string, nowSeconds?: number): Explanation;
package/dist/explain.js CHANGED
@@ -128,6 +128,24 @@ export const TEXT_ANCHORS = [
128
128
  "bottom-center",
129
129
  "bottom-right",
130
130
  ];
131
+ /** The most characters a `text` label may hold (url.rs MAX_TEXT_GLYPHS, issue #606). */
132
+ export const MAX_TEXT_GLYPHS = 1000;
133
+ /** The most a `text` label's character count times its size may come to (url.rs MAX_TEXT_EXTENT). */
134
+ export const MAX_TEXT_EXTENT = 100000;
135
+ /**
136
+ * Whether a decoded `text` label at `size` is within the
137
+ * server's caps. Characters are Unicode code points, as the
138
+ * server counts them, not bytes or UTF-16 code units.
139
+ */
140
+ export function textLabelFits(label, size) {
141
+ let glyphs = 0;
142
+ for (const _ of label) {
143
+ glyphs += 1;
144
+ if (glyphs > MAX_TEXT_GLYPHS)
145
+ return false;
146
+ }
147
+ return glyphs * size <= MAX_TEXT_EXTENT;
148
+ }
131
149
  /** Output formats `format(...)` names; `jpg` is an input alias of `jpeg`. */
132
150
  export const IMAGE_FORMATS = ["jpeg", "jpg", "png", "webp", "jxl", "avif", "gif", "mp4", "webm"];
133
151
  /**
@@ -166,6 +184,46 @@ export function isOneOf(list, value) {
166
184
  * MAX_OBJECTS_CLASSES).
167
185
  */
168
186
  export const MAX_OBJECTS_CLASSES = 32;
187
+ /**
188
+ * Whether a UTF-16 code unit is in the Unicode White_Space
189
+ * set, the set Rust's `str::trim` strips. Every member is in
190
+ * the Basic Multilingual Plane, so one code unit is one
191
+ * character here, and a surrogate is never white space.
192
+ */
193
+ function isServerWhiteSpace(unit) {
194
+ return ((unit >= 0x0009 && unit <= 0x000d) ||
195
+ unit === 0x0020 ||
196
+ unit === 0x0085 ||
197
+ unit === 0x00a0 ||
198
+ unit === 0x1680 ||
199
+ (unit >= 0x2000 && unit <= 0x200a) ||
200
+ unit === 0x2028 ||
201
+ unit === 0x2029 ||
202
+ unit === 0x202f ||
203
+ unit === 0x205f ||
204
+ unit === 0x3000);
205
+ }
206
+ /**
207
+ * Trim like the server's Rust `str::trim`: exactly the
208
+ * Unicode White_Space set, from both ends. JavaScript's
209
+ * `String.prototype.trim` disagrees on two characters:
210
+ * it also strips U+FEFF, which the server keeps (so a
211
+ * class name wrapped in it is no class name), and it
212
+ * keeps U+0085, which the server strips (issue #537).
213
+ * Every place this package mirrors a server-side trim
214
+ * uses this instead of the built-in. It walks in from
215
+ * each end, so it takes time linear in the input, however
216
+ * long a run of white space is.
217
+ */
218
+ export function trimLikeServer(text) {
219
+ let start = 0;
220
+ let end = text.length;
221
+ while (start < end && isServerWhiteSpace(text.charCodeAt(start)))
222
+ start++;
223
+ while (end > start && isServerWhiteSpace(text.charCodeAt(end - 1)))
224
+ end--;
225
+ return text.slice(start, end);
226
+ }
169
227
  /**
170
228
  * A detection class name as the server's parse_class_name
171
229
  * takes it, already trimmed: 1 to 64 UTF-8 bytes (bytes, not
@@ -206,7 +264,12 @@ function isIntIn(s, min, max) {
206
264
  // unsigned parsers accept '+' too), then digits.
207
265
  return /^[+-]?\d+$/.test(s) && BigInt(s) >= BigInt(min) && BigInt(s) <= BigInt(max);
208
266
  }
209
- const RUST_FLOAT = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
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+)?$/;
210
273
  function isFloat(s) {
211
274
  // Rust's f32::from_str syntax (AP-23): plain decimal with
212
275
  // an optional exponent; no hex, no surrounding whitespace,
@@ -535,7 +598,7 @@ function validateFilter(name, args) {
535
598
  if (args === null)
536
599
  return bad;
537
600
  const decoded = percentDecodable(args);
538
- return decoded !== null && isClassName(decoded.trim()) ? null : bad;
601
+ return decoded !== null && isClassName(trimLikeServer(decoded)) ? null : bad;
539
602
  }
540
603
  case "recolorclass": {
541
604
  if (args === null)
@@ -546,7 +609,7 @@ function validateFilter(name, args) {
546
609
  if (!/^[0-9a-fA-F]{6}$/.test(args.slice(cut + 1)))
547
610
  return bad;
548
611
  const decoded = percentDecodable(args.slice(0, cut));
549
- return decoded !== null && isClassName(decoded.trim()) ? null : bad;
612
+ return decoded !== null && isClassName(trimLikeServer(decoded)) ? null : bad;
550
613
  }
551
614
  case "blur_region":
552
615
  case "pixelate_region":
@@ -582,7 +645,8 @@ function validateFilter(name, args) {
582
645
  /^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(color) &&
583
646
  isIntIn(size, 1, 1000) &&
584
647
  text !== null &&
585
- text !== ""
648
+ text !== "" &&
649
+ textLabelFits(text, Number(size))
586
650
  ? null
587
651
  : bad;
588
652
  }
@@ -692,7 +756,7 @@ function parseObjectsAlign(align) {
692
756
  const decoded = percentDecodable(part);
693
757
  if (decoded === null)
694
758
  return null;
695
- const name = decoded.trim();
759
+ const name = trimLikeServer(decoded);
696
760
  if (!isClassName(name))
697
761
  return null;
698
762
  const key = classFoldKey(name);
@@ -971,6 +1035,18 @@ function isSizeShaped(seg) {
971
1035
  };
972
1036
  return spelling(left) || spelling(right);
973
1037
  }
1038
+ /**
1039
+ * The most input explainUrl reads, in UTF-8 bytes: 64 KiB. It
1040
+ * bounds the work one call does, and it sits above the URL
1041
+ * limits of common CDNs and proxies.
1042
+ */
1043
+ const MAX_EXPLAIN_BYTES = 64 * 1024;
1044
+ function utf8Length(text) {
1045
+ // UTF-8 never takes fewer bytes than UTF-16 code units, so
1046
+ // the caller checks .length first and this only runs on
1047
+ // input of at most MAX_EXPLAIN_BYTES code units.
1048
+ return new TextEncoder().encode(text).length;
1049
+ }
974
1050
  /**
975
1051
  * Parse a crabcrop URL (or bare path) back into its pieces,
976
1052
  * explaining each segment. Mirrors the server's dispatch:
@@ -979,14 +1055,27 @@ function isSizeShaped(seg) {
979
1055
  *
980
1056
  * Returns { signature, segments, source, remainder, errors }
981
1057
  * where segments carry { raw, kind, title, detail?, error? }.
1058
+ *
1059
+ * Input longer than MAX_EXPLAIN_BYTES is not read: the answer
1060
+ * is one error and no signature, so verifyUrlSignature returns
1061
+ * null for it.
982
1062
  */
983
1063
  export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
1064
+ if (input.length > MAX_EXPLAIN_BYTES || utf8Length(input) > MAX_EXPLAIN_BYTES) {
1065
+ return {
1066
+ signature: null,
1067
+ segments: [],
1068
+ source: "",
1069
+ remainder: "",
1070
+ errors: [`the URL is longer than 64 KiB (${MAX_EXPLAIN_BYTES} bytes): the explainer does not read it`],
1071
+ };
1072
+ }
984
1073
  // Extract the path by string surgery, never via the URL
985
1074
  // parser: WHATWG parsing resolves dot segments (.. and
986
1075
  // %2e%2e) that the server treats as literal path bytes
987
1076
  // (audit P-3). A query or fragment is not part of the
988
1077
  // signed path, on either side.
989
- let path = input.trim();
1078
+ let path = trimLikeServer(input);
990
1079
  const scheme = path.indexOf("://");
991
1080
  if (scheme > 0 && /^[a-zA-Z][a-zA-Z0-9+.-]*$/.test(path.slice(0, scheme))) {
992
1081
  const afterAuthority = path.slice(scheme + 3);
package/dist/index.d.ts CHANGED
@@ -173,7 +173,8 @@ export { filter, joinOps, ops } from "./operations.ts";
173
173
  export type { Anchor, BlendMode, CropAlign, CurveChannel, Dimension, FormatOptions, ImageFormat, MaskShape, PerFormatQualityFormat, StudioMode, StudioOptions, StudioShadow, } from "./operations.ts";
174
174
  /**
175
175
  * Verify a URL's signature locally. Returns true or false, or
176
- * null when the URL is unsigned or malformed.
176
+ * null when the URL is unsigned or malformed, or longer than
177
+ * the 64 KiB the explainer reads.
177
178
  *
178
179
  * With a single secret string, the key ID (when the URL
179
180
  * carries one) is ignored: the question is whether this
package/dist/index.js CHANGED
@@ -361,7 +361,8 @@ export { filter, joinOps, ops } from "./operations.js";
361
361
  import { explainUrl } from "./explain.js";
362
362
  /**
363
363
  * Verify a URL's signature locally. Returns true or false, or
364
- * null when the URL is unsigned or malformed.
364
+ * null when the URL is unsigned or malformed, or longer than
365
+ * the 64 KiB the explainer reads.
365
366
  *
366
367
  * With a single secret string, the key ID (when the URL
367
368
  * carries one) is ignored: the question is whether this
@@ -256,6 +256,8 @@ export declare const filter: {
256
256
  /**
257
257
  * Draw a text overlay. Color is RRGGBB or RRGGBBAA; the
258
258
  * canonical spelling is always eight lowercase hex digits.
259
+ * The label holds at most 1000 characters, and characters
260
+ * times size is at most 100000 (the server's caps).
259
261
  */
260
262
  text(content: string, size: number, color: string, anchor: Anchor): string;
261
263
  /** Blur every detected object of the named class. */
@@ -16,7 +16,7 @@
16
16
  * still written on each side: the builders check numbers, the
17
17
  * explainer checks their spellings.
18
18
  */
19
- import { BLEND_MODES, classFoldKey, CROP_ALIGNS, CURVE_CHANNELS, DPR_FACTORS, FLIP_AXES, IMAGE_FORMATS, isClassName, isOneOf, JPEG_SUBSAMPLINGS, MASK_SHAPES, MAX_OBJECTS_CLASSES, QUALITY_FORMATS, STUDIO_BACKDROPS, STUDIO_MODES, STUDIO_SHADOWS, TEXT_ANCHORS, UPSCALE_FACTORS, } from "./explain.js";
19
+ import { BLEND_MODES, classFoldKey, CROP_ALIGNS, CURVE_CHANNELS, DPR_FACTORS, FLIP_AXES, IMAGE_FORMATS, isClassName, isOneOf, JPEG_SUBSAMPLINGS, MASK_SHAPES, MAX_OBJECTS_CLASSES, MAX_TEXT_EXTENT, MAX_TEXT_GLYPHS, QUALITY_FORMATS, STUDIO_BACKDROPS, STUDIO_MODES, STUDIO_SHADOWS, TEXT_ANCHORS, textLabelFits, trimLikeServer, UPSCALE_FACTORS, } from "./explain.js";
20
20
  import { MAX_DIMENSION } from "./limits.js";
21
21
  function fail(what, value, rule) {
22
22
  throw new Error(`${what} must be ${rule}, got ${JSON.stringify(value)}`);
@@ -173,7 +173,7 @@ function encodeArg(text) {
173
173
  return encodeURIComponent(text).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
174
174
  }
175
175
  function className(what, name) {
176
- const trimmed = name.trim();
176
+ const trimmed = trimLikeServer(name);
177
177
  if (!isClassName(trimmed)) {
178
178
  fail(what, name, "1 to 64 UTF-8 bytes of letters, digits, space, `_`, `.`, `-`, `/`");
179
179
  }
@@ -236,7 +236,7 @@ export const ops = {
236
236
  const names = [];
237
237
  for (const name of classes) {
238
238
  const encoded = className("crop objects class", name);
239
- const key = classFoldKey(name.trim());
239
+ const key = classFoldKey(trimLikeServer(name));
240
240
  if (!seen.has(key)) {
241
241
  if (names.length === MAX_OBJECTS_CLASSES) {
242
242
  fail("crop objects classes", classes, "an array of 1 to 32 distinct class names");
@@ -740,6 +740,8 @@ export const filter = {
740
740
  /**
741
741
  * Draw a text overlay. Color is RRGGBB or RRGGBBAA; the
742
742
  * canonical spelling is always eight lowercase hex digits.
743
+ * The label holds at most 1000 characters, and characters
744
+ * times size is at most 100000 (the server's caps).
743
745
  */
744
746
  text(content, size, color, anchor) {
745
747
  if (!isOneOf(TEXT_ANCHORS, anchor)) {
@@ -748,6 +750,9 @@ export const filter = {
748
750
  if (content === "")
749
751
  fail("text", content, "a non-empty label");
750
752
  intIn("text size", size, 1, 1000);
753
+ if (!textLabelFits(content, size)) {
754
+ fail("text", content, `at most ${MAX_TEXT_GLYPHS} characters, and characters times size at most ${MAX_TEXT_EXTENT}`);
755
+ }
751
756
  return `text(${encodeArg(content)},${size},${hex6or8("text color", color)},${anchor})`;
752
757
  },
753
758
  /** Blur every detected object of the named class. */
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.11.0",
32
+ "version": "0.12.0",
33
33
  "devDependencies": {
34
34
  "@types/node": "^26.6.5",
35
35
  "typescript": "^7.0.2"