@usethrottle/builder 0.2.0 → 0.3.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 +5 -2
- package/dist/chunk-XYWLWXKG.js +619 -0
- package/dist/chunk-ZLNUG6ZZ.cjs +619 -0
- package/dist/index.cjs +3 -508
- package/dist/index.js +11 -516
- package/dist/next.cjs +71 -6
- package/dist/next.d.cts +30 -1
- package/dist/next.d.ts +30 -1
- package/dist/next.js +66 -1
- package/dist/watch.d.cts +28 -0
- package/dist/watch.d.ts +28 -0
- package/package.json +2 -2
- package/dist/chunk-EERLS5TR.js +0 -98
- package/dist/chunk-UFIR4HJA.cjs +0 -98
package/dist/next.d.ts
CHANGED
|
@@ -23,6 +23,35 @@ type CreateRevalidateHandlerOptions = {
|
|
|
23
23
|
*/
|
|
24
24
|
declare function createRevalidateHandler(options: CreateRevalidateHandlerOptions): (req: Request) => Promise<Response>;
|
|
25
25
|
|
|
26
|
+
type CreateWatchSyncHandlerOptions = {
|
|
27
|
+
/** The publishable key (`tb_pk_…`): `process.env` straight in. With none the route answers 500. */
|
|
28
|
+
builderKey: string | undefined;
|
|
29
|
+
baseUrl?: string;
|
|
30
|
+
/** Default 20 000 (never below 5 000). */
|
|
31
|
+
minIntervalMs?: number;
|
|
32
|
+
/** Called with the coarse Builder tag when the generation moved. Defaults to `revalidateTag` from `next/cache`. */
|
|
33
|
+
revalidateTag?: (tag: string) => void;
|
|
34
|
+
/** For tests. */
|
|
35
|
+
fetch?: typeof fetch;
|
|
36
|
+
now?: () => number;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* The server half of the `@usethrottle/builder/watch` backstop. The watcher
|
|
40
|
+
* in an open tab only learns that the Builder's generation moved; it cannot
|
|
41
|
+
* clear the store's data cache. The tab POSTs here (a store route such as
|
|
42
|
+
* `app/api/throttle/builder-sync/route.ts`), and the route reads the site's
|
|
43
|
+
* generation uncached from the Builder with the publishable key. When it
|
|
44
|
+
* differs from the last one this instance saw (or this instance has seen
|
|
45
|
+
* none), it clears the coarse `throttle-builder` tag, and the `router.refresh()`
|
|
46
|
+
* that follows renders fresh. The Builder is read at most once per
|
|
47
|
+
* `minIntervalMs` per instance and nothing is cleared unless the generation
|
|
48
|
+
* really moved, so the route cannot be used to hammer the Builder or to empty
|
|
49
|
+
* the cache. Tags only, never a path. Answers 200 `{ changed, generation? }`
|
|
50
|
+
* (`throttled: true` inside the window), 500 with no key, 502 when the Builder
|
|
51
|
+
* cannot be read.
|
|
52
|
+
*/
|
|
53
|
+
declare function createWatchSyncHandler(options: CreateWatchSyncHandlerOptions): (req?: Request) => Promise<Response>;
|
|
54
|
+
|
|
26
55
|
/** The cookie that carries the preview token. */
|
|
27
56
|
declare const PREVIEW_COOKIE = "throttle_builder_preview";
|
|
28
57
|
/**
|
|
@@ -42,4 +71,4 @@ declare function previewMiddleware(req: Request): Response | null;
|
|
|
42
71
|
*/
|
|
43
72
|
declare function getPreviewToken(): Promise<string | undefined>;
|
|
44
73
|
|
|
45
|
-
export { type CreateRevalidateHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, getPreviewToken, previewMiddleware };
|
|
74
|
+
export { type CreateRevalidateHandlerOptions, type CreateWatchSyncHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, createWatchSyncHandler, getPreviewToken, previewMiddleware };
|
package/dist/next.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
BUILDER_TAGS,
|
|
3
|
+
DEFAULT_BASE_URL,
|
|
3
4
|
TAG_MAX_CHARS,
|
|
4
5
|
scopesToTags,
|
|
5
6
|
verifyBuilderNotice
|
|
6
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-XYWLWXKG.js";
|
|
7
8
|
|
|
8
9
|
// src/next/index.ts
|
|
9
10
|
import "server-only";
|
|
@@ -83,6 +84,69 @@ function createRevalidateHandler(options) {
|
|
|
83
84
|
};
|
|
84
85
|
}
|
|
85
86
|
|
|
87
|
+
// src/next/watch-sync.ts
|
|
88
|
+
var DEFAULT_MIN_INTERVAL_MS = 2e4;
|
|
89
|
+
var READ_TIMEOUT_MS = 5e3;
|
|
90
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), {
|
|
91
|
+
status,
|
|
92
|
+
headers: { "content-type": "application/json", "cache-control": "no-store" }
|
|
93
|
+
});
|
|
94
|
+
async function defaultRevalidateTag2() {
|
|
95
|
+
const { revalidateTag } = await import("next/cache");
|
|
96
|
+
return (tag) => revalidateTag(tag, { expire: 0 });
|
|
97
|
+
}
|
|
98
|
+
function createWatchSyncHandler(options) {
|
|
99
|
+
const minInterval = Math.max(options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS, 5e3);
|
|
100
|
+
const now = options.now ?? Date.now;
|
|
101
|
+
let known;
|
|
102
|
+
let lastReadAt;
|
|
103
|
+
let running;
|
|
104
|
+
const run = async (key) => {
|
|
105
|
+
const doFetch = options.fetch ?? fetch;
|
|
106
|
+
const base = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/u, "");
|
|
107
|
+
let generation;
|
|
108
|
+
try {
|
|
109
|
+
const response = await doFetch(`${base}/v1/site`, {
|
|
110
|
+
headers: { "X-Builder-Key": key },
|
|
111
|
+
cache: "no-store",
|
|
112
|
+
signal: AbortSignal.timeout(READ_TIMEOUT_MS)
|
|
113
|
+
});
|
|
114
|
+
if (!response.ok) throw new Error(`Builder answered ${String(response.status)}`);
|
|
115
|
+
const body = await response.json();
|
|
116
|
+
if (typeof body.generation !== "number" || !Number.isSafeInteger(body.generation))
|
|
117
|
+
throw new Error("Builder answered no generation");
|
|
118
|
+
generation = body.generation;
|
|
119
|
+
} catch {
|
|
120
|
+
return json2(502, { error: "The Builder could not be read." });
|
|
121
|
+
}
|
|
122
|
+
if (generation === known) return json2(200, { changed: false, generation });
|
|
123
|
+
const revalidate = options.revalidateTag ?? await defaultRevalidateTag2();
|
|
124
|
+
revalidate(BUILDER_TAGS.all);
|
|
125
|
+
known = generation;
|
|
126
|
+
return json2(200, { changed: true, generation });
|
|
127
|
+
};
|
|
128
|
+
return () => {
|
|
129
|
+
const key = options.builderKey;
|
|
130
|
+
if (key === void 0 || key === "")
|
|
131
|
+
return Promise.resolve(
|
|
132
|
+
json2(500, {
|
|
133
|
+
error: "createWatchSyncHandler has no Builder key: set the publishable key (tb_pk_\u2026, for example NEXT_PUBLIC_THROTTLE_BUILDER_KEY) in this environment."
|
|
134
|
+
})
|
|
135
|
+
);
|
|
136
|
+
if (key.startsWith("tb_sk_"))
|
|
137
|
+
return Promise.resolve(json2(500, { error: "createWatchSyncHandler takes the publishable key, never a secret key." }));
|
|
138
|
+
if (running) return running;
|
|
139
|
+
const at = now();
|
|
140
|
+
if (lastReadAt !== void 0 && at - lastReadAt < minInterval)
|
|
141
|
+
return Promise.resolve(json2(200, { changed: false, throttled: true }));
|
|
142
|
+
lastReadAt = at;
|
|
143
|
+
running = run(key).finally(() => {
|
|
144
|
+
running = void 0;
|
|
145
|
+
});
|
|
146
|
+
return running;
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
86
150
|
// src/next/preview.ts
|
|
87
151
|
var PREVIEW_COOKIE = "throttle_builder_preview";
|
|
88
152
|
var PREVIEW_PARAM = "throttle_builder_preview";
|
|
@@ -111,6 +175,7 @@ async function getPreviewToken() {
|
|
|
111
175
|
export {
|
|
112
176
|
PREVIEW_COOKIE,
|
|
113
177
|
createRevalidateHandler,
|
|
178
|
+
createWatchSyncHandler,
|
|
114
179
|
getPreviewToken,
|
|
115
180
|
previewMiddleware,
|
|
116
181
|
verifyBuilderNotice
|
package/dist/watch.d.cts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** No store polls faster than this, whatever it asks for. */
|
|
2
|
+
declare const MIN_INTERVAL_MS = 30000;
|
|
3
|
+
declare const DEFAULT_INTERVAL_MS = 60000;
|
|
4
|
+
type WatchGenerationInput = {
|
|
5
|
+
/** Reads the current generation. A rejection is ignored until the next check. */
|
|
6
|
+
read: () => Promise<number>;
|
|
7
|
+
intervalMs?: number;
|
|
8
|
+
onChange: (generation: number) => void;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Checks every `intervalMs` (at least 30 s) while the page is visible, and at
|
|
12
|
+
* once when it becomes visible after being hidden for a whole interval. The
|
|
13
|
+
* first answer is the baseline: only a later, different one calls `onChange`.
|
|
14
|
+
* Returns the stop function.
|
|
15
|
+
*/
|
|
16
|
+
declare function watchGeneration({ read, intervalMs, onChange, }: WatchGenerationInput): () => void;
|
|
17
|
+
type UseGenerationWatchOptions = {
|
|
18
|
+
/** The publishable key (`tb_pk_…`). */
|
|
19
|
+
builderKey: string;
|
|
20
|
+
baseUrl?: string;
|
|
21
|
+
intervalMs?: number;
|
|
22
|
+
/** Called with the new generation, for example `() => router.refresh()`. */
|
|
23
|
+
onChange: (generation: number) => void;
|
|
24
|
+
};
|
|
25
|
+
/** Watches the Builder's generation from a client component. Nothing runs on the server. */
|
|
26
|
+
declare function useGenerationWatch({ builderKey, baseUrl, intervalMs, onChange, }: UseGenerationWatchOptions): void;
|
|
27
|
+
|
|
28
|
+
export { DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, type UseGenerationWatchOptions, type WatchGenerationInput, useGenerationWatch, watchGeneration };
|
package/dist/watch.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** No store polls faster than this, whatever it asks for. */
|
|
2
|
+
declare const MIN_INTERVAL_MS = 30000;
|
|
3
|
+
declare const DEFAULT_INTERVAL_MS = 60000;
|
|
4
|
+
type WatchGenerationInput = {
|
|
5
|
+
/** Reads the current generation. A rejection is ignored until the next check. */
|
|
6
|
+
read: () => Promise<number>;
|
|
7
|
+
intervalMs?: number;
|
|
8
|
+
onChange: (generation: number) => void;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Checks every `intervalMs` (at least 30 s) while the page is visible, and at
|
|
12
|
+
* once when it becomes visible after being hidden for a whole interval. The
|
|
13
|
+
* first answer is the baseline: only a later, different one calls `onChange`.
|
|
14
|
+
* Returns the stop function.
|
|
15
|
+
*/
|
|
16
|
+
declare function watchGeneration({ read, intervalMs, onChange, }: WatchGenerationInput): () => void;
|
|
17
|
+
type UseGenerationWatchOptions = {
|
|
18
|
+
/** The publishable key (`tb_pk_…`). */
|
|
19
|
+
builderKey: string;
|
|
20
|
+
baseUrl?: string;
|
|
21
|
+
intervalMs?: number;
|
|
22
|
+
/** Called with the new generation, for example `() => router.refresh()`. */
|
|
23
|
+
onChange: (generation: number) => void;
|
|
24
|
+
};
|
|
25
|
+
/** Watches the Builder's generation from a client component. Nothing runs on the server. */
|
|
26
|
+
declare function useGenerationWatch({ builderKey, baseUrl, intervalMs, onChange, }: UseGenerationWatchOptions): void;
|
|
27
|
+
|
|
28
|
+
export { DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, type UseGenerationWatchOptions, type WatchGenerationInput, useGenerationWatch, watchGeneration };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usethrottle/builder",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Headless client for Throttle Builder: read published pages, parts, slots and site settings from a storefront, with Next.js cache, revalidation and preview helpers.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
"access": "public"
|
|
90
90
|
},
|
|
91
91
|
"scripts": {
|
|
92
|
-
"build": "tsup",
|
|
92
|
+
"build": "rm -rf dist && tsup && node scripts/check-dist.mjs",
|
|
93
93
|
"test": "vitest run",
|
|
94
94
|
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json"
|
|
95
95
|
}
|
package/dist/chunk-EERLS5TR.js
DELETED
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
|
-
|
|
5
|
-
// src/tags.ts
|
|
6
|
-
var TAG = "throttle-builder";
|
|
7
|
-
var TAG_MAX_CHARS = 256;
|
|
8
|
-
var BUILDER_TAGS = {
|
|
9
|
-
all: TAG,
|
|
10
|
-
site: `${TAG}:site`,
|
|
11
|
-
pages: `${TAG}:pages`,
|
|
12
|
-
page: (slug) => `${TAG}:page:${slug}`,
|
|
13
|
-
part: (name) => `${TAG}:part:${name}`,
|
|
14
|
-
slot: (name) => `${TAG}:slot:${name}`
|
|
15
|
-
};
|
|
16
|
-
function fitTags(tags) {
|
|
17
|
-
return [...new Set(tags)].filter((tag) => tag.length <= TAG_MAX_CHARS);
|
|
18
|
-
}
|
|
19
|
-
function scopesToTags(scopes) {
|
|
20
|
-
const out = [];
|
|
21
|
-
for (const scope of scopes) {
|
|
22
|
-
const colon = scope.indexOf(":");
|
|
23
|
-
const name = colon < 0 ? scope : scope.slice(0, colon);
|
|
24
|
-
const rest = colon < 0 ? "" : scope.slice(colon + 1);
|
|
25
|
-
if (colon < 0 && (scope === "site" || scope === "menus"))
|
|
26
|
-
out.push(BUILDER_TAGS.site, BUILDER_TAGS.part("header"), BUILDER_TAGS.part("footer"));
|
|
27
|
-
else if (colon < 0 && (scope === "header" || scope === "footer"))
|
|
28
|
-
out.push(BUILDER_TAGS.part(scope));
|
|
29
|
-
else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages);
|
|
30
|
-
else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest));
|
|
31
|
-
else if (rest !== "" && name === "slot") out.push(BUILDER_TAGS.slot(rest));
|
|
32
|
-
else out.push(BUILDER_TAGS.all);
|
|
33
|
-
}
|
|
34
|
-
return fitTags(out);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
// src/next/verify.ts
|
|
38
|
-
var SIGNATURE_LABEL = "throttle.builder-notice.v1";
|
|
39
|
-
var HEX_SHA256 = /^[0-9a-fA-F]{64}$/u;
|
|
40
|
-
var TOLERANCE_SECONDS = 300;
|
|
41
|
-
var MAX_V1 = 8;
|
|
42
|
-
var MAX_HEADER_BYTES = 1024;
|
|
43
|
-
var encoder = new TextEncoder();
|
|
44
|
-
async function hmac(secret, payload) {
|
|
45
|
-
const key = await crypto.subtle.importKey(
|
|
46
|
-
"raw",
|
|
47
|
-
encoder.encode(secret),
|
|
48
|
-
{ name: "HMAC", hash: "SHA-256" },
|
|
49
|
-
false,
|
|
50
|
-
["sign"]
|
|
51
|
-
);
|
|
52
|
-
return new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(payload)));
|
|
53
|
-
}
|
|
54
|
-
function fromHex(hex) {
|
|
55
|
-
return Uint8Array.from(
|
|
56
|
-
{ length: hex.length / 2 },
|
|
57
|
-
(_, i) => Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
|
|
58
|
-
);
|
|
59
|
-
}
|
|
60
|
-
function constantTimeEqual(left, right) {
|
|
61
|
-
const length = Math.max(left.length, right.length);
|
|
62
|
-
let difference = left.length ^ right.length;
|
|
63
|
-
for (let i = 0; i < length; i += 1) difference |= (left[i] ?? 0) ^ (right[i] ?? 0);
|
|
64
|
-
return difference === 0;
|
|
65
|
-
}
|
|
66
|
-
async function verifyBuilderNotice(input) {
|
|
67
|
-
try {
|
|
68
|
-
const { rawBody, header, secret, now } = input;
|
|
69
|
-
if (secret.length === 0 || rawBody.length === 0 || header.length === 0 || !Number.isFinite(now) || encoder.encode(header).byteLength > MAX_HEADER_BYTES)
|
|
70
|
-
return false;
|
|
71
|
-
const parts = header.split(",").map((part) => part.split("="));
|
|
72
|
-
if (parts.some((part) => part.length !== 2)) return false;
|
|
73
|
-
const timestamps = parts.filter(([k]) => k === "t").map(([, v]) => v ?? "");
|
|
74
|
-
const digests = parts.filter(([k]) => k === "v1").map(([, v]) => v ?? "");
|
|
75
|
-
if (parts.some(([k]) => k !== "t" && k !== "v1") || timestamps.length !== 1 || digests.length === 0 || digests.length > MAX_V1 || digests.some((d) => !HEX_SHA256.test(d)))
|
|
76
|
-
return false;
|
|
77
|
-
const timestampText = timestamps[0] ?? "";
|
|
78
|
-
if (!/^(?:0|[1-9][0-9]*)$/u.test(timestampText)) return false;
|
|
79
|
-
const timestamp = Number(timestampText);
|
|
80
|
-
if (!Number.isSafeInteger(timestamp) || Math.abs(now - timestamp) > TOLERANCE_SECONDS)
|
|
81
|
-
return false;
|
|
82
|
-
const expected = await hmac(secret, `${SIGNATURE_LABEL}.${timestampText}.${rawBody}`);
|
|
83
|
-
let matched = false;
|
|
84
|
-
for (const digest of digests) matched = constantTimeEqual(expected, fromHex(digest)) || matched;
|
|
85
|
-
return matched;
|
|
86
|
-
} catch {
|
|
87
|
-
return false;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
export {
|
|
92
|
-
__publicField,
|
|
93
|
-
TAG_MAX_CHARS,
|
|
94
|
-
BUILDER_TAGS,
|
|
95
|
-
fitTags,
|
|
96
|
-
scopesToTags,
|
|
97
|
-
verifyBuilderNotice
|
|
98
|
-
};
|
package/dist/chunk-UFIR4HJA.cjs
DELETED
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var __defProp = Object.defineProperty;
|
|
2
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
|
-
|
|
5
|
-
// src/tags.ts
|
|
6
|
-
var TAG = "throttle-builder";
|
|
7
|
-
var TAG_MAX_CHARS = 256;
|
|
8
|
-
var BUILDER_TAGS = {
|
|
9
|
-
all: TAG,
|
|
10
|
-
site: `${TAG}:site`,
|
|
11
|
-
pages: `${TAG}:pages`,
|
|
12
|
-
page: (slug) => `${TAG}:page:${slug}`,
|
|
13
|
-
part: (name) => `${TAG}:part:${name}`,
|
|
14
|
-
slot: (name) => `${TAG}:slot:${name}`
|
|
15
|
-
};
|
|
16
|
-
function fitTags(tags) {
|
|
17
|
-
return [...new Set(tags)].filter((tag) => tag.length <= TAG_MAX_CHARS);
|
|
18
|
-
}
|
|
19
|
-
function scopesToTags(scopes) {
|
|
20
|
-
const out = [];
|
|
21
|
-
for (const scope of scopes) {
|
|
22
|
-
const colon = scope.indexOf(":");
|
|
23
|
-
const name = colon < 0 ? scope : scope.slice(0, colon);
|
|
24
|
-
const rest = colon < 0 ? "" : scope.slice(colon + 1);
|
|
25
|
-
if (colon < 0 && (scope === "site" || scope === "menus"))
|
|
26
|
-
out.push(BUILDER_TAGS.site, BUILDER_TAGS.part("header"), BUILDER_TAGS.part("footer"));
|
|
27
|
-
else if (colon < 0 && (scope === "header" || scope === "footer"))
|
|
28
|
-
out.push(BUILDER_TAGS.part(scope));
|
|
29
|
-
else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages);
|
|
30
|
-
else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest));
|
|
31
|
-
else if (rest !== "" && name === "slot") out.push(BUILDER_TAGS.slot(rest));
|
|
32
|
-
else out.push(BUILDER_TAGS.all);
|
|
33
|
-
}
|
|
34
|
-
return fitTags(out);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
// src/next/verify.ts
|
|
38
|
-
var SIGNATURE_LABEL = "throttle.builder-notice.v1";
|
|
39
|
-
var HEX_SHA256 = /^[0-9a-fA-F]{64}$/u;
|
|
40
|
-
var TOLERANCE_SECONDS = 300;
|
|
41
|
-
var MAX_V1 = 8;
|
|
42
|
-
var MAX_HEADER_BYTES = 1024;
|
|
43
|
-
var encoder = new TextEncoder();
|
|
44
|
-
async function hmac(secret, payload) {
|
|
45
|
-
const key = await crypto.subtle.importKey(
|
|
46
|
-
"raw",
|
|
47
|
-
encoder.encode(secret),
|
|
48
|
-
{ name: "HMAC", hash: "SHA-256" },
|
|
49
|
-
false,
|
|
50
|
-
["sign"]
|
|
51
|
-
);
|
|
52
|
-
return new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(payload)));
|
|
53
|
-
}
|
|
54
|
-
function fromHex(hex) {
|
|
55
|
-
return Uint8Array.from(
|
|
56
|
-
{ length: hex.length / 2 },
|
|
57
|
-
(_, i) => Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
|
|
58
|
-
);
|
|
59
|
-
}
|
|
60
|
-
function constantTimeEqual(left, right) {
|
|
61
|
-
const length = Math.max(left.length, right.length);
|
|
62
|
-
let difference = left.length ^ right.length;
|
|
63
|
-
for (let i = 0; i < length; i += 1) difference |= (_nullishCoalesce(left[i], () => ( 0))) ^ (_nullishCoalesce(right[i], () => ( 0)));
|
|
64
|
-
return difference === 0;
|
|
65
|
-
}
|
|
66
|
-
async function verifyBuilderNotice(input) {
|
|
67
|
-
try {
|
|
68
|
-
const { rawBody, header, secret, now } = input;
|
|
69
|
-
if (secret.length === 0 || rawBody.length === 0 || header.length === 0 || !Number.isFinite(now) || encoder.encode(header).byteLength > MAX_HEADER_BYTES)
|
|
70
|
-
return false;
|
|
71
|
-
const parts = header.split(",").map((part) => part.split("="));
|
|
72
|
-
if (parts.some((part) => part.length !== 2)) return false;
|
|
73
|
-
const timestamps = parts.filter(([k]) => k === "t").map(([, v]) => _nullishCoalesce(v, () => ( "")));
|
|
74
|
-
const digests = parts.filter(([k]) => k === "v1").map(([, v]) => _nullishCoalesce(v, () => ( "")));
|
|
75
|
-
if (parts.some(([k]) => k !== "t" && k !== "v1") || timestamps.length !== 1 || digests.length === 0 || digests.length > MAX_V1 || digests.some((d) => !HEX_SHA256.test(d)))
|
|
76
|
-
return false;
|
|
77
|
-
const timestampText = _nullishCoalesce(timestamps[0], () => ( ""));
|
|
78
|
-
if (!/^(?:0|[1-9][0-9]*)$/u.test(timestampText)) return false;
|
|
79
|
-
const timestamp = Number(timestampText);
|
|
80
|
-
if (!Number.isSafeInteger(timestamp) || Math.abs(now - timestamp) > TOLERANCE_SECONDS)
|
|
81
|
-
return false;
|
|
82
|
-
const expected = await hmac(secret, `${SIGNATURE_LABEL}.${timestampText}.${rawBody}`);
|
|
83
|
-
let matched = false;
|
|
84
|
-
for (const digest of digests) matched = constantTimeEqual(expected, fromHex(digest)) || matched;
|
|
85
|
-
return matched;
|
|
86
|
-
} catch (e) {
|
|
87
|
-
return false;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
exports.__publicField = __publicField; exports.TAG_MAX_CHARS = TAG_MAX_CHARS; exports.BUILDER_TAGS = BUILDER_TAGS; exports.fitTags = fitTags; exports.scopesToTags = scopesToTags; exports.verifyBuilderNotice = verifyBuilderNotice;
|