@crabcrop/mcp 0.1.0 → 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/dist/index.js CHANGED
@@ -19,7 +19,7 @@
19
19
  * Run: node src/index.ts (Node >= 22, for type stripping)
20
20
  */
21
21
  import { buildURL, explainUrl, purgeSignature } from "@crabcrop/url";
22
- const SERVER = { name: "crabcrop", version: "0.1.0" };
22
+ const SERVER = { name: "crabcrop", version: "0.9.11" };
23
23
  const PROTOCOL = "2024-11-05";
24
24
  const envBase = process.env.CRABCROP_BASE ?? "";
25
25
  const envSecret = process.env.CRABCROP_SECRET ?? null;
@@ -214,6 +214,14 @@ const TOOLS = [
214
214
  if (target.origin !== new URL(envBase).origin) {
215
215
  return textResult(`fetch_meta: refusing to fetch ${target.origin}; only the configured server origin (${new URL(envBase).origin}) is allowed`, true);
216
216
  }
217
+ // The system endpoints are not meta targets (issue
218
+ // #271): this tool's contract is the meta JSON of an
219
+ // image URL, and /metrics is token-gated on the
220
+ // server besides, so the tool is not a route around
221
+ // the gate.
222
+ if (target.pathname === "/metrics" || target.pathname === "/health") {
223
+ return textResult(`fetch_meta: refusing to fetch the system endpoint ${target.pathname}; this tool reads meta for image URLs`, true);
224
+ }
217
225
  const accept = boolArg(args, "placeholders")
218
226
  ? "application/json; placeholders=1"
219
227
  : "application/json";
@@ -1,11 +1,11 @@
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
 
7
7
  ```ts
8
- import { buildURL, buildSrcSet, purgeGroupSignature, purgeSignature, sign, uploadSignature, verifyUrlSignature } from "@crabcrop/url";
8
+ import { buildSealedURL, buildURL, buildSrcSet, purgeGroupSignature, purgeSignature, seal, sign, unseal, uploadSignature, verifyUrlSignature } from "@crabcrop/url";
9
9
 
10
10
  // A signed URL. The operation string is passed verbatim and may
11
11
  // contain several segments and preset: references.
@@ -48,7 +48,23 @@ const group = purgeGroupSignature("your-secret", "thumb");
48
48
 
49
49
  // Upload signatures for the server's PUT /upload/<signature>/<name>
50
50
  // endpoint live in a third domain, under their own derived subkey.
51
+ // Pass an expiry (unix seconds) for a token that stops working
52
+ // then; its path is /upload/<signature>/exp:<expiry>/<name>.
51
53
  const upload = uploadSignature("your-secret", "heroes/photo.jpg");
54
+ const expiring = uploadSignature("your-secret", "heroes/photo.jpg", 1893456000);
55
+
56
+ // Sealed URLs (issue #255): the whole remainder encrypted into an
57
+ // opaque token in the signature slot, for public links whose recipe
58
+ // should stay unreadable. The server serves the sealed and plain
59
+ // forms of one render from the same cache entry.
60
+ const sealedUrl = buildSealedURL(
61
+ "https://images.example.com",
62
+ "your-secret",
63
+ "300x200",
64
+ "https://example.com/photo.jpg",
65
+ { name: "photo.jpg" },
66
+ );
67
+ const remainder = unseal("your-secret", seal("your-secret", "300x200/https://example.com/photo.jpg"));
52
68
  ```
53
69
 
54
70
  Pass `null` as the secret to produce the literal `unsafe` signature segment, for servers running with `CRABCROP_ALLOW_UNSAFE` or in presets-only mode.
@@ -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;
@@ -13,19 +13,27 @@ export const FILTER_DESCRIPTIONS = {
13
13
  blurfaces: "blur detected faces (needs a face model on the server)",
14
14
  brighten: "brighten by the given amount (-255..255)",
15
15
  contrast: "contrast in percent, -100..100 (0 is unchanged, -100 is flat)",
16
+ gamma: "gamma correction with divisor g, 0 < g <= 10: each channel becomes 255 * (v / 255)^(1 / g) (1 is unchanged, above 1 brightens midtones)",
17
+ exposure: "exposure in stops, -10..10: multiply the linear light by 2^stops (0 is unchanged, positive brightens, negative darkens)",
18
+ highlights_shadows: "adjust the highlights and shadows ranges independently: two percents, each -100..100 (0 is unchanged)",
19
+ vibrance: "saturation weighted toward the muted colors: percent, -100..100 (0 is unchanged; vivid colors and skin tones are protected)",
16
20
  huerotate: "rotate the hue by the given degrees",
17
21
  rotate: "rotate by the given angle in degrees; the canvas expands to fit",
18
- quality: "output quality 1..100, or `auto` for perceptual targeting",
19
- format: "force the output format",
22
+ quality: "output quality 1..100, or `auto` for perceptual targeting; or per-format values in one list (quality(80,jpeg:90,webp:75)), resolved after format negotiation",
23
+ palette: "write PNG output as an indexed (palette) image with at most this many colors, 2..256; ignored by the other formats",
24
+ format: "force the output format; a format also takes its encoder options (format(jpeg,progressive), format(png,interlace), format(webp,method:6,sns:50)); an option its encoder cannot honour is refused",
20
25
  fill: "the background color other operations pad with",
21
26
  facepad: "how much a face crop expands around the face",
22
27
  pixelatefaces: "pixelate detected faces (needs a face model on the server)",
23
28
  blurclass: "blur every detected object of the named class (needs a detection model on the server)",
24
29
  pixelateclass: "pixelate every detected object of the named class (needs a detection model on the server)",
30
+ recolorclass: "recolor every detected object of the named class to the given color (needs a detection model on the server)",
25
31
  removebg: "remove the background (needs an AI model on the server)",
32
+ studio: "studio mode: `product` composites the subject onto a backdrop (bg: white, a RRGGBB color, brand, or none) with a synthesized contact shadow (shadow: soft, strong, or none), scaled and centered to a pad margin (pad: 0..40, default 10); `scene` keeps the photograph's scene, reframing it on the detected subject with light and color correction (pad only) (needs an AI model on the server)",
26
33
  keep_profile: "keep the source color profile instead of converting to sRGB",
27
34
  upscale: "AI upscale by the given factor (needs an AI model on the server)",
28
35
  equalize: "histogram equalization",
36
+ enhance: "gentle per-channel auto-levels (0.5th percentile to 0, 99.5th to 255)",
29
37
  saturation: "saturation factor, 0..255 (0 is grayscale, 1 is identity)",
30
38
  sharpen: "sharpen by the given amount",
31
39
  text: "draw a text overlay (needs a font on the server)",
@@ -33,7 +41,7 @@ export const FILTER_DESCRIPTIONS = {
33
41
  curve: "tone curve: remap the named channel (rgb, r, g, or b) through 2 to 16 x,y control points, linearly interpolated, ends clamped",
34
42
  convolution: "convolve with a 3x3 or 5x5 kernel: 9 or 25 row-major values (plain decimals, -1024..1024), then a normalize flag (0 or 1); edges replicate",
35
43
  noise: "add monochrome film grain: one deterministic noise value per pixel on all channels, strength 0..100 percent of full scale (0 is a no-op)",
36
- trim: "trim uniform borders",
44
+ trim: "trim uniform borders; the five-argument form (tolerance,left,top,right,bottom) also removes that many pixels per side after the tolerance pass",
37
45
  dpr: "device pixel ratio the sizes are multiplied by",
38
46
  watermark: "overlay a watermark image",
39
47
  max_bytes: "cap the output size, lowering quality to fit",
@@ -48,6 +56,7 @@ export const FILTER_DESCRIPTIONS = {
48
56
  blur_region: "gaussian-blur the rectangle (x,y,w,h) in pixels at this point in the chain (redaction)",
49
57
  overlay: "composite another image over the result: (url,x,y,alpha,blend[,width %]) with blend normal, multiply, screen, or overlay",
50
58
  pixelate_region: "pixelate the rectangle (x,y,w,h) in pixels at this point in the chain (redaction)",
59
+ remove_region: "erase the rectangle (x,y,w,h) in pixels at this point in the chain and inpaint it from the surrounding pixels (AI region removal)",
51
60
  };
52
61
  const MAX_DIMENSION = 16383;
53
62
  function parseDimension(part) {
@@ -101,6 +110,7 @@ const NO_ARG_FILTERS = new Set([
101
110
  "invert",
102
111
  "no_upscale",
103
112
  "equalize",
113
+ "enhance",
104
114
  "removebg",
105
115
  "keep_profile",
106
116
  "sepia",
@@ -163,9 +173,24 @@ function validateFilter(name, args) {
163
173
  return args === null ? null : bad;
164
174
  }
165
175
  switch (name) {
166
- case "trim":
167
- return args === null || isIntIn(args, 0, 255) ? null : bad;
176
+ case "trim": {
177
+ if (args === null)
178
+ return null;
179
+ const parts = args.split(",");
180
+ if (parts.length === 1)
181
+ return isIntIn(parts[0], 0, 255) ? null : bad;
182
+ return parts.length === 5 &&
183
+ isIntIn(parts[0], 0, 255) &&
184
+ parts.slice(1).every((p) => isIntIn(p, 0, 4294967295))
185
+ ? null
186
+ : bad;
187
+ }
168
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;
169
194
  case "sharpen":
170
195
  return args !== null && isFloat(args) && Number(args) > 0 ? null : bad;
171
196
  case "brighten":
@@ -176,14 +201,103 @@ function validateFilter(name, args) {
176
201
  return args !== null && isFloat(args) && Number(args) >= -100 && Number(args) <= 100
177
202
  ? null
178
203
  : bad;
204
+ case "gamma":
205
+ return args !== null && isFloat(args) && Number(args) > 0 && Number(args) <= 10
206
+ ? null
207
+ : bad;
208
+ case "exposure":
209
+ return args !== null && isFloat(args) && Number(args) >= -10 && Number(args) <= 10
210
+ ? null
211
+ : bad;
212
+ case "highlights_shadows": {
213
+ if (args === null)
214
+ return bad;
215
+ const parts = args.split(",");
216
+ return parts.length === 2 &&
217
+ parts.every((p) => isFloat(p) && Number(p) >= -100 && Number(p) <= 100)
218
+ ? null
219
+ : bad;
220
+ }
221
+ case "vibrance":
222
+ return args !== null && isFloat(args) && Number(args) >= -100 && Number(args) <= 100
223
+ ? null
224
+ : bad;
179
225
  case "saturation":
180
226
  return args !== null && isFloat(args) && Number(args) >= 0 && Number(args) <= 255
181
227
  ? null
182
228
  : bad;
183
- case "quality":
184
- return args === "auto" || (args !== null && isIntIn(args, 1, 100)) ? null : bad;
185
- case "format":
186
- return args !== null && FORMAT_NAMES.has(args) ? null : bad;
229
+ case "quality": {
230
+ if (args === null)
231
+ return bad;
232
+ if (args === "auto" || isIntIn(args, 1, 100))
233
+ return null;
234
+ // Per-format list (issue #319): at most one bare
235
+ // fallback, at most one entry per format, no video
236
+ // formats (their quality is not the server's to set).
237
+ const seen = new Set();
238
+ let fallbackSeen = false;
239
+ for (const part of args.split(",")) {
240
+ const colon = part.indexOf(":");
241
+ if (colon === -1) {
242
+ if (fallbackSeen || !(part === "auto" || isIntIn(part, 1, 100)))
243
+ return bad;
244
+ fallbackSeen = true;
245
+ }
246
+ else {
247
+ const name = part.slice(0, colon);
248
+ const value = part.slice(colon + 1);
249
+ if (!FORMAT_NAMES.has(name) || name === "mp4" || name === "webm")
250
+ return bad;
251
+ const canonical = name === "jpg" ? "jpeg" : name;
252
+ if (seen.has(canonical))
253
+ return bad;
254
+ seen.add(canonical);
255
+ if (!(value === "auto" || isIntIn(value, 1, 100)))
256
+ return bad;
257
+ }
258
+ }
259
+ return seen.size + (fallbackSeen ? 1 : 0) > 0 ? null : bad;
260
+ }
261
+ case "palette":
262
+ return args !== null && isIntIn(args, 2, 256) ? null : bad;
263
+ case "format": {
264
+ if (args === null)
265
+ return bad;
266
+ // A format name plus its encoder options (issue #319),
267
+ // each validated against the format it belongs to.
268
+ const parts = args.split(",");
269
+ const [name, ...options] = parts;
270
+ if (!FORMAT_NAMES.has(name))
271
+ return bad;
272
+ const seen = new Set();
273
+ for (const option of options) {
274
+ const key = option.includes(":") ? option.slice(0, option.indexOf(":")) : option;
275
+ if (seen.has(key))
276
+ return bad;
277
+ seen.add(key);
278
+ if (name === "jpeg" || name === "jpg") {
279
+ if (option === "progressive")
280
+ continue;
281
+ if (/^subsampling:(444|422|420)$/.test(option))
282
+ continue;
283
+ return bad;
284
+ }
285
+ if (name === "png") {
286
+ if (option === "interlace")
287
+ continue;
288
+ return bad;
289
+ }
290
+ if (name === "webp") {
291
+ if (/^method:[0-6]$/.test(option))
292
+ continue;
293
+ if (/^sns:\d+$/.test(option) && isIntIn(option.slice(4), 0, 100))
294
+ continue;
295
+ return bad;
296
+ }
297
+ return bad;
298
+ }
299
+ return null;
300
+ }
187
301
  case "rgb": {
188
302
  if (args === null)
189
303
  return bad;
@@ -228,6 +342,55 @@ function validateFilter(name, args) {
228
342
  return args !== null && /^[+-]?\d+$/.test(args) && (Number(args) === 2 || Number(args) === 4)
229
343
  ? null
230
344
  : bad;
345
+ case "studio": {
346
+ // The server's studio grammar (url.rs parse_studio):
347
+ // the mode (`product` or `scene`) first, then named
348
+ // `key:value` arguments, each key at most once.
349
+ // Product takes `bg`, `shadow`, and `pad`; scene
350
+ // takes `pad` only, because a backdrop and a shadow
351
+ // are product concepts (naming one under scene is a
352
+ // bad argument, not a silent no-op).
353
+ if (args === null)
354
+ return bad;
355
+ const parts = args.split(",");
356
+ const mode = parts[0];
357
+ if (mode !== "product" && mode !== "scene")
358
+ return bad;
359
+ const seen = new Set();
360
+ for (const part of parts.slice(1)) {
361
+ const cut = part.indexOf(":");
362
+ if (cut === -1)
363
+ return bad;
364
+ const key = part.slice(0, cut);
365
+ const value = part.slice(cut + 1);
366
+ if (seen.has(key))
367
+ return bad;
368
+ seen.add(key);
369
+ if (key === "pad") {
370
+ // The pad parses as a Rust u8 (an optional `+`,
371
+ // then digits; no minus sign, not even `-0`) and
372
+ // is bounded to 40.
373
+ if (!/^\+?\d+$/.test(value) || BigInt(value) > 40n)
374
+ return bad;
375
+ }
376
+ else if (mode === "product" && key === "bg") {
377
+ if (value !== "white" &&
378
+ value !== "brand" &&
379
+ value !== "none" &&
380
+ !/^[0-9a-fA-F]{6}$/.test(value)) {
381
+ return bad;
382
+ }
383
+ }
384
+ else if (mode === "product" && key === "shadow") {
385
+ if (value !== "none" && value !== "soft" && value !== "strong")
386
+ return bad;
387
+ }
388
+ else {
389
+ return bad;
390
+ }
391
+ }
392
+ return null;
393
+ }
231
394
  case "dpr":
232
395
  return args !== null && isFloat(args) && [1, 1.5, 2, 3].includes(Number(args))
233
396
  ? null
@@ -252,7 +415,7 @@ function validateFilter(name, args) {
252
415
  return bad;
253
416
  const parts = args.split(",");
254
417
  return parts.length === 2 &&
255
- isIntIn(parts[0], 1, 16383) &&
418
+ isIntIn(parts[0], 0, 16383) &&
256
419
  /^[0-9a-fA-F]{6}$/.test(parts[1])
257
420
  ? null
258
421
  : bad;
@@ -313,8 +476,27 @@ function validateFilter(name, args) {
313
476
  ? null
314
477
  : bad;
315
478
  }
479
+ case "recolorclass": {
480
+ if (args === null)
481
+ return bad;
482
+ const cut = args.lastIndexOf(",");
483
+ if (cut < 0)
484
+ return bad;
485
+ if (!/^[0-9a-fA-F]{6}$/.test(args.slice(cut + 1)))
486
+ return bad;
487
+ const decoded = percentDecodable(args.slice(0, cut));
488
+ if (decoded === null)
489
+ return bad;
490
+ const name = decoded.trim();
491
+ return name.length >= 1 &&
492
+ new TextEncoder().encode(name).length <= 64 &&
493
+ /^[\p{L}\p{N} _.\-/]+$/u.test(name)
494
+ ? null
495
+ : bad;
496
+ }
316
497
  case "blur_region":
317
- case "pixelate_region": {
498
+ case "pixelate_region":
499
+ case "remove_region": {
318
500
  if (args === null)
319
501
  return bad;
320
502
  const parts = args.split(",");
@@ -373,9 +555,30 @@ function validateFilter(name, args) {
373
555
  }
374
556
  }
375
557
  function explainFilters(rest) {
376
- // The server splits the list naively on ':'; a ':' inside
377
- // parentheses is not special there either.
378
- const parts = rest.split(":");
558
+ // The server splits the list on the ':' separators that
559
+ // sit outside parentheses (url.rs split_filter_chain):
560
+ // an argument list may itself contain ':' (the studio
561
+ // filter's named arguments are `key:value`), so a naive
562
+ // split would cut those filters apart. Unbalanced
563
+ // parentheses leave the tail in one part, which then
564
+ // fails its own parse, as on the server.
565
+ const parts = [];
566
+ let depth = 0;
567
+ let start = 0;
568
+ for (let i = 0; i < rest.length; i++) {
569
+ const c = rest[i];
570
+ if (c === "(") {
571
+ depth += 1;
572
+ }
573
+ else if (c === ")") {
574
+ depth = Math.max(0, depth - 1);
575
+ }
576
+ else if (c === ":" && depth === 0) {
577
+ parts.push(rest.slice(start, i));
578
+ start = i + 1;
579
+ }
580
+ }
581
+ parts.push(rest.slice(start));
379
582
  const blurbs = [];
380
583
  for (const part of parts) {
381
584
  const match = part.match(/^([a-z_0-9]+)(?:\((.*)\))?$/);
@@ -398,6 +601,59 @@ function explainFilters(rest) {
398
601
  }
399
602
  const ALIGN_NAMES = new Set(["center", "smart", "face", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"]);
400
603
  const U64_MAX = 18446744073709551615n;
604
+ /**
605
+ * The objects crop alignment (url.rs parse_objects, ported):
606
+ * `objects(<class>[,<class>...])[:<scale>]`. Returns the
607
+ * decoded class names (duplicates folded, first spelling
608
+ * kept, as the server's canonical form folds them) and the
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).
613
+ */
614
+ function parseObjectsAlign(align) {
615
+ if (!align.startsWith("objects("))
616
+ return null;
617
+ const inner = align.slice("objects(".length);
618
+ const close = inner.indexOf(")");
619
+ if (close < 0)
620
+ return null;
621
+ const list = inner.slice(0, close);
622
+ const tail = inner.slice(close + 1);
623
+ let scale = 1;
624
+ if (tail !== "") {
625
+ if (!tail.startsWith(":"))
626
+ return null;
627
+ const text = tail.slice(1);
628
+ if (!isFloat(text))
629
+ return null;
630
+ scale = Number(text);
631
+ if (!(scale > 0) || scale > 100)
632
+ return null;
633
+ }
634
+ const parts = list.split(",");
635
+ const classes = [];
636
+ const seen = new Set();
637
+ for (const part of parts) {
638
+ const decoded = percentDecodable(part);
639
+ if (decoded === null)
640
+ return null;
641
+ const name = decoded.trim();
642
+ if (name.length < 1 ||
643
+ new TextEncoder().encode(name).length > 64 ||
644
+ !/^[\p{L}\p{N} _.\-/]+$/u.test(name)) {
645
+ return null;
646
+ }
647
+ const key = name.toLowerCase();
648
+ if (!seen.has(key)) {
649
+ if (classes.length === 32)
650
+ return null;
651
+ seen.add(key);
652
+ classes.push(name);
653
+ }
654
+ }
655
+ return classes.length > 0 ? { classes, scale } : null;
656
+ }
401
657
  function explainSegment(seg, nowSeconds) {
402
658
  if (seg.startsWith("exp:")) {
403
659
  const value = seg.slice(4);
@@ -463,9 +719,45 @@ function explainSegment(seg, nowSeconds) {
463
719
  return {
464
720
  kind: "debug",
465
721
  title: "Debug view",
466
- 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, detected face boxes (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",
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",
467
723
  };
468
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
+ }
469
761
  if (seg.startsWith("preset:")) {
470
762
  const name = seg.slice(7);
471
763
  if (!name) {
@@ -507,17 +799,53 @@ function explainSegment(seg, nowSeconds) {
507
799
  }
508
800
  return { kind: "operation", title: "Focal rectangle", detail: `set the focal rectangle ${rest} for the next crop (left x top : right x bottom)` };
509
801
  }
802
+ if (seg.startsWith("focalpoint:")) {
803
+ const rest = seg.slice(11);
804
+ const colon = rest.indexOf(":");
805
+ const point = colon === -1 ? rest : rest.slice(0, colon);
806
+ const zoomText = colon === -1 ? null : rest.slice(colon + 1);
807
+ const xy = point.split("x");
808
+ const ok = xy.length === 2 &&
809
+ isFloat(xy[0]) &&
810
+ isFloat(xy[1]) &&
811
+ Number(xy[0]) >= 0 &&
812
+ Number(xy[0]) <= 1 &&
813
+ Number(xy[1]) >= 0 &&
814
+ Number(xy[1]) <= 1 &&
815
+ (zoomText === null ||
816
+ (isFloat(zoomText) && Number(zoomText) > 0 && Number(zoomText) <= 100));
817
+ if (!ok) {
818
+ return {
819
+ kind: "operation",
820
+ title: "Focal point",
821
+ error: `malformed focalpoint segment: ${seg} (want focalpoint:<x>x<y>[:<zoom>] with x and y in 0..1 and zoom in (0, 100])`,
822
+ };
823
+ }
824
+ return {
825
+ kind: "operation",
826
+ title: "Focal point",
827
+ detail: `set the focal point ${point} at zoom ${zoomText ?? "1"} for the next crop (fractions of the image dimensions; zoom above 1 tightens the crop around the point)`,
828
+ };
829
+ }
510
830
  if (seg.startsWith("crop:")) {
511
831
  const rest = seg.slice(5);
512
832
  const idx = rest.indexOf(":");
513
833
  const dims = idx === -1 ? rest : rest.slice(0, idx);
514
834
  const align = idx === -1 ? "center" : rest.slice(idx + 1);
515
835
  const cropSize = parseSizeSegment(dims);
516
- if (!cropSize || !isExactBox(cropSize) || !ALIGN_NAMES.has(align)) {
836
+ const objects = align.startsWith("objects") ? parseObjectsAlign(align) : null;
837
+ if (!cropSize || !isExactBox(cropSize) || (!ALIGN_NAMES.has(align) && objects === null)) {
517
838
  return {
518
839
  kind: "operation",
519
840
  title: "Crop",
520
- error: `malformed crop segment: ${seg} (want crop:<w>x<h>[:center|smart|face|top|bottom|left|right|top-left|top-right|bottom-left|bottom-right], pixels only, no flips)`,
841
+ error: `malformed crop segment: ${seg} (want crop:<w>x<h>[:center|smart|face|top|bottom|left|right|top-left|top-right|bottom-left|bottom-right|objects(<class>[,<class>...])[:<scale>]], pixels only, no flips)`,
842
+ };
843
+ }
844
+ if (objects !== null) {
845
+ return {
846
+ kind: "operation",
847
+ title: "Crop",
848
+ detail: `crop to the aspect of ${dims} and resize to it; alignment: objects (${objects.classes.join(", ")}): frame the union of every detection of the named classes, the union box scaled by ${objects.scale} about its center and the crop centered on it; needs a detection model on the server, and falls back to the plain center crop of the same size when none of the classes is detected`,
521
849
  };
522
850
  }
523
851
  return { kind: "operation", title: "Crop", detail: `crop to the aspect of ${dims} and resize to it; alignment: ${align === "center" ? "center (or the focal point for smart)" : align}` };
@@ -557,8 +885,41 @@ function explainSegment(seg, nowSeconds) {
557
885
  if (parseSizeSegment(seg)) {
558
886
  return { kind: "operation", title: "Resize", detail: sizeBlurb(seg) };
559
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
+ }
560
900
  return null; // Not an operation: the source starts here.
561
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
+ }
562
923
  /**
563
924
  * Parse a crabcrop URL (or bare path) back into its pieces,
564
925
  * explaining each segment. Mirrors the server's dispatch:
@@ -589,6 +950,21 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
589
950
  path = path.slice(0, cut);
590
951
  }
591
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
+ }
592
968
  const slash = path.indexOf("/");
593
969
  if (slash === -1) {
594
970
  return { signature: null, segments: [], source: "", remainder: "", errors: ["no signature segment: the path is a single segment"] };
@@ -597,6 +973,22 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
597
973
  const remainder = path.slice(slash + 1);
598
974
  let signature;
599
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
+ }
600
992
  if (signatureRaw === "unsafe") {
601
993
  signature = { kind: "unsafe", value: signatureRaw, detail: "unsigned; the server honors it only with CRABCROP_ALLOW_UNSAFE or in presets-only deployments" };
602
994
  }
@@ -610,6 +1002,10 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
610
1002
  signature = { kind: "invalid", value: signatureRaw, detail: "lowercase hex, but not a full 64-character HMAC tag: the server will answer 403" };
611
1003
  errors.push("malformed signature segment");
612
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
+ }
613
1009
  else {
614
1010
  signature = { kind: "invalid", value: signatureRaw, detail: "not `unsafe` and not lowercase hex: the server rejects it as malformed (400)" };
615
1011
  errors.push("malformed signature segment");