@snowcone-app/mockup-resolver 1.0.8 → 1.0.10

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/src/signing.ts CHANGED
@@ -40,3 +40,63 @@ export async function verifyUrl(
40
40
  }
41
41
  return result === 0;
42
42
  }
43
+
44
+ /**
45
+ * rc#262 — Ed25519 (v2) seal minting.
46
+ *
47
+ * The private key never leaves the edge/backend. Boxes hold only the 32-byte
48
+ * public half, so a compromised box can no longer forge seals for itself OR
49
+ * the fleet — which is the whole point of the migration away from the shared
50
+ * `URL_SIGNING_SECRET`.
51
+ *
52
+ * Wire format: `v2.<base64url(64-byte signature)>`. The signed canonical
53
+ * string is IDENTICAL to the v1 HMAC one, so callers need no other change.
54
+ */
55
+ export const SEAL_V2_PREFIX = "v2.";
56
+
57
+ /**
58
+ * @param url Canonical string to sign (`path?query`, seal+debug removed)
59
+ * @param pkcs8B64 Ed25519 private key, PKCS#8 DER, base64 (NOT base64url)
60
+ */
61
+ export async function signUrlV2(url: string, pkcs8B64: string): Promise<string> {
62
+ const der = Uint8Array.from(atob(pkcs8B64), (c) => c.charCodeAt(0));
63
+
64
+ let key: CryptoKey;
65
+ try {
66
+ key = await crypto.subtle.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
67
+ } catch (cause) {
68
+ // An unusable signing key is an operator error, not a request error. Throw
69
+ // with the fix named rather than silently falling back to a v1 HMAC seal —
70
+ // a silent downgrade would quietly un-do the security migration.
71
+ throw new Error(
72
+ "E_SEAL_PRIVATE_KEY_INVALID: RENDER_SEAL_PRIVATE_KEY is not an importable " +
73
+ "Ed25519 PKCS#8 key. Expect base64 of the PKCS#8 DER (64 chars for Ed25519). " +
74
+ "Regenerate with `openssl genpkey -algorithm ed25519` and re-set the secret.",
75
+ { cause },
76
+ );
77
+ }
78
+
79
+ const sig = new Uint8Array(await crypto.subtle.sign("Ed25519", key, new TextEncoder().encode(url)));
80
+
81
+ // base64url, no padding — safe to drop straight into a query string.
82
+ let bin = "";
83
+ for (const b of sig) bin += String.fromCharCode(b);
84
+ return SEAL_V2_PREFIX + btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
85
+ }
86
+
87
+ /**
88
+ * Mint the correct seal for the current rollout stage.
89
+ *
90
+ * Presence of the Ed25519 key IS the intent — there is no separate boolean to
91
+ * forget. Distribute the public key to every box FIRST; the box throws
92
+ * E_SEAL_PUBKEY_MISSING (loudly, never a silent 401) if that order is broken.
93
+ */
94
+ export async function mintSeal(
95
+ url: string,
96
+ hmacSecret: string,
97
+ ed25519PrivateKeyB64?: string,
98
+ ): Promise<string> {
99
+ return ed25519PrivateKeyB64
100
+ ? signUrlV2(url, ed25519PrivateKeyB64)
101
+ : signUrl(url, hmacSecret);
102
+ }
@@ -0,0 +1,11 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { isLoadtestExempt } from "../src/loadtest-exempt";
3
+ describe("isLoadtestExempt", () => {
4
+ const list = "172.236.245.89, 50.116.2.79";
5
+ it("exact listed IPs only", () => {
6
+ expect(isLoadtestExempt("50.116.2.79", list)).toBe(true);
7
+ expect(isLoadtestExempt("50.116.2.7", list)).toBe(false);
8
+ expect(isLoadtestExempt("unknown-ip", "unknown-ip")).toBe(false);
9
+ expect(isLoadtestExempt("172.236.245.89", undefined)).toBe(false);
10
+ });
11
+ });
@@ -7,6 +7,7 @@ import {
7
7
  PUBLIC_PARAM_GRAMMAR,
8
8
  PUBLIC_PARAM_NAMES,
9
9
  isKnownPublicParam,
10
+ parsePublicUrl,
10
11
  unknownPublicParams,
11
12
  unknownPublicParamsMessage,
12
13
  } from '@snowcone-app/mockup-url'
