@crabcrop/url 0.9.9 → 0.9.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.
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. Standard library only (`node:crypto`); 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 are pinned by a grammar corpus mirrored in the playground's test suite.
3
+ Build and sign [crabcrop](https://github.com/dayvson/crabcrop) URLs from TypeScript or JavaScript. Standard library only (`node:crypto`); 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.
4
4
 
5
5
  ## Usage
6
6
 
package/dist/explain.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  /** The segment kinds an explanation is made of. */
9
9
  export type SegmentKind = "expiry" | "maxage" | "debug" | "preset" | "operation";
10
10
  /** The signature kinds an explanation can report. */
11
- export type SignatureKind = "hmac" | "unsafe" | "invalid";
11
+ export type SignatureKind = "hmac" | "unsafe" | "sealed" | "invalid";
12
12
  export interface ExplainedSegment {
13
13
  raw: string;
14
14
  kind: SegmentKind;
package/dist/explain.js CHANGED
@@ -186,6 +186,11 @@ function validateFilter(name, args) {
186
186
  : bad;
187
187
  }
188
188
  case "blur":
189
+ // The server's blur bound (url.rs MAX_BLUR_SIGMA):
190
+ // positive and at most 512.
191
+ return args !== null && isFloat(args) && Number(args) > 0 && Number(args) <= 512
192
+ ? null
193
+ : bad;
189
194
  case "sharpen":
190
195
  return args !== null && isFloat(args) && Number(args) > 0 ? null : bad;
191
196
  case "brighten":
@@ -410,7 +415,7 @@ function validateFilter(name, args) {
410
415
  return bad;
411
416
  const parts = args.split(",");
412
417
  return parts.length === 2 &&
413
- isIntIn(parts[0], 1, 16383) &&
418
+ isIntIn(parts[0], 0, 16383) &&
414
419
  /^[0-9a-fA-F]{6}$/.test(parts[1])
415
420
  ? null
416
421
  : bad;
@@ -602,6 +607,9 @@ const U64_MAX = 18446744073709551615n;
602
607
  * decoded class names (duplicates folded, first spelling
603
608
  * kept, as the server's canonical form folds them) and the
604
609
  * scale, or null when the server would reject the form.
610
+ * The 32-class cap counts distinct names, as the server's
611
+ * does: repeats are free, and a 33rd distinct name rejects
612
+ * the form (issue #408).
605
613
  */
606
614
  function parseObjectsAlign(align) {
607
615
  if (!align.startsWith("objects("))
@@ -624,8 +632,6 @@ function parseObjectsAlign(align) {
624
632
  return null;
625
633
  }
626
634
  const parts = list.split(",");
627
- if (parts.length > 32)
628
- return null;
629
635
  const classes = [];
630
636
  const seen = new Set();
631
637
  for (const part of parts) {
@@ -640,6 +646,8 @@ function parseObjectsAlign(align) {
640
646
  }
641
647
  const key = name.toLowerCase();
642
648
  if (!seen.has(key)) {
649
+ if (classes.length === 32)
650
+ return null;
643
651
  seen.add(key);
644
652
  classes.push(name);
645
653
  }
@@ -714,6 +722,42 @@ function explainSegment(seg, nowSeconds) {
714
722
  detail: "the response is a diagnostic image instead of the transform result: the canvas the next crop operates on, with the chosen focal point (magenta crosshair), the focal rectangle when one is in play, the detection boxes that fed the decision (amber), and the crop window outline (blue); with no crop it shows the focal analysis of the final image; debug responses are never cached and are served with Cache-Control: no-store; animated sources and video formats are refused with 400",
715
723
  };
716
724
  }
725
+ if (seg.startsWith("frame:")) {
726
+ const rest = seg.slice(6);
727
+ // The server's frame grammar (url.rs parse_frame): the
728
+ // poster keyword, or a strict decimal (no sign, no
729
+ // exponent, no leading dot) as seconds up to 86400 or,
730
+ // with a % suffix, as a percent up to 100.
731
+ const decimal = (text, max) => /^\d+(\.\d+)?$/.test(text) && Number(text) <= max;
732
+ if (rest === "poster") {
733
+ return { kind: "operation", title: "Frame", detail: "render the video source's poster frame" };
734
+ }
735
+ if (rest.endsWith("%") && decimal(rest.slice(0, -1), 100)) {
736
+ return { kind: "operation", title: "Frame", detail: `render the frame ${rest} through the video source` };
737
+ }
738
+ if (!rest.endsWith("%") && decimal(rest, 86400)) {
739
+ return { kind: "operation", title: "Frame", detail: `render the frame at ${rest} seconds into the video source` };
740
+ }
741
+ return {
742
+ kind: "operation",
743
+ title: "Frame",
744
+ error: `malformed frame segment: ${seg} (want frame:poster, frame:<seconds> up to 86400, or frame:<percent>% up to 100; the server answers 400)`,
745
+ };
746
+ }
747
+ if (seg.startsWith("page:")) {
748
+ const rest = seg.slice(5);
749
+ // The server's page grammar (url.rs parse_page): ASCII
750
+ // digits, leading zeros allowed, 1 to 999999.
751
+ const digits = rest.replace(/^0+/, "");
752
+ if (!/^\d+$/.test(rest) || digits === "" || digits.length > 6) {
753
+ return {
754
+ kind: "operation",
755
+ title: "Page",
756
+ error: `malformed page segment: ${seg} (want page:<n> with n from 1 to 999999; the server answers 400)`,
757
+ };
758
+ }
759
+ return { kind: "operation", title: "Page", detail: `render page ${Number(digits)} of the PDF source` };
760
+ }
717
761
  if (seg.startsWith("preset:")) {
718
762
  const name = seg.slice(7);
719
763
  if (!name) {
@@ -841,8 +885,41 @@ function explainSegment(seg, nowSeconds) {
841
885
  if (parseSizeSegment(seg)) {
842
886
  return { kind: "operation", title: "Resize", detail: sizeBlurb(seg) };
843
887
  }
888
+ if (isSizeShaped(seg)) {
889
+ // The server's dispatch (url.rs size_shaped, issue #228):
890
+ // a segment shaped like a size that fails the size
891
+ // grammar is a malformed size, not the start of the
892
+ // source, so the request is a 400 rather than a fetch
893
+ // of a nonsense source.
894
+ return {
895
+ kind: "operation",
896
+ title: "Resize",
897
+ error: `malformed size segment: ${seg} (each side is a pixel count up to ${MAX_DIMENSION}, 0, or orig; the server answers 400)`,
898
+ };
899
+ }
844
900
  return null; // Not an operation: the source starts here.
845
901
  }
902
+ /**
903
+ * The server's size-shape test (url.rs size_shaped), ported:
904
+ * an `x` joining two parts, at least one of them a dimension
905
+ * spelling (digits, `orig`, or empty, with an optional flip
906
+ * sign), and no `.` or `:` anywhere, the punctuation that
907
+ * marks URL text.
908
+ */
909
+ function isSizeShaped(seg) {
910
+ const x = seg.indexOf("x");
911
+ if (x === -1)
912
+ return false;
913
+ const left = seg.slice(0, x);
914
+ const right = seg.slice(x + 1);
915
+ if (left.includes(".") || right.includes(".") || seg.includes(":"))
916
+ return false;
917
+ const spelling = (part) => {
918
+ const digits = part.startsWith("-") ? part.slice(1) : part;
919
+ return digits === "" || digits === "orig" || /^\d+$/.test(digits);
920
+ };
921
+ return spelling(left) || spelling(right);
922
+ }
846
923
  /**
847
924
  * Parse a crabcrop URL (or bare path) back into its pieces,
848
925
  * explaining each segment. Mirrors the server's dispatch:
@@ -873,6 +950,21 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
873
950
  path = path.slice(0, cut);
874
951
  }
875
952
  const errors = [];
953
+ // A sealed URL is a single segment: the token carries
954
+ // the whole remainder encrypted, so there is no slash
955
+ // and nothing visible to itemize (issue #388).
956
+ const sealedWhole = path.match(/^(?:([A-Za-z0-9_-]{1,32}):)?s1\.([A-Za-z0-9_-]+)$/);
957
+ if (sealedWhole) {
958
+ const signature = {
959
+ kind: "sealed",
960
+ value: `s1.${sealedWhole[2]}`,
961
+ detail: "sealed token (AES-256-GCM): the operations and source are encrypted inside it, so there is nothing visible to itemize; the server opens it and serves the URL it carries",
962
+ };
963
+ if (sealedWhole[1]) {
964
+ signature.keyId = sealedWhole[1];
965
+ }
966
+ return { signature, segments: [], source: "", remainder: "", errors: [] };
967
+ }
876
968
  const slash = path.indexOf("/");
877
969
  if (slash === -1) {
878
970
  return { signature: null, segments: [], source: "", remainder: "", errors: ["no signature segment: the path is a single segment"] };
@@ -881,6 +973,22 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
881
973
  const remainder = path.slice(slash + 1);
882
974
  let signature;
883
975
  const keyed = signatureRaw.match(/^([A-Za-z0-9_-]{1,32}):([0-9a-f]{64})$/);
976
+ const sealedTok = signatureRaw.match(/^(?:([A-Za-z0-9_-]{1,32}):)?s1\.([A-Za-z0-9_-]+)$/);
977
+ if (sealedTok) {
978
+ // A sealed token with a trailing path (issue #388):
979
+ // the server opens the token and serves the URL it
980
+ // carries; the visible remainder behind it is not
981
+ // part of that URL, so there is nothing to itemize.
982
+ signature = {
983
+ kind: "sealed",
984
+ value: `s1.${sealedTok[2]}`,
985
+ detail: "sealed token (AES-256-GCM): the operations and source are encrypted inside it; the server opens it and serves the URL it carries, and anything visible after the token is not part of that URL",
986
+ };
987
+ if (sealedTok[1]) {
988
+ signature.keyId = sealedTok[1];
989
+ }
990
+ return { signature, segments: [], source: "", remainder, errors };
991
+ }
884
992
  if (signatureRaw === "unsafe") {
885
993
  signature = { kind: "unsafe", value: signatureRaw, detail: "unsigned; the server honors it only with CRABCROP_ALLOW_UNSAFE or in presets-only deployments" };
886
994
  }
@@ -894,6 +1002,10 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
894
1002
  signature = { kind: "invalid", value: signatureRaw, detail: "lowercase hex, but not a full 64-character HMAC tag: the server will answer 403" };
895
1003
  errors.push("malformed signature segment");
896
1004
  }
1005
+ else if (/^(?:[A-Za-z0-9_-]{1,32}:)?s\d+\./.test(signatureRaw)) {
1006
+ signature = { kind: "invalid", value: signatureRaw, detail: "a sealed-token shape this scheme does not open (an unknown version marker, or a malformed token body): the server answers the uniform 403 refusal, indistinguishable from a token that fails to open" };
1007
+ errors.push("malformed signature segment");
1008
+ }
897
1009
  else {
898
1010
  signature = { kind: "invalid", value: signatureRaw, detail: "not `unsafe` and not lowercase hex: the server rejects it as malformed (400)" };
899
1011
  errors.push("malformed signature segment");
@@ -95,7 +95,9 @@ export declare const ops: {
95
95
  * none of the classes is detected the render falls back
96
96
  * to the plain center crop of the same size. Duplicate
97
97
  * classes (case-insensitive) are spelled once, as the
98
- * server's canonical form spells them.
98
+ * server's canonical form spells them; at most 32
99
+ * distinct classes, and a 33rd throws, since the server
100
+ * rejects it with `invalid_crop`.
99
101
  */
100
102
  cropObjects(width: number, height: number, classes: string[], scale?: number): string;
101
103
  /** `crop-rect:10x20:110x220` (left x top : right x bottom). */
@@ -142,7 +144,7 @@ export declare const filter: {
142
144
  sepia(): string;
143
145
  blurFaces(): string;
144
146
  pixelateFaces(): string;
145
- /** Gaussian blur by sigma (positive). */
147
+ /** Gaussian blur by sigma: positive, at most the server's 512 cap. */
146
148
  blur(sigma: number): string;
147
149
  /** Unsharp-mask strength (positive). */
148
150
  sharpen(amount: number): string;
@@ -247,7 +249,7 @@ export declare const filter: {
247
249
  maxBytes(bytes: number): string;
248
250
  /** Round the corners: one radius for all, or [tl, tr, br, bl]. */
249
251
  radius(value: number | [number, number, number, number]): string;
250
- /** Paint an opaque border inside the frame (RRGGBB). */
252
+ /** Paint an opaque border inside the frame (RRGGBB); a width of 0 is a no-op. */
251
253
  border(width: number, color: string): string;
252
254
  mask(shape: MaskShape): string;
253
255
  duotone(shadow: string, highlight: string): string;
@@ -164,18 +164,25 @@ export const ops = {
164
164
  * none of the classes is detected the render falls back
165
165
  * to the plain center crop of the same size. Duplicate
166
166
  * classes (case-insensitive) are spelled once, as the
167
- * server's canonical form spells them.
167
+ * server's canonical form spells them; at most 32
168
+ * distinct classes, and a 33rd throws, since the server
169
+ * rejects it with `invalid_crop`.
168
170
  */
169
171
  cropObjects(width, height, classes, scale = 1) {
170
- if (!Array.isArray(classes) || classes.length < 1 || classes.length > 32) {
171
- fail("crop objects classes", classes, "an array of 1 to 32 class names");
172
+ if (!Array.isArray(classes) || classes.length < 1) {
173
+ fail("crop objects classes", classes, "an array of 1 to 32 distinct class names");
172
174
  }
175
+ // The cap counts distinct names, as the server's parser
176
+ // does (issue #408): repeats fold first and cost nothing.
173
177
  const seen = new Set();
174
178
  const names = [];
175
179
  for (const name of classes) {
176
180
  const encoded = className("crop objects class", name);
177
181
  const key = typeof name === "string" ? name.trim().toLowerCase() : "";
178
182
  if (!seen.has(key)) {
183
+ if (names.length === 32) {
184
+ fail("crop objects classes", classes, "an array of 1 to 32 distinct class names");
185
+ }
179
186
  seen.add(key);
180
187
  names.push(encoded);
181
188
  }
@@ -306,9 +313,12 @@ export const filter = {
306
313
  pixelateFaces() {
307
314
  return "pixelatefaces";
308
315
  },
309
- /** Gaussian blur by sigma (positive). */
316
+ /** Gaussian blur by sigma: positive, at most the server's 512 cap. */
310
317
  blur(sigma) {
311
- return `blur(${num(positiveFloat("blur sigma", sigma))})`;
318
+ if (!Number.isFinite(sigma) || sigma <= 0 || sigma > 512) {
319
+ fail("blur sigma", sigma, "a positive number up to 512");
320
+ }
321
+ return `blur(${num(sigma)})`;
312
322
  },
313
323
  /** Unsharp-mask strength (positive). */
314
324
  sharpen(amount) {
@@ -489,7 +499,11 @@ export const filter = {
489
499
  if (!IMAGE_FORMATS.includes(format)) {
490
500
  fail("format", format, `one of ${IMAGE_FORMATS.join(", ")}`);
491
501
  }
492
- const args = [format];
502
+ // The output segment is the canonical spelling: the
503
+ // `jpg` input alias spells as `jpeg`, like the server's
504
+ // canonical form.
505
+ const canonical = format === "jpg" ? "jpeg" : format;
506
+ const args = [canonical];
493
507
  const used = (key) => options[key] !== undefined;
494
508
  if (format === "jpeg" || format === "jpg") {
495
509
  if (used("interlace") || used("method") || used("sns")) {
@@ -609,9 +623,9 @@ export const filter = {
609
623
  intIn("radius", c, 0, MAX_DIMENSION);
610
624
  return `radius(${corners.join(",")})`;
611
625
  },
612
- /** Paint an opaque border inside the frame (RRGGBB). */
626
+ /** Paint an opaque border inside the frame (RRGGBB); a width of 0 is a no-op. */
613
627
  border(width, color) {
614
- return `border(${intIn("border width", width, 1, MAX_DIMENSION)},${hex6("border color", color)})`;
628
+ return `border(${intIn("border width", width, 0, MAX_DIMENSION)},${hex6("border color", color)})`;
615
629
  },
616
630
  mask(shape) {
617
631
  if (shape !== "circle" && shape !== "ellipse") {
package/package.json CHANGED
@@ -21,7 +21,7 @@
21
21
  "test": "node --test"
22
22
  },
23
23
  "type": "module",
24
- "version": "0.9.9",
24
+ "version": "0.9.11",
25
25
  "devDependencies": {
26
26
  "@types/node": "^26.6.5",
27
27
  "typescript": "^7.0.2"