@crabcrop/mcp 0.1.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @crabcrop/mcp
2
2
 
3
- A first-party MCP (Model Context Protocol) server for crabcrop, so coding agents can sign URLs, debug them, inspect results, and purge the cache without hand-rolling the scheme. It is a thin wrapper over [`@crabcrop/url`](../typescript) and the server's HTTP surface. The explainer comes from `@crabcrop/url`; the [playground](../../playground) ships its own copy of the same grammar, and both are pinned by a mirrored grammar corpus in their test suites, while signing everywhere runs the canonical `spec/test-vectors.json`.
3
+ A first-party MCP (Model Context Protocol) server for crabcrop, so coding agents can sign URLs, debug them, inspect results, and purge the cache without hand-rolling the scheme. It is a thin wrapper over [`@crabcrop/url`](../typescript) and the server's HTTP surface. The explainer comes from `@crabcrop/url`, as does the [playground](../../playground)'s, so every JavaScript surface reads one implementation of the grammar, pinned by the shared grammar corpora in `spec/`, while signing everywhere runs the canonical `spec/test-vectors.json`.
4
4
 
5
5
  ## Tools
6
6
 
@@ -8,8 +8,8 @@ A first-party MCP (Model Context Protocol) server for crabcrop, so coding agents
8
8
  |---|---|
9
9
  | `sign_url` | Build and sign a URL from an operation string and a source (optional expiry). |
10
10
  | `explain_url` | Parse a URL back into its signature kind, explained segments, and source; malformed segments are flagged. |
11
- | `fetch_meta` | Fetch the server's meta JSON for a URL (dimensions, format, bytes, quality, placeholders on request). Only fetches URLs on the configured `CRABCROP_BASE` origin, never follows redirects, and caps the response at 256 KiB. |
12
- | `purge_result` | Evict a cached result by its URL remainder; a preset URL works as-is (the server expands it before matching). Only purges on the configured `CRABCROP_BASE` origin (a per-call `base` must match it) and refuses paths with dot segments. |
11
+ | `fetch_meta` | Fetch the server's meta JSON for a URL (dimensions, format, bytes, quality, placeholders on request). The server needs meta mode on (`CRABCROP_META_MODE=1`); it is off by default, and the tool then reports the server's `403 meta_disabled`. Only fetches URLs on the configured `CRABCROP_BASE` origin, never follows redirects, and caps the response at 256 KiB. |
12
+ | `purge_result` | Evict a cached result by its URL remainder; a preset URL works as-is (the server expands it before matching). Only POSTs to `/purge/` under the configured `CRABCROP_BASE` (a per-call `base` must equal it) and refuses paths with dot segments. |
13
13
 
14
14
  ## Setup
15
15
 
@@ -30,7 +30,14 @@ The server runs over stdio with Node >= 22. Once published, point your MCP clien
30
30
  }
31
31
  ```
32
32
 
33
- From a checkout, it also runs directly from source (Node type-strips the TypeScript):
33
+ From a checkout, it also runs directly from source on Node 22.18 or newer, which type-strips the TypeScript. Build the SDK and install the package's link to it once first:
34
+
35
+ ```bash
36
+ cd /path/to/crabcrop/sdks/typescript && npm ci && npm run build
37
+ cd ../mcp && npm ci
38
+ ```
39
+
40
+ Then point the client at the source:
34
41
 
35
42
  ```json
