@crabcrop/mcp 0.9.11 → 0.10.1
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 +12 -5
- package/dist/index.js +75 -34
- package/node_modules/@crabcrop/url/README.md +35 -7
- package/node_modules/@crabcrop/url/dist/bytes.d.ts +21 -0
- package/node_modules/@crabcrop/url/dist/bytes.js +86 -0
- package/node_modules/@crabcrop/url/dist/crypto/aes-gcm.d.ts +21 -0
- package/node_modules/@crabcrop/url/dist/crypto/aes-gcm.js +248 -0
- package/node_modules/@crabcrop/url/dist/crypto/node.d.ts +11 -0
- package/node_modules/@crabcrop/url/dist/crypto/node.js +41 -0
- package/node_modules/@crabcrop/url/dist/crypto/portable.d.ts +14 -0
- package/node_modules/@crabcrop/url/dist/crypto/portable.js +60 -0
- package/node_modules/@crabcrop/url/dist/crypto/sha256.d.ts +14 -0
- package/node_modules/@crabcrop/url/dist/crypto/sha256.js +131 -0
- package/node_modules/@crabcrop/url/dist/explain.d.ts +55 -7
- package/node_modules/@crabcrop/url/dist/explain.js +116 -65
- package/node_modules/@crabcrop/url/dist/index.d.ts +2 -1
- package/node_modules/@crabcrop/url/dist/index.js +60 -50
- package/node_modules/@crabcrop/url/dist/limits.d.ts +9 -0
- package/node_modules/@crabcrop/url/dist/limits.js +9 -0
- package/node_modules/@crabcrop/url/dist/operations.d.ts +8 -20
- package/node_modules/@crabcrop/url/dist/operations.js +133 -71
- package/node_modules/@crabcrop/url/package.json +11 -3
- package/package.json +1 -1
- package/server.json +1 -1
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
|
|
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
|
|
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
|
|
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`
|
|
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.
|
|
22
|
+
const SERVER = { name: "crabcrop", version: "0.10.1" };
|
|
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,
|
|
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: {
|
|
@@ -252,45 +288,40 @@ const TOOLS = [
|
|
|
252
288
|
"URL's remainder after its signature (operations and source; a preset " +
|
|
253
289
|
"URL works as-is, the server expands it). Requires the signing secret (argument or " +
|
|
254
290
|
"CRABCROP_SECRET). Returns how many entries were removed. " +
|
|
255
|
-
"For safety the request only goes to the configured
|
|
256
|
-
"
|
|
257
|
-
"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.",
|
|
258
294
|
inputSchema: {
|
|
259
295
|
type: "object",
|
|
260
296
|
properties: {
|
|
261
297
|
path: { type: "string", description: "Remainder of the cached URL, e.g. \"300x200/https://example.com/a.jpg\"." },
|
|
262
|
-
base: { type: "string", description: "
|
|
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." },
|
|
263
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." },
|
|
264
300
|
},
|
|
265
301
|
required: ["path"],
|
|
266
302
|
additionalProperties: false,
|
|
267
303
|
},
|
|
268
304
|
async run(args) {
|
|
269
|
-
// The
|
|
270
|
-
//
|
|
271
|
-
//
|
|
272
|
-
//
|
|
273
|
-
//
|
|
274
|
-
//
|
|
275
|
-
//
|
|
276
|
-
//
|
|
277
|
-
//
|
|
278
|
-
//
|
|
279
|
-
//
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
const base = (optionalStringArg(args, "base") ?? envBase).replace(/\/+$/, "");
|
|
285
|
-
let baseOrigin;
|
|
286
|
-
try {
|
|
287
|
-
baseOrigin = new URL(base).origin;
|
|
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);
|
|
288
320
|
}
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
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);
|
|
294
325
|
}
|
|
295
326
|
const secret = optionalStringArg(args, "secret") ?? envSecret;
|
|
296
327
|
if (!secret)
|
|
@@ -303,13 +334,23 @@ const TOOLS = [
|
|
|
303
334
|
// domain-separated from image signatures (audit P-1),
|
|
304
335
|
// and the derivation lives in exactly one place.
|
|
305
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
|
+
}
|
|
306
347
|
// The same network hygiene as fetch_meta: no
|
|
307
348
|
// redirects, a bounded wait, and a capped body, so a
|
|
308
349
|
// hung or hostile endpoint cannot hang the tool call
|
|
309
350
|
// or stream an unbounded response.
|
|
310
351
|
let resp;
|
|
311
352
|
try {
|
|
312
|
-
resp = await fetch(
|
|
353
|
+
resp = await fetch(url, {
|
|
313
354
|
method: "POST",
|
|
314
355
|
redirect: "error",
|
|
315
356
|
signal: AbortSignal.timeout(10_000),
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @crabcrop/url
|
|
2
2
|
|
|
3
|
-
Build and sign [crabcrop](https://github.com/dayvson/crabcrop) URLs from TypeScript or JavaScript.
|
|
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
|
|
|
@@ -51,7 +51,7 @@ const group = purgeGroupSignature("your-secret", "thumb");
|
|
|
51
51
|
// Pass an expiry (unix seconds) for a token that stops working
|
|
52
52
|
// then; its path is /upload/<signature>/exp:<expiry>/<name>.
|
|
53
53
|
const upload = uploadSignature("your-secret", "heroes/photo.jpg");
|
|
54
|
-
const
|
|
54
|
+
const expiringUpload = uploadSignature("your-secret", "heroes/photo.jpg", 1893456000);
|
|
55
55
|
|
|
56
56
|
// Sealed URLs (issue #255): the whole remainder encrypted into an
|
|
57
57
|
// opaque token in the signature slot, for public links whose recipe
|
|
@@ -69,9 +69,11 @@ const remainder = unseal("your-secret", seal("your-secret", "300x200/https://exa
|
|
|
69
69
|
|
|
70
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.
|
|
71
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
|
+
|
|
72
74
|
## Typed operations
|
|
73
75
|
|
|
74
|
-
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:
|
|
75
77
|
|
|
76
78
|
```ts
|
|
77
79
|
import { buildURL, filter, joinOps, ops } from "@crabcrop/url";
|
|
@@ -84,14 +86,40 @@ const operations = joinOps(
|
|
|
84
86
|
const url = buildURL("https://images.example.com", "your-secret", operations, "https://example.com/photo.jpg");
|
|
85
87
|
```
|
|
86
88
|
|
|
87
|
-
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.
|
|
88
114
|
|
|
89
115
|
## Runtime
|
|
90
116
|
|
|
91
|
-
The package is TypeScript and
|
|
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:
|
|
92
118
|
|
|
93
119
|
```bash
|
|
94
|
-
|
|
120
|
+
npm test
|
|
95
121
|
```
|
|
96
122
|
|
|
97
|
-
|
|
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;
|