@@ -29,6 +30,20 @@ describe('isKnownPublicParam', () => {
29
30
  }
30
31
  })
31
32
 
33
+ it('accepts the ADR-0099 bundle families (role level) and parses them', () => {
34
+ for (const name of ['variant.top', 'pick.top', 'opt.top.Size', 'asset.top.front', 'asset.top', 'color.shorts.front']) {
35
+ expect(isKnownPublicParam(name), name).toBe(true)
36
+ }
37
+ expect(isKnownPublicParam('variant.')).toBe(false)
38
+ expect(isKnownPublicParam('pick.')).toBe(false)
39
+ const parsed = parsePublicUrl('https://img.snowcone.app/SUMSET?shop=s&asset=https%3A%2F%2Fa%2Fx.png&variant.top=tM&pick.top=TEE001&opt.shorts.Color=Navy&asset.shorts.front=https%3A%2F%2Fa%2Fy.png')
40
+ expect(parsed.variants).toEqual({ top: 'tM' })
41
+ expect(parsed.picks).toEqual({ top: 'TEE001' })
42
+ expect(parsed.options).toEqual({ 'shorts.Color': 'Navy' })
43
+ expect(parsed.design).toEqual({ 'shorts.front': { src: 'https://a/y.png' } })
44
+ expect(PUBLIC_PARAM_GRAMMAR).toMatch(/variant\.<role>, pick\.<role>/)
45
+ })
46
+
32
47
  it('rejects a bare dotted prefix (empty placement key)', () => {
33
48
  for (const name of ['asset.', 'color.', 'tile.', 'align.', 'opt.']) {
34
49
  expect(isKnownPublicParam(name), name).toBe(false)
@@ -0,0 +1,73 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import { describe, expect, it } from 'vitest'
4
+
5
+ import {
6
+ E_RENDER_URL_TOO_LONG,
7
+ MAX_DESIGN_ELEMENTS,
8
+ MAX_RENDER_URL_LENGTH,
9
+ renderUrlLengthError,
10
+ } from '@snowcone-app/mockup-url'
11
+
12
+ /**
13
+ * The design-element cap is ONE number enforced in three places: this
14
+ * resolver, the buy worker (both import MAX_DESIGN_ELEMENTS) and the render
15
+ * box (`services/rendercenter/shared/src/types.ts` CACHE_LIMITS.MAX_ELEMENTS,
16
+ * a separate repo that cannot import this package). Each side pins the
17
+ * literal and names the other; when the submodule is checked out (local dev)
18
+ * the two files are ALSO compared directly. CI checks out the monorepo
19
+ * without the submodule, so there the literal pin is the whole assertion —
20
+ * stated here so nobody reads a green run as "cross-checked".
21
+ */
22
+ describe('MAX_DESIGN_ELEMENTS drift pin (resolver ↔ buy ↔ render box)', () => {
23
+ it('pins the literal the render box enforces (rendercenter shared CACHE_LIMITS.MAX_ELEMENTS = 10)', () => {
24
+ expect(MAX_DESIGN_ELEMENTS).toBe(10)
25
+ })
26
+
27
+ it('matches the submodule copy when services/rendercenter is checked out (literal-only in CI)', () => {
28
+ const typesTs = resolve(__dirname, '../../../services/rendercenter/shared/src/types.ts')
29
+ if (!existsSync(typesTs)) {
30
+ // Submodule absent (CI): the literal pin above is the assertion.
31
+ expect(MAX_DESIGN_ELEMENTS).toBe(10)
32
+ return
33
+ }
34
+ const m = /MAX_ELEMENTS:\s*(\d+)/.exec(readFileSync(typesTs, 'utf8'))
35
+ expect(m, 'CACHE_LIMITS.MAX_ELEMENTS not found in rendercenter shared/src/types.ts').not.toBeNull()
36
+ expect(Number(m![1])).toBe(MAX_DESIGN_ELEMENTS)
37
+ })
38
+ })
39
+
40
+ describe('renderUrlLengthError (E_RENDER_URL_TOO_LONG)', () => {
41
+ const path = '/5J6AQA?shop=dqMwU8Jct3&width=800&assets='
42
+ it('accepts a URL at the ceiling and refuses one character past it', () => {
43
+ expect(MAX_RENDER_URL_LENGTH).toBe(12 * 1024)
44
+ expect(renderUrlLengthError(path + 'a'.repeat(MAX_RENDER_URL_LENGTH - path.length))).toBeNull()
45
+ const msg = renderUrlLengthError(path + 'a'.repeat(MAX_RENDER_URL_LENGTH - path.length + 1), 7)
46
+ expect(msg).not.toBeNull()
47
+ expect(msg).toContain(`${MAX_RENDER_URL_LENGTH + 1} characters`)
48
+ expect(msg).toContain('7 placements')
49
+ expect(msg).toContain(String(MAX_RENDER_URL_LENGTH))
50
+ })
51
+
52
+ it('names the fix: design=<reference> or fewer/shorter asset URLs', () => {
53
+ const msg = renderUrlLengthError('x'.repeat(MAX_RENDER_URL_LENGTH * 2), 10)!
54
+ expect(msg).toContain('design=<reference>')
55
+ expect(msg).toMatch(/fewer placements \/ shorter asset URLs/)
56
+ expect(E_RENDER_URL_TOO_LONG).toBe('E_RENDER_URL_TOO_LONG')
57
+ })
58
+
59
+ it('a realistic oversize request (7 placements × 1.9 KB asset URLs, the prod 431 repro) is refused before the seal', () => {
60
+ // The resolver base64-encodes the design array into `assets=`: 7 × ~1.9 KB
61
+ // → ~18 KB, which the render box's 16 KiB header limit answered with a
62
+ // bare 431 (2026-09-06). Model the expansion the way buildMockupUrl does.
63
+ const asset = 'https://dqMwU8Jct3.storage.snowcone.app/demo/demo-001.jpg?pad=' + 'x'.repeat(1850)
64
+ const design = ['front', 'placket', 'back', 'left_sleeve', 'right_sleeve', 'inner_collar', 'outer_collar'].map(
65
+ (placement) => ({ imageUrl: asset, placement }),
66
+ )
67
+ const assets = Buffer.from(JSON.stringify(design)).toString('base64')
68
+ expect(renderUrlLengthError(path + encodeURIComponent(assets), design.length)).not.toBeNull()
69
+ // …while the single-placement shape of the same asset URL fits comfortably.
70
+ const one = Buffer.from(JSON.stringify(design.slice(0, 1))).toString('base64')
71
+ expect(renderUrlLengthError(path + encodeURIComponent(one), 1)).toBeNull()
72
+ })
73
+ })
@@ -5,9 +5,11 @@ import {
5
5
  normalizeAlbum,
6
6
  resolveAlbumPagePlacement,
7
7
  resolveVariant,
8
+ unknownOptionPick,
8
9
  slugify,
9
10
  type ResolvedPlacement,
10
11
  type ResolvedProduct,
12
+ fetchProduct,
11
13
  } from "../src/resolve";
12
14
 
13
15
  // A size×color-style product WITH combinations (picks select the SKU).
@@ -83,6 +85,13 @@ describe("looksLikeResolveRequest", () => {
83
85
  const u = (path: string, host = "img.snowcone.app") =>
84
86
  new URL(`https://${host}${path}`);
85
87
 
88
+ // eng/0049 F3: HEAD must take the same path as GET so `curl -I` on an
89
+ // img.snowcone.app URL never lands on the JSON default route.
90
+ it("treats HEAD like GET on the img host (F3)", () => {
91
+ expect(looksLikeResolveRequest("HEAD", "img.snowcone.app", u("/JFBH0Q"))).toBe(true);
92
+ expect(looksLikeResolveRequest("POST", "img.snowcone.app", u("/JFBH0Q"))).toBe(false);
93
+ });
94
+
86
95
  it("resolves on the prod img host (leading label)", () => {
87
96
  expect(
88
97
  looksLikeResolveRequest("GET", "img.snowcone.app", u("/JFBH0Q"))
@@ -436,3 +445,230 @@ describe("assembleArtwork (base + override, ADR-0089)", () => {
436
445
  expect(r.elements).toHaveLength(0);
437
446
  });
438
447
  });
448
+
449
+ describe("fetchProduct render version (pv=)", () => {
450
+ const rawTee = {
451
+ id: "T",
452
+ variants: [{ gvid: "g1" }],
453
+ mockups: [{ id: "m1", gvids: ["g1"] }],
454
+ placements: [{ key: "front", label: "Front", type: "image", width: 12, height: 16 }],
455
+ defaultGvid: "g1",
456
+ options: { attributes: {}, combinations: [] },
457
+ album: null,
458
+ };
459
+ const kvWith = (record: unknown) =>
460
+ ({ get: async () => record }) as unknown as KVNamespace;
461
+
462
+ it("surfaces the backend's renderVersion", async () => {
463
+ const p = await fetchProduct("T", kvWith({ version: "v1", renderVersion: "r1", raw: rawTee }));
464
+ expect(p?.version).toBe("v1");
465
+ expect(p?.renderVersion).toBe("r1");
466
+ });
467
+
468
+ it("falls back to version for records published before renderVersion existed", async () => {
469
+ const p = await fetchProduct("T", kvWith({ version: "v1", raw: rawTee }));
470
+ expect(p?.renderVersion).toBe("v1");
471
+ });
472
+ });
473
+
474
+ describe("unknownOptionPick (E_OPTION_NOT_FOUND / E_OPTION_CHOICE_NOT_FOUND)", () => {
475
+ it("accepts valid picks case-insensitively and no picks at all", () => {
476
+ expect(unknownOptionPick(tee, {})).toBeNull();
477
+ expect(unknownOptionPick(tee, { size: "m" })).toBeNull();
478
+ expect(unknownOptionPick(cap, { pocket: "left chest" })).toBeNull();
479
+ });
480
+
481
+ it("names an unknown attribute with the valid ones", () => {
482
+ expect(unknownOptionPick(tee, { Colour: "Red" })).toEqual({
483
+ attribute: "Colour", choice: "Red", validAttributes: ["Size"], validChoices: null,
484
+ });
485
+ });
486
+
487
+ it("names an unknown choice with the attribute's choices (a render-only underlay pick that would otherwise render with no underlay)", () => {
488
+ expect(unknownOptionPick(cap, { Pocket: "Right chest" })).toEqual({
489
+ attribute: "Pocket", choice: "Right chest", validAttributes: ["Crown", "Pocket"], validChoices: ["None", "Left chest"],
490
+ });
491
+ expect(unknownOptionPick(tee, { Size: "XXL" })?.validChoices).toEqual(["S", "M", "L"]);
492
+ });
493
+
494
+ it("an attribute with no listed choices accepts any value (nothing to validate against)", () => {
495
+ expect(unknownOptionPick(cap, { Crown: "anything" })).toBeNull();
496
+ });
497
+ });
498
+
499
+ // ─── ADR-0099 bundles: per-role picks, variants and the mockup choice ───────
500
+ import {
501
+ bundleVariantToken,
502
+ normalizeBundle,
503
+ resolveBundleScene,
504
+ wirePlacement,
505
+ } from "../src/resolve";
506
+
507
+ const bundleRaw = {
508
+ members: [
509
+ {
510
+ role: "top",
511
+ required: true,
512
+ products: [
513
+ {
514
+ productId: "TANK01",
515
+ defaultGvid: "tS",
516
+ variants: [{ gvid: "tS", gvidForMockup: "tR" }, { gvid: "tM" }],
517
+ options: {
518
+ attributes: { Size: { affectsCombinations: true, choices: [{ label: "S" }, { label: "M" }] } },
519
+ combinations: [{ Size: "S", variantId: "tS" }, { Size: "M", variantId: "tM" }],
520
+ },
521
+ },
522
+ { productId: "TEE001", defaultGvid: "eS", variants: [{ gvid: "eS" }], options: { attributes: {}, combinations: [] } },
523
+ ],
524
+ },
525
+ {
526
+ role: "shorts",
527
+ required: true,
528
+ products: [
529
+ {
530
+ productId: "SH0RT5",
531
+ defaultGvid: null,
532
+ variants: [{ gvid: "sS" }],
533
+ options: {
534
+ attributes: { Color: { affectsCombinations: false, choices: [{ label: "Red" }, { label: "Navy" }] } },
535
+ combinations: [],
536
+ },
537
+ },
538
+ ],
539
+ },
540
+ ],
541
+ priceRule: { kind: "percent_off", bps: 1000 },
542
+ };
543
+
544
+ const bundleProduct = (): ResolvedProduct => ({
545
+ version: "v1",
546
+ renderVersion: "r1",
547
+ id: "SUMSET",
548
+ variants: [],
549
+ mockups: [
550
+ { id: "mTank", gvids: ["tS", "sS"], picks: { top: "TANK01", shorts: "SH0RT5" } },
551
+ { id: "mTee", gvids: ["eS", "sS"], picks: { top: "TEE001", shorts: "SH0RT5" } },
552
+ ],
553
+ placements: [
554
+ { key: "top.front", label: "Front", type: "image", width: 10, height: 12, role: "top", memberProductId: "TANK01" },
555
+ { key: "top.back", label: "Back", type: "image", width: 10, height: 12, role: "top", memberProductId: "TANK01" },
556
+ { key: "top.front", label: "Front", type: "image", width: 11, height: 13, role: "top", memberProductId: "TEE001" },
557
+ { key: "shorts.front", label: "Front", type: "image", width: 8, height: 9, role: "shorts", memberProductId: "SH0RT5" },
558
+ ],
559
+ defaultGvid: null,
560
+ attributes: {},
561
+ combinations: [],
562
+ album: null,
563
+ bundle: normalizeBundle(bundleRaw),
564
+ });
565
+
566
+ describe("normalizeBundle", () => {
567
+ it("normalizes members, alternatives, variants (with render gvids) and options", () => {
568
+ const b = normalizeBundle(bundleRaw)!;
569
+ expect(b.members.map((m) => m.role)).toEqual(["top", "shorts"]);
570
+ expect(b.members[0].products[0].variants).toEqual([{ gvid: "tS", gvidForMockup: "tR" }, { gvid: "tM", gvidForMockup: null }]);
571
+ expect(b.members[0].products[0].attributes.Size).toEqual({ affectsCombinations: true, choices: ["S", "M"] });
572
+ expect(b.members[1].products[0].defaultGvid).toBeNull();
573
+ });
574
+ it("is null for absent or empty blocks", () => {
575
+ expect(normalizeBundle(undefined)).toBeNull();
576
+ expect(normalizeBundle({ members: [] })).toBeNull();
577
+ expect(normalizeBundle({ members: [{ role: "x", products: [] }] })).toBeNull();
578
+ });
579
+ });
580
+
581
+ describe("resolveBundleScene", () => {
582
+ const ok = (r: ReturnType<typeof resolveBundleScene>) => {
583
+ if (!r.ok) throw new Error(`${r.code}: ${r.message}`);
584
+ return r.scene;
585
+ };
586
+
587
+ it("defaults: products[0] per slot, the member's default SKU, the RENDER gvid in the token, the best-covering mockup", () => {
588
+ const scene = ok(resolveBundleScene(bundleProduct(), { picks: {}, variants: {}, options: {} }));
589
+ expect(scene.picks).toEqual({ top: "TANK01", shorts: "SH0RT5" });
590
+ expect(scene.variantByRole).toEqual({ top: { skuGvid: "tS", renderGvid: "tR" }, shorts: { skuGvid: "sS", renderGvid: "sS" } });
591
+ expect(scene.variantToken).toBe("shorts:sS,top:tR");
592
+ expect(scene.mockupId).toBe("mTank");
593
+ expect(scene.placements.map((p) => [p.key, p.memberProductId])).toEqual([["top.front", "TANK01"], ["top.back", "TANK01"], ["shorts.front", "SH0RT5"]]);
594
+ expect(scene.optionSelections).toEqual({});
595
+ });
596
+
597
+ it("pick.<role> swaps the alternative, narrows placements and re-picks the mockup", () => {
598
+ const scene = ok(resolveBundleScene(bundleProduct(), { picks: { top: "TEE001" }, variants: {}, options: {} }));
599
+ expect(scene.picks.top).toBe("TEE001");
600
+ expect(scene.mockupId).toBe("mTee");
601
+ expect(scene.placements.map((p) => [p.key, p.width])).toEqual([["top.front", 11], ["shorts.front", 8]]);
602
+ expect(scene.variantToken).toBe("shorts:sS,top:eS");
603
+ });
604
+
605
+ it("variant.<role> and opt.<role>.<attr> resolve through the member's combinations; render-only picks are role-qualified", () => {
606
+ const byOpt = ok(resolveBundleScene(bundleProduct(), { picks: {}, variants: {}, options: { "top.size": "m", "shorts.color": "navy" } }));
607
+ expect(byOpt.variantByRole.top).toEqual({ skuGvid: "tM", renderGvid: "tM" });
608
+ expect(byOpt.optionSelections).toEqual({ "shorts.Color": "Navy" });
609
+ const byVariant = ok(resolveBundleScene(bundleProduct(), { picks: {}, variants: { top: "tM" }, options: {} }));
610
+ expect(byVariant.variantToken).toBe("shorts:sS,top:tM");
611
+ });
612
+
613
+ it("mockup= override wins; an unknown one lists the mockups", () => {
614
+ expect(ok(resolveBundleScene(bundleProduct(), { picks: {}, variants: {}, options: {}, mockupOverride: "mTee" })).mockupId).toBe("mTee");
615
+ const r = resolveBundleScene(bundleProduct(), { picks: {}, variants: {}, options: {}, mockupOverride: "nope" });
616
+ expect(r.ok).toBe(false);
617
+ if (!r.ok) expect(r.code).toBe("E_MOCKUP_NOT_FOUND");
618
+ });
619
+
620
+ it.each([
621
+ ["bare variant=", { picks: {}, variants: {}, options: {}, variantOverride: "tS" }, "E_BUNDLE_ROLE_REQUIRED", /variant\.<role>=/],
622
+ ["bare opt.<attr>", { picks: {}, variants: {}, options: { Size: "M" } }, "E_BUNDLE_ROLE_REQUIRED", /opt\.<role>\.<attribute>/],
623
+ ["unknown role in pick", { picks: { hat: "X" }, variants: {}, options: {} }, "E_BUNDLE_ROLE_NOT_FOUND", /Roles: top, shorts/],
624
+ ["unknown role in variant", { picks: {}, variants: { hat: "X" }, options: {} }, "E_BUNDLE_ROLE_NOT_FOUND", /variant\.hat=/],
625
+ ["unknown role in opt", { picks: {}, variants: {}, options: { "hat.Size": "M" } }, "E_BUNDLE_ROLE_NOT_FOUND", /opt\.hat\.Size=/],
626
+ ["unknown pick", { picks: { top: "HOODIE" }, variants: {}, options: {} }, "E_BUNDLE_PICK_NOT_FOUND", /Alternatives: TANK01, TEE001/],
627
+ ["unknown option on the member", { picks: {}, variants: {}, options: { "top.Fit": "slim" } }, "E_OPTION_NOT_FOUND", /TANK01 \(role "top"\)/],
628
+ ["unknown choice on the member", { picks: {}, variants: {}, options: { "shorts.Color": "Teal" } }, "E_OPTION_CHOICE_NOT_FOUND", /Valid choices: Red, Navy/],
629
+ ])("fails loudly: %s", (_name, input, code, re) => {
630
+ const r = resolveBundleScene(bundleProduct(), input as any);
631
+ expect(r.ok).toBe(false);
632
+ if (!r.ok) {
633
+ expect(r.code).toBe(code);
634
+ expect(r.message).toMatch(re);
635
+ expect(r.status).toBe(400);
636
+ }
637
+ });
638
+
639
+ it("no mockups → 422 E_BUNDLE_NO_MOCKUP", () => {
640
+ const p = bundleProduct();
641
+ p.mockups = [];
642
+ const r = resolveBundleScene(p, { picks: {}, variants: {}, options: {} });
643
+ expect(r.ok).toBe(false);
644
+ if (!r.ok) expect([r.status, r.code]).toEqual([422, "E_BUNDLE_NO_MOCKUP"]);
645
+ });
646
+
647
+ it("the variant token is sorted by role (deterministic cache key)", () => {
648
+ expect(bundleVariantToken({ top: { renderGvid: "b" }, shorts: { renderGvid: "a" } })).toBe("shorts:a,top:b");
649
+ });
650
+ });
651
+
652
+ describe("assembleArtwork on a bundle (role-scoped wire keys)", () => {
653
+ it("elements carry the role-scoped key as their placement; base broadcasts across the pick set; overrides by scoped key", () => {
654
+ const scene = ok2(resolveBundleScene(bundleProduct(), { picks: {}, variants: {}, options: {} }));
655
+ const view = { ...bundleProduct(), placements: scene.placements };
656
+ const findPlacement = (k: string) => view.placements.find((p) => p.key === k) ?? null;
657
+ const base = assembleArtwork(view, { asset: "https://a/x.png", design: {}, house: "https://h/b.png", findPlacement });
658
+ expect(base.ok && base.elements.map((e) => e.placement)).toEqual(["top.front", "top.back", "shorts.front"]);
659
+ const over = assembleArtwork(view, { asset: "https://a/x.png", design: { "shorts.front": { src: "https://a/y.png" } }, house: "https://h/b.png", findPlacement });
660
+ expect(over.ok && over.elements.find((e) => e.placement === "shorts.front")).toMatchObject({ imageUrl: "https://a/y.png" });
661
+ const bad = assembleArtwork(view, { asset: null, design: { "top.left_sleeve": { src: "https://a/y.png" } }, house: "https://h/b.png", findPlacement });
662
+ expect(bad.ok).toBe(false);
663
+ if (!bad.ok) expect(bad.message).toMatch(/Valid placements: top.front, top.back, shorts.front/);
664
+ });
665
+ it("single-product placements keep the label on the wire", () => {
666
+ expect(wirePlacement({ key: "front", label: "Front", type: "image", width: 1, height: 1 })).toBe("Front");
667
+ expect(wirePlacement({ key: "top.front", label: "Front", type: "image", width: 1, height: 1, role: "top" })).toBe("top.front");
668
+ });
669
+ });
670
+
671
+ function ok2(r: ReturnType<typeof resolveBundleScene>) {
672
+ if (!r.ok) throw new Error(`${r.code}: ${r.message}`);
673
+ return r.scene;
674
+ }
@@ -0,0 +1,84 @@
1
+ import crypto from "node:crypto";
2
+
3
+ import { describe, expect, it } from "vitest";
4
+
5
+ import { signUrl, signUrlV2, mintSeal, SEAL_V2_PREFIX } from "../src/signing";
6
+
7
+ /**
8
+ * rc#262 — the edge signs, the box only verifies.
9
+ *
10
+ * These tests pin the exact contract the rendercenter verifier
11
+ * (api/src/utils/seal-ed25519.ts) implements, using an INDEPENDENT
12
+ * implementation (node:crypto) to verify what WebCrypto produced. If the two
13
+ * runtimes ever disagree, that is precisely the failure this catches — a
14
+ * seal that mints fine at the edge and 401s on every box.
15
+ */
16
+
17
+ const kp = crypto.generateKeyPairSync("ed25519");
18
+ const PKCS8_B64 = kp.privateKey.export({ type: "pkcs8", format: "der" }).toString("base64");
19
+ const RAW_PUB = kp.publicKey.export({ type: "spki", format: "der" }).subarray(12);
20
+
21
+ /** Verify exactly the way a box does: raw 32-byte pubkey, SPKI-wrapped. */
22
+ function boxVerifies(canonical: string, seal: string): boolean {
23
+ const sig = Buffer.from(seal.slice(SEAL_V2_PREFIX.length), "base64url");
24
+ const pub = crypto.createPublicKey({
25
+ key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), RAW_PUB]),
26
+ format: "der",
27
+ type: "spki",
28
+ });
29
+ return crypto.verify(null, Buffer.from(canonical), pub, sig);
30
+ }
31
+
32
+ describe("signUrlV2", () => {
33
+ const canonical = "/mockup?product=tee&width=800";
34
+
35
+ it("mints a seal a box can verify with only the public key", async () => {
36
+ const seal = await signUrlV2(canonical, PKCS8_B64);
37
+ expect(seal.startsWith(SEAL_V2_PREFIX)).toBe(true);
38
+ expect(boxVerifies(canonical, seal)).toBe(true);
39
+ });
40
+
41
+ it("produces a 64-byte signature (86 base64url chars)", async () => {
42
+ const seal = await signUrlV2(canonical, PKCS8_B64);
43
+ expect(seal.slice(SEAL_V2_PREFIX.length)).toHaveLength(86);
44
+ });
45
+
46
+ it("is URL-safe — no +, / or = to escape", async () => {
47
+ const seal = await signUrlV2(canonical, PKCS8_B64);
48
+ expect(seal).toMatch(/^v2\.[A-Za-z0-9_-]+$/);
49
+ });
50
+
51
+ it("does not verify against a different canonical string", async () => {
52
+ const seal = await signUrlV2(canonical, PKCS8_B64);
53
+ expect(boxVerifies("/mockup?product=tee&width=4000", seal)).toBe(false);
54
+ });
55
+
56
+ it("throws a named error on an unusable key rather than downgrading", async () => {
57
+ // A silent fall back to a v1 HMAC seal would quietly undo the migration.
58
+ await expect(signUrlV2(canonical, "bm90LWEta2V5")).rejects.toThrow(
59
+ /E_SEAL_PRIVATE_KEY_INVALID/,
60
+ );
61
+ });
62
+ });
63
+
64
+ describe("mintSeal rollout gate", () => {
65
+ const canonical = "/mockup?product=tee&width=800";
66
+
67
+ it("mints a legacy HMAC seal when no Ed25519 key is configured", async () => {
68
+ const seal = await mintSeal(canonical, "hmac-secret", undefined);
69
+ expect(seal).toBe(await signUrl(canonical, "hmac-secret"));
70
+ expect(seal).toMatch(/^[0-9a-f]{16}$/);
71
+ });
72
+
73
+ it("mints v2 as soon as the Ed25519 key is present — presence IS the intent", async () => {
74
+ const seal = await mintSeal(canonical, "hmac-secret", PKCS8_B64);
75
+ expect(boxVerifies(canonical, seal)).toBe(true);
76
+ });
77
+
78
+ it("v1 and v2 seals are never confusable", async () => {
79
+ const v1 = await mintSeal(canonical, "hmac-secret", undefined);
80
+ const v2 = await mintSeal(canonical, "hmac-secret", PKCS8_B64);
81
+ expect(v1.includes(".")).toBe(false);
82
+ expect(v2.startsWith("v2.")).toBe(true);
83
+ });
84
+ });
package/wrangler.jsonc CHANGED
@@ -30,6 +30,8 @@
30
30
  // to override these prod defaults. For standalone `pnpm dev`, copy
31
31
  // .dev.vars.example -> .dev.vars.
32
32
  "vars": {
33
+ // Our nine metro relays (relay-<metro>-1): the production-shape load generator. Exact IPs; change via PR.
34
+ "LOADTEST_EXEMPT_IPS": "172.236.245.89,139.144.31.189,45.79.3.111,172.104.24.94,172.234.136.102,172.235.133.146,172.237.142.112,172.234.252.106,50.116.2.79",
33
35
  "TTL_DEFAULT": "86400",
34
36
  "LOG_LEVEL": "info",
35
37
  // MEILISEARCH_API_KEY is the public read-only search key (same as apps/www);