36
43
  {
@@ -56,7 +63,7 @@ claude mcp add crabcrop \
56
63
  -- node /path/to/crabcrop/sdks/mcp/src/index.ts
57
64
  ```
58
65
 
59
- `CRABCROP_BASE` and `CRABCROP_SECRET` are the defaults, and the environment is the recommended home for the secret: `sign_url` and `purge_result` still accept per-call `base`/`secret` overrides, but the per-call secret is deprecated because agentic clients persist tool arguments in their transcripts. With no secret configured, `sign_url` produces `unsafe` URLs for servers that allow them. `purge_result` always requires a secret, and it only ever sends its POST to the configured `CRABCROP_BASE` origin: a per-call `base` must match that origin, with no `CRABCROP_BASE` set the tool refuses outright, and paths carrying dot segments are refused, the same origin discipline `fetch_meta` follows.
66
+ `CRABCROP_BASE` and `CRABCROP_SECRET` are the defaults, and the environment is the recommended home for the secret: `sign_url` still accepts per-call `base`/`secret` overrides and `purge_result` a per-call `secret`, but the per-call secret is deprecated because agentic clients persist tool arguments in their transcripts. With no secret configured, `sign_url` produces `unsafe` URLs for servers that allow them. `purge_result` always requires a secret, and it only ever sends its POST to `/purge/` under the configured `CRABCROP_BASE`, which may carry a path for a server mounted under a prefix (`https://example.com/img` purges at `https://example.com/img/purge/...`). The request URL is built from `CRABCROP_BASE` alone: a per-call `base` is only checked, and must equal `CRABCROP_BASE` (trailing slashes aside), so a path, query, or fragment in it cannot move the POST elsewhere on the host. `CRABCROP_BASE` itself must be an http(s) URL with no userinfo, query, or fragment; with it unset or malformed the tool refuses outright. Paths carrying dot segments are refused, and a `?` or `#` in a path is sent percent-encoded inside the path. This is the origin discipline `fetch_meta` follows, held to the configured path as well.
60
67
 
61
68
  Both this package and `@crabcrop/url` ship compiled `dist/` builds (their `prepack` runs `tsc`). The published tarball is self-contained: the declared `@crabcrop/url` dependency is a `file:` path, which no registry install could resolve, so the package bundles it (`bundleDependencies`); the tarball carries the SDK's published form under its own `node_modules`, and installing the package is all a consumer does. In this repository's tests (no install step), a register hook maps `@crabcrop/url` to the SDK sources, and the pack test does the real thing instead of simulating it: `npm pack`, `npm install` the tarball into a fresh project, and a JSON-RPC round trip against the installed bin. The end-to-end test (`npm test`) spawns this server plus a real crabcrop binary and runs sign -> fetch -> meta -> purge against it; it needs `cargo build` to have produced `target/debug/crabcrop` and uses the bench fixture photo as its source.
62
69
 
package/dist/index.js CHANGED
@@ -16,13 +16,45 @@
16
16
  * agentic clients persist tool arguments in transcripts, so
17
17
  * the environment is the right home for the secret.
18
18
  *
19
- * Run: node src/index.ts (Node >= 22, for type stripping)
19
+ * Run: node src/index.ts (Node >= 22.18, 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.10.0" };
23
23
  const PROTOCOL = "2024-11-05";
24
24
  const envBase = process.env.CRABCROP_BASE ?? "";
25
25
  const envSecret = process.env.CRABCROP_SECRET ?? null;
26
+ /**
27
+ * CRABCROP_BASE as purge_result's POST target, parsed once
28
+ * (issue #459): the purge URL is built from this with the
29
+ * URL API, never concatenated from tool arguments. The rule
30
+ * is the one source roots follow: an absolute http(s) URL
31
+ * with no userinfo, query, or fragment. A query or fragment
32
+ * would swallow the /purge/ suffix appended to the path, and
33
+ * fetch refuses userinfo with an error that echoes it back.
34
+ * The href test also catches an empty `?` or `#`, which the
35
+ * parser keeps but `search` and `hash` report as "".
36
+ */
37
+ function parsePurgeBase(raw) {
38
+ if (!raw) {
39
+ return "purge_result requires CRABCROP_BASE to be set: it only purges on the configured server's origin";
40
+ }
41
+ const invalid = "purge_result: CRABCROP_BASE must be an absolute http(s) URL with no userinfo, query, or fragment";
42
+ let url;
43
+ try {
44
+ url = new URL(raw);
45
+ }
46
+ catch {
47
+ return invalid;
48
+ }
49
+ if ((url.protocol !== "http:" && url.protocol !== "https:") ||
50
+ url.username ||
51
+ url.password ||
52
+ /[?#]/.test(url.href)) {
53
+ return invalid;
54
+ }
55
+ return url;
56
+ }
57
+ const purgeBase = parsePurgeBase(envBase);
26
58
  function textResult(text, isError = false) {
27
59
  return { content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) };
28
60
  }
@@ -101,12 +133,14 @@ async function readCapped(resp, cap) {
101
133
  * exactly `.` or `..`, with dots inside a name (`a.b`,
102
134
  * `c..d`) counting as ordinary content. Because the string
103
135
  * is later parsed as a WHATWG URL, the percent-encoded
104
- * spellings (`%2e`, `.%2e`, `%2e.`, `%2e%2e`) count too, and
136
+ * spellings (`%2e`, `.%2e`, `%2e.`, `%2e%2e`) count too,
105
137
  * backslashes are separators for http(s) URLs, so components
106
- * are split on both.
138
+ * are split on both, and ASCII tabs and newlines are dropped
139
+ * first, as the parser drops them: `.<TAB>.` reaches the
140
+ * server as `..` (issue #459).
107
141
  */
108
142
  function hasDotSegment(path) {
109
- return path.split(/[/\\]/).some((segment) => {
143
+ return path.replace(/[\t\n\r]/g, "").split(/[/\\]/).some((segment) => {
110
144
  const decoded = segment.toLowerCase().replaceAll("%2e", ".");
111
145
  return decoded === "." || decoded === "..";
112
146
  });
@@ -188,6 +222,8 @@ const TOOLS = [
188
222
  description: "Fetch the crabcrop meta JSON for a URL (the processed result's width, " +
189
223
  "height, format, byte size, quality, and placeholder data on request). " +
190
224
  "The URL must already be signed if the server requires signatures. " +
225
+ "The server must have meta mode on (CRABCROP_META_MODE=1, off by default); " +
226
+ "without it the server answers 403 meta_disabled. " +
191
227
  "For safety the URL's origin must match CRABCROP_BASE: this tool will " +
192
228
  "not fetch arbitrary URLs.",
193
229
  inputSchema: {
@@ -214,6 +250,14 @@ const TOOLS = [
214
250
  if (target.origin !== new URL(envBase).origin) {
215
251
  return textResult(`fetch_meta: refusing to fetch ${target.origin}; only the configured server origin (${new URL(envBase).origin}) is allowed`, true);
216
252
  }
253
+ // The system endpoints are not meta targets (issue
254
+ // #271): this tool's contract is the meta JSON of an
255
+ // image URL, and /metrics is token-gated on the
256
+ // server besides, so the tool is not a route around
257
+ // the gate.
258
+ if (target.pathname === "/metrics" || target.pathname === "/health") {
259
+ return textResult(`fetch_meta: refusing to fetch the system endpoint ${target.pathname}; this tool reads meta for image URLs`, true);
260
+ }
217
261
  const accept = boolArg(args, "placeholders")
218
262
  ? "application/json; placeholders=1"
219
263
  : "application/json";
@@ -244,45 +288,40 @@ const TOOLS = [
244
288
  "URL's remainder after its signature (operations and source; a preset " +
245
289
  "URL works as-is, the server expands it). Requires the signing secret (argument or " +
246
290
  "CRABCROP_SECRET). Returns how many entries were removed. " +
247
- "For safety the request only goes to the configured CRABCROP_BASE " +
248
- "origin (a base argument must match it) and paths with dot segments " +
249
- "are refused: this tool will not POST to arbitrary endpoints.",
291
+ "For safety the request only goes to /purge/ under the configured " +
292
+ "CRABCROP_BASE (a base argument must equal it) and paths with dot " +
293
+ "segments are refused: this tool will not POST to arbitrary endpoints.",
250
294
  inputSchema: {
251
295
  type: "object",
252
296
  properties: {
253
297
  path: { type: "string", description: "Remainder of the cached URL, e.g. \"300x200/https://example.com/a.jpg\"." },
254
- base: { type: "string", description: "crabcrop endpoint origin. Defaults to CRABCROP_BASE; its origin must match CRABCROP_BASE." },
298
+ base: { type: "string", description: "Redundant: the request always goes to CRABCROP_BASE, and a base argument must equal it (trailing slashes aside). Omit it." },
255
299
  secret: { type: "string", description: "Signing secret. Defaults to CRABCROP_SECRET. Sensitive, deprecated: prefer the CRABCROP_SECRET environment variable; a per-call secret is kept in client transcripts." },
256
300
  },
257
301
  required: ["path"],
258
302
  additionalProperties: false,
259
303
  },
260
304
  async run(args) {
261
- // The fetch_meta treatment (audit PL-1, extended by
262
- // R2-10): the POST may only ever go to the configured
263
- // server's origin. Without the check, a caller-chosen
264
- // base made the tool an SSRF oracle: it POSTed to
265
- // internal endpoints and read the responses back, and
266
- // dot segments in the path resolved out of the
267
- // /purge/ prefix onto arbitrary paths on that host.
268
- // Refusing before any fetch keeps every disallowed or
269
- // unreachable target indistinguishable: no request is
270
- // sent, so there is no timing, status, or body signal
271
- // to tell them apart.
272
- if (!envBase) {
273
- return textResult("purge_result requires CRABCROP_BASE to be set: it only purges on the configured server's origin", true);
305
+ // The POST may only ever go to /purge/ under the
306
+ // configured base (audit PL-1, R2-10, issue #459).
307
+ // A caller-chosen base made the tool an SSRF oracle
308
+ // that POSTed to internal endpoints and read the
309
+ // responses back, and an origin check alone left a
310
+ // path, query, or fragment on the configured origin
311
+ // free to move the POST anywhere on that host. So the
312
+ // target is built from CRABCROP_BASE alone, and a base
313
+ // argument is only checked against it. Refusing before
314
+ // any fetch keeps every disallowed or unreachable
315
+ // target indistinguishable: no request is sent, so
316
+ // there is no timing, status, or body signal to tell
317
+ // them apart.
318
+ if (typeof purgeBase === "string") {
319
+ return textResult(purgeBase, true);
274
320
  }
275
- const configuredOrigin = new URL(envBase).origin;
276
- const base = (optionalStringArg(args, "base") ?? envBase).replace(/\/+$/, "");
277
- let baseOrigin;
278
- try {
279
- baseOrigin = new URL(base).origin;
280
- }
281
- catch {
282
- return textResult(`purge_result: not a valid base URL: ${base}`, true);
283
- }
284
- if (baseOrigin !== configuredOrigin) {
285
- return textResult(`purge_result: refusing to purge ${baseOrigin}; only the configured server origin (${configuredOrigin}) is allowed`, true);
321
+ const configured = envBase.replace(/\/+$/, "");
322
+ const baseArg = optionalStringArg(args, "base");
323
+ if (baseArg !== undefined && baseArg.replace(/\/+$/, "") !== configured) {
324
+ return textResult(`purge_result: refusing base ${baseArg}; a base argument must equal CRABCROP_BASE (${configured})`, true);
286
325
  }
287
326
  const secret = optionalStringArg(args, "secret") ?? envSecret;
288
327
  if (!secret)
@@ -295,13 +334,23 @@ const TOOLS = [
295
334
  // domain-separated from image signatures (audit P-1),
296
335
  // and the derivation lives in exactly one place.
297
336
  const signature = purgeSignature(secret, target);
337
+ // Set as a path, a `?` or `#` in the target is
338
+ // percent-encoded instead of starting a query or
339
+ // fragment. The prefix check is the invariant itself,
340
+ // whatever spelling a path finds past hasDotSegment.
341
+ const url = new URL(purgeBase);
342
+ const prefix = `${url.pathname.replace(/\/+$/, "")}/purge/${signature}/`;
343
+ url.pathname = prefix + target;
344
+ if (!url.pathname.startsWith(prefix)) {
345
+ return textResult("purge_result: refusing a path that resolves out of the purge prefix", true);
346
+ }
298
347
  // The same network hygiene as fetch_meta: no
299
348
  // redirects, a bounded wait, and a capped body, so a
300
349
  // hung or hostile endpoint cannot hang the tool call
301
350
  // or stream an unbounded response.
302
351
  let resp;
303
352
  try {
304
- resp = await fetch(`${base}/purge/${signature}/${target}`, {
353
+ resp = await fetch(url, {
305
354
  method: "POST",
306
355
  redirect: "error",
307
356
  signal: AbortSignal.timeout(10_000),
@@ -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, on Node or in the browser. No dependencies: Node signs and seals with `node:crypto`, and browser bundles get a built-in TypeScript implementation of the same functions (see [Browsers and bundlers](#browsers-and-bundlers)). 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,14 +48,32 @@ 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 expiringUpload = 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.
55
71
 
72
+ The builders throw on operations or a source that can never verify: `?`, `#`, whitespace, control and non-ASCII characters, and `"` `<` `>` `\` `^` `` ` `` `{` `|` `}`, which a browser rewrites before an `<img src>` or `fetch()` request leaves the page (`\` becomes `/`, the rest are percent-encoded). Percent-encode those in the source first (`x{y}.jpg` as `x%7By%7D.jpg`); the error names the encoding. The full rules are in [`spec/url-signing.md`](../../spec/url-signing.md#building-urls).
73
+
56
74
  ## Typed operations
57
75
 
58
- The operation string is the spec, and passing it verbatim stays the primary API. For callers who would rather build it, `ops` and `filter` are typed builders that validate each argument against the server's grammar and return the canonical spelling, so the typed and hand-written forms sign byte-identical URLs (the test suite pins this against the canonical corpus):
76
+ The operation string is the spec, and passing it verbatim stays the primary API. For callers who would rather build it, `ops` and `filter` are typed builders that validate each argument against the server's grammar and return the canonical spelling, so the typed and hand-written forms sign byte-identical URLs (the test suite pins this against the canonical corpus). Numbers and names are canonical too: a decimal argument is spelled the way the server prints it, which for every parameter but the convolution kernel's 64-bit values is the shortest decimal that reads back as the same 32-bit float (`ops.focalPoint(0.1 + 0.2, 0.4, 2)` is `focalpoint:0.3x0.4:2`), and a class name is spelled trimmed (`ops.cropObjects(100, 100, [" person "])` is `crop:100x100:objects(person):1`). For example:
59
77
 
60
78
  ```ts
61
79
  import { buildURL, filter, joinOps, ops } from "@crabcrop/url";
@@ -68,14 +86,40 @@ const operations = joinOps(
68
86
  const url = buildURL("https://images.example.com", "your-secret", operations, "https://example.com/photo.jpg");
69
87
  ```
70
88
 
71
- A value the server would reject (`filter.quality(0)`, `filter.brighten(256)`, `ops.crop(0, 100)`) throws at build time instead of minting a URL that fails at the edge. The closed sets are exported as types (`ImageFormat`, `CropAlign`, `Anchor`, `BlendMode`, `MaskShape`, `Dimension`), and `FILTER_DESCRIPTIONS` is the filter metadata table the explainer uses.
89
+ A value the server would reject (`filter.quality(0)`, `filter.brighten(256)`, `ops.crop(0, 100)`) throws at build time instead of minting a URL that fails at the edge. The closed sets are exported as types (`ImageFormat`, `PerFormatQualityFormat`, `CropAlign`, `Anchor`, `BlendMode`, `MaskShape`, `CurveChannel`, `StudioMode`, `StudioShadow`, `Dimension`), and so are the option objects (`FormatOptions` for `filter.format`, `StudioOptions` for `filter.studio`). `MAX_DIMENSION` is the server's per-axis pixel cap, 16383. The size, box, region, border, radius, and pixelate builders check against it (source coordinates, as in `ops.cropRect` and `ops.focal`, are not capped), and the [framework integrations](../../frameworks) import it for their own checks. `FILTER_DESCRIPTIONS` is the filter metadata table the explainer uses.
90
+
91
+ ```ts
92
+ import { filter, MAX_DIMENSION, ops, type FormatOptions } from "@crabcrop/url";
93
+
94
+ const jpeg: FormatOptions = { progressive: true, subsampling: 420 };
95
+ filter.format("jpeg", jpeg); // "format(jpeg,progressive,subsampling:420)"
96
+ ops.size(Math.min(requestedWidth, MAX_DIMENSION), 0); // clamp rather than throw
97
+ ```
98
+
99
+ ## Browsers and bundlers
100
+
101
+ The package imports its crypto through one internal specifier, `#crypto`, which `package.json` maps by condition:
102
+
103
+ | Condition | Backend | Who resolves it |
104
+ |---|---|---|
105
+ | `browser` | `dist/crypto/portable.js`: SHA-256, HMAC-SHA-256, and AES-256-GCM in plain TypeScript | client builds from bundlers that read `imports` conditions (Vite, webpack 5, esbuild, Rollup) |
106
+ | `node` | `dist/crypto/node.js`: `node:crypto` (OpenSSL) | Node, and server builds that target it |
107
+ | `default` | the portable backend | any other runtime, such as an edge worker without Node compatibility |
108
+
109
+ The rest of the package uses no Node globals (no `Buffer`, no `process`), so a client bundle never pulls in a Node built-in. Every function stays synchronous on both backends; WebCrypto's `crypto.subtle` is asynchronous and could not keep the API as it is. Both backends produce identical bytes: the test suite checks the portable one against `node:crypto` on thousands of random inputs and runs every spec vector on each, and [`tests/browser-bundles`](../../tests/browser-bundles) builds the framework integrations with Vite and runs the bundles without Node globals.
110
+
111
+ The portable backend is slower: about 5 µs per signature against about 2 µs on `node:crypto` (Node 22), and about a quarter of a millisecond to seal a 2 KB remainder, the largest allowed. Sealing needs `crypto.getRandomValues`, which every browser and edge runtime provides. Its AES rounds index the S-box by key-dependent bytes, which a cache-timing observer could in principle measure; Node keeps OpenSSL for that reason as well as speed.
112
+
113
+ A secret in browser code is public: anyone who loads the page can read it. The browser build exists so that client code can import the package at all: to build unsigned and preset URLs, explain URLs, and sign where the secret belongs to the person using the page (a playground-style tool). Sign with a deployment secret only in server code; the [framework integrations](../../frameworks) never sign in the browser.
72
114
 
73
115
  ## Runtime
74
116
 
75
- The package is TypeScript and runs directly on Node >= 22 (type stripping), which is also how the tests run:
117
+ The published package is compiled JavaScript (`dist/`) for Node >= 22. The sources are TypeScript and run directly on Node 22.18 or newer (or 23.6 or newer), where type stripping is on by default, which is also how the tests run:
76
118
 
77
119
  ```bash
78
- node --test
120
+ npm test
79
121
  ```
80
122
 
81
- In this repository the framework loaders and the MCP server resolve `@crabcrop/url` to these sources; a standalone install comes from npm once published, or from the repository with `"@crabcrop/url": "file:../typescript"` as the MCP package in this repo does.
123
+ `npm test` builds `dist/` first (the `#crypto` import resolves there) and type-checks [`test/exports.test.ts`](test/exports.test.ts), which imports the package by its own name, against the built declarations, so a type missing from the public index fails here. It then runs the suite twice: on `node:crypto`, and again under `--conditions=browser` on the portable backend.
124
+
125
+ In this repository the framework loaders and the MCP server resolve `@crabcrop/url` to these sources, so build the package once (`npm run build`) before running their tests; a standalone install comes from npm once published, or from the repository with `"@crabcrop/url": "file:../typescript"` as the MCP package in this repo does.
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Byte encodings the SDK needs, without Node's `Buffer`, so
3
+ * the same code runs in browsers: UTF-8 through the
4
+ * TextEncoder and TextDecoder globals, hex, and unpadded
5
+ * base64url.
6
+ */
7
+ /** The UTF-8 bytes of `text` (lone surrogates become U+FFFD, as in Node). */
8
+ export declare function utf8(text: string): Uint8Array;
9
+ /** Decode UTF-8, or null when the bytes are not valid UTF-8. */
10
+ export declare function utf8Strict(bytes: Uint8Array): string | null;
11
+ /** Lowercase hex. */
12
+ export declare function toHex(bytes: Uint8Array): string;
13
+ /** Unpadded base64url (RFC 4648 section 5). */
14
+ export declare function toBase64Url(bytes: Uint8Array): string;
15
+ /**
16
+ * Decode unpadded base64url, or null on any character outside
17
+ * the alphabet (padding included) or an impossible length.
18
+ * Callers that need the canonical spelling compare the input
19
+ * with `toBase64Url` of the result.
20
+ */
21
+ export declare function fromBase64Url(text: string): Uint8Array | null;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Byte encodings the SDK needs, without Node's `Buffer`, so
3
+ * the same code runs in browsers: UTF-8 through the
4
+ * TextEncoder and TextDecoder globals, hex, and unpadded
5
+ * base64url.
6
+ */
7
+ const encoder = new TextEncoder();
8
+ // fatal: invalid UTF-8 is an error, not U+FFFD. ignoreBOM:
9
+ // a leading U+FEFF is text like any other, kept as decoded.
10
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
11
+ /** The UTF-8 bytes of `text` (lone surrogates become U+FFFD, as in Node). */
12
+ export function utf8(text) {
13
+ return encoder.encode(text);
14
+ }
15
+ /** Decode UTF-8, or null when the bytes are not valid UTF-8. */
16
+ export function utf8Strict(bytes) {
17
+ try {
18
+ return decoder.decode(bytes);
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
24
+ const HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
25
+ /** Lowercase hex. */
26
+ export function toHex(bytes) {
27
+ let out = "";
28
+ for (let i = 0; i < bytes.length; i++) {
29
+ out += HEX[bytes[i]];
30
+ }
31
+ return out;
32
+ }
33
+ const B64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
34
+ // Character code to sextet, -1 outside the alphabet.
35
+ const B64URL_INDEX = new Int8Array(128).fill(-1);
36
+ for (let i = 0; i < B64URL.length; i++) {
37
+ B64URL_INDEX[B64URL.charCodeAt(i)] = i;
38
+ }
39
+ /** Unpadded base64url (RFC 4648 section 5). */
40
+ export function toBase64Url(bytes) {
41
+ let out = "";
42
+ let i = 0;
43
+ for (; i + 3 <= bytes.length; i += 3) {
44
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
45
+ out += B64URL[n >>> 18] + B64URL[(n >>> 12) & 63] + B64URL[(n >>> 6) & 63] + B64URL[n & 63];
46
+ }
47
+ const rest = bytes.length - i;
48
+ if (rest === 1) {
49
+ const n = bytes[i] << 16;
50
+ out += B64URL[n >>> 18] + B64URL[(n >>> 12) & 63];
51
+ }
52
+ else if (rest === 2) {
53
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8);
54
+ out += B64URL[n >>> 18] + B64URL[(n >>> 12) & 63] + B64URL[(n >>> 6) & 63];
55
+ }
56
+ return out;
57
+ }
58
+ /**
59
+ * Decode unpadded base64url, or null on any character outside
60
+ * the alphabet (padding included) or an impossible length.
61
+ * Callers that need the canonical spelling compare the input
62
+ * with `toBase64Url` of the result.
63
+ */
64
+ export function fromBase64Url(text) {
65
+ if (text.length % 4 === 1) {
66
+ return null;
67
+ }
68
+ const out = new Uint8Array(Math.floor((text.length * 3) / 4));
69
+ let bits = 0;
70
+ let acc = 0;
71
+ let o = 0;
72
+ for (let i = 0; i < text.length; i++) {
73
+ const code = text.charCodeAt(i);
74
+ const v = code < 128 ? B64URL_INDEX[code] : -1;
75
+ if (v < 0) {
76
+ return null;
77
+ }
78
+ acc = ((acc << 6) | v) & 0xffffff;
79
+ bits += 6;
80
+ if (bits >= 8) {
81
+ bits -= 8;
82
+ out[o++] = (acc >>> bits) & 0xff;
83
+ }
84
+ }
85
+ return out;
86
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * AES-256 (FIPS 197) in GCM mode (NIST SP 800-38D) with a
3
+ * 96-bit nonce and a 128-bit tag, in plain TypeScript, for
4
+ * runtimes without `node:crypto`. Like SHA-256 here, it backs
5
+ * synchronous functions (`seal`, `unseal`), which WebCrypto's
6
+ * asynchronous `subtle.encrypt` cannot.
7
+ *
8
+ * GHASH is computed with masks rather than branches. The AES
9
+ * rounds index the S-box by key-dependent bytes, so they are
10
+ * not hardened against cache-timing observers; Node keeps
11
+ * OpenSSL through the package's `node` condition, and this
12
+ * implementation serves the browser and edge builds.
13
+ */
14
+ /** AES-256-GCM encryption: returns ciphertext || 16-byte tag. */
15
+ export declare function aes256GcmSeal(key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, plaintext: Uint8Array): Uint8Array;
16
+ /**
17
+ * AES-256-GCM decryption of ciphertext || tag. Returns the
18
+ * plaintext, or null when the tag does not verify; nothing is
19
+ * decrypted before the tag is checked.
20
+ */
21
+ export declare function aes256GcmOpen(key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, sealed: Uint8Array): Uint8Array | null;