@crabcrop/url 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 +35 -7
- package/dist/bytes.d.ts +21 -0
- package/dist/bytes.js +86 -0
- package/dist/crypto/aes-gcm.d.ts +21 -0
- package/dist/crypto/aes-gcm.js +248 -0
- package/dist/crypto/node.d.ts +11 -0
- package/dist/crypto/node.js +41 -0
- package/dist/crypto/portable.d.ts +14 -0
- package/dist/crypto/portable.js +60 -0
- package/dist/crypto/sha256.d.ts +14 -0
- package/dist/crypto/sha256.js +131 -0
- package/dist/explain.d.ts +55 -7
- package/dist/explain.js +116 -65
- package/dist/index.d.ts +2 -1
- package/dist/index.js +60 -50
- package/dist/limits.d.ts +9 -0
- package/dist/limits.js +9 -0
- package/dist/operations.d.ts +8 -20
- package/dist/operations.js +133 -71
- package/package.json +11 -3
package/README.md
CHANGED
|
@@ -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.
|
package/dist/bytes.d.ts
ADDED
|
@@ -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;
|
package/dist/bytes.js
ADDED
|
@@ -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;
|
|
@@ -0,0 +1,248 @@
|
|
|
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
|
+
const SBOX = new Uint8Array(256);
|
|
15
|
+
{
|
|
16
|
+
// The S-box is the multiplicative inverse in GF(2^8)
|
|
17
|
+
// followed by the FIPS 197 affine map. Walk p over the
|
|
18
|
+
// powers of the generator 3 while q walks the matching
|
|
19
|
+
// inverses (powers of 3^-1), so sbox[p] = affine(q).
|
|
20
|
+
let p = 1;
|
|
21
|
+
let q = 1;
|
|
22
|
+
do {
|
|
23
|
+
p = p ^ ((p << 1) & 0xff) ^ (p & 0x80 ? 0x1b : 0);
|
|
24
|
+
q ^= q << 1;
|
|
25
|
+
q ^= q << 2;
|
|
26
|
+
q ^= q << 4;
|
|
27
|
+
q &= 0xff;
|
|
28
|
+
if (q & 0x80) {
|
|
29
|
+
q ^= 0x09;
|
|
30
|
+
}
|
|
31
|
+
const rotl = (x, n) => ((x << n) | (x >>> (8 - n))) & 0xff;
|
|
32
|
+
SBOX[p] = q ^ rotl(q, 1) ^ rotl(q, 2) ^ rotl(q, 3) ^ rotl(q, 4) ^ 0x63;
|
|
33
|
+
} while (p !== 1);
|
|
34
|
+
SBOX[0] = 0x63;
|
|
35
|
+
}
|
|
36
|
+
/** Multiply by x in GF(2^8), without a branch on the high bit. */
|
|
37
|
+
const xtime = (x) => ((x << 1) ^ ((x >>> 7) * 0x1b)) & 0xff;
|
|
38
|
+
const ROUNDS = 14;
|
|
39
|
+
/** The AES-256 key schedule: 15 round keys, 240 bytes. */
|
|
40
|
+
function expandKey(key) {
|
|
41
|
+
if (key.length !== 32) {
|
|
42
|
+
throw new Error(`AES-256 needs a 32-byte key, got ${key.length}`);
|
|
43
|
+
}
|
|
44
|
+
const w = new Uint8Array(16 * (ROUNDS + 1));
|
|
45
|
+
w.set(key);
|
|
46
|
+
let rcon = 1;
|
|
47
|
+
for (let i = 32; i < w.length; i += 4) {
|
|
48
|
+
let t0 = w[i - 4];
|
|
49
|
+
let t1 = w[i - 3];
|
|
50
|
+
let t2 = w[i - 2];
|
|
51
|
+
let t3 = w[i - 1];
|
|
52
|
+
if (i % 32 === 0) {
|
|
53
|
+
// RotWord, SubWord, and the round constant.
|
|
54
|
+
const first = t0;
|
|
55
|
+
t0 = SBOX[t1] ^ rcon;
|
|
56
|
+
t1 = SBOX[t2];
|
|
57
|
+
t2 = SBOX[t3];
|
|
58
|
+
t3 = SBOX[first];
|
|
59
|
+
rcon = xtime(rcon);
|
|
60
|
+
}
|
|
61
|
+
else if (i % 32 === 16) {
|
|
62
|
+
t0 = SBOX[t0];
|
|
63
|
+
t1 = SBOX[t1];
|
|
64
|
+
t2 = SBOX[t2];
|
|
65
|
+
t3 = SBOX[t3];
|
|
66
|
+
}
|
|
67
|
+
w[i] = w[i - 32] ^ t0;
|
|
68
|
+
w[i + 1] = w[i - 31] ^ t1;
|
|
69
|
+
w[i + 2] = w[i - 30] ^ t2;
|
|
70
|
+
w[i + 3] = w[i - 29] ^ t3;
|
|
71
|
+
}
|
|
72
|
+
return w;
|
|
73
|
+
}
|
|
74
|
+
/** Encrypt one 16-byte block from `input` into `output`. */
|
|
75
|
+
function encryptBlock(roundKeys, input, output) {
|
|
76
|
+
// The state is column-major: byte r of column c is s[r + 4c].
|
|
77
|
+
const s = new Uint8Array(16);
|
|
78
|
+
const t = new Uint8Array(16);
|
|
79
|
+
for (let i = 0; i < 16; i++) {
|
|
80
|
+
s[i] = input[i] ^ roundKeys[i];
|
|
81
|
+
}
|
|
82
|
+
for (let round = 1; round <= ROUNDS; round++) {
|
|
83
|
+
// SubBytes and ShiftRows: row r rotates left by r columns.
|
|
84
|
+
for (let c = 0; c < 4; c++) {
|
|
85
|
+
for (let r = 0; r < 4; r++) {
|
|
86
|
+
t[r + 4 * c] = SBOX[s[r + 4 * ((c + r) & 3)]];
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (round < ROUNDS) {
|
|
90
|
+
for (let c = 0; c < 16; c += 4) {
|
|
91
|
+
const a0 = t[c];
|
|
92
|
+
const a1 = t[c + 1];
|
|
93
|
+
const a2 = t[c + 2];
|
|
94
|
+
const a3 = t[c + 3];
|
|
95
|
+
const all = a0 ^ a1 ^ a2 ^ a3;
|
|
96
|
+
// MixColumns: b_i = a_i ^ all ^ 2·(a_i ^ a_{i+1}).
|
|
97
|
+
t[c] = a0 ^ all ^ xtime(a0 ^ a1);
|
|
98
|
+
t[c + 1] = a1 ^ all ^ xtime(a1 ^ a2);
|
|
99
|
+
t[c + 2] = a2 ^ all ^ xtime(a2 ^ a3);
|
|
100
|
+
t[c + 3] = a3 ^ all ^ xtime(a3 ^ a0);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const k = round * 16;
|
|
104
|
+
for (let i = 0; i < 16; i++) {
|
|
105
|
+
s[i] = t[i] ^ roundKeys[k + i];
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
output.set(s);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Multiply two GF(2^128) elements in GCM's bit order, each as
|
|
112
|
+
* four big-endian 32-bit words (SP 800-38D, Algorithm 1). The
|
|
113
|
+
* loop runs all 128 steps with masks, never a branch on a
|
|
114
|
+
* secret bit.
|
|
115
|
+
*/
|
|
116
|
+
function gmul(x, h) {
|
|
117
|
+
let z0 = 0;
|
|
118
|
+
let z1 = 0;
|
|
119
|
+
let z2 = 0;
|
|
120
|
+
let z3 = 0;
|
|
121
|
+
let v0 = h[0];
|
|
122
|
+
let v1 = h[1];
|
|
123
|
+
let v2 = h[2];
|
|
124
|
+
let v3 = h[3];
|
|
125
|
+
for (let i = 0; i < 128; i++) {
|
|
126
|
+
const bit = (x[i >>> 5] >>> (31 - (i & 31))) & 1;
|
|
127
|
+
const take = -bit;
|
|
128
|
+
z0 ^= v0 & take;
|
|
129
|
+
z1 ^= v1 & take;
|
|
130
|
+
z2 ^= v2 & take;
|
|
131
|
+
z3 ^= v3 & take;
|
|
132
|
+
const reduce = -(v3 & 1);
|
|
133
|
+
v3 = (v3 >>> 1) | (v2 << 31);
|
|
134
|
+
v2 = (v2 >>> 1) | (v1 << 31);
|
|
135
|
+
v1 = (v1 >>> 1) | (v0 << 31);
|
|
136
|
+
v0 = (v0 >>> 1) ^ (0xe1000000 & reduce);
|
|
137
|
+
}
|
|
138
|
+
x[0] = z0;
|
|
139
|
+
x[1] = z1;
|
|
140
|
+
x[2] = z2;
|
|
141
|
+
x[3] = z3;
|
|
142
|
+
}
|
|
143
|
+
function readWords(bytes) {
|
|
144
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, 16);
|
|
145
|
+
return Int32Array.of(view.getInt32(0), view.getInt32(4), view.getInt32(8), view.getInt32(12));
|
|
146
|
+
}
|
|
147
|
+
/** GHASH_H over the AAD and ciphertext, then their bit lengths. */
|
|
148
|
+
function ghash(h, aad, ciphertext) {
|
|
149
|
+
const hw = readWords(h);
|
|
150
|
+
const x = new Int32Array(4);
|
|
151
|
+
const block = new Uint8Array(16);
|
|
152
|
+
const absorb = (data) => {
|
|
153
|
+
for (let off = 0; off < data.length; off += 16) {
|
|
154
|
+
block.fill(0);
|
|
155
|
+
block.set(data.subarray(off, off + 16));
|
|
156
|
+
const bw = readWords(block);
|
|
157
|
+
for (let i = 0; i < 4; i++) {
|
|
158
|
+
x[i] ^= bw[i];
|
|
159
|
+
}
|
|
160
|
+
gmul(x, hw);
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
absorb(aad);
|
|
164
|
+
absorb(ciphertext);
|
|
165
|
+
const lengths = new DataView(block.buffer);
|
|
166
|
+
lengths.setUint32(0, Math.floor(aad.length / 0x20000000));
|
|
167
|
+
lengths.setUint32(4, (aad.length << 3) >>> 0);
|
|
168
|
+
lengths.setUint32(8, Math.floor(ciphertext.length / 0x20000000));
|
|
169
|
+
lengths.setUint32(12, (ciphertext.length << 3) >>> 0);
|
|
170
|
+
const lw = readWords(block);
|
|
171
|
+
for (let i = 0; i < 4; i++) {
|
|
172
|
+
x[i] ^= lw[i];
|
|
173
|
+
}
|
|
174
|
+
gmul(x, hw);
|
|
175
|
+
const out = new Uint8Array(16);
|
|
176
|
+
const outView = new DataView(out.buffer);
|
|
177
|
+
for (let i = 0; i < 4; i++) {
|
|
178
|
+
outView.setInt32(i * 4, x[i]);
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
/** CTR mode from inc32(J0), XORing `input` into `output`. */
|
|
183
|
+
function ctr(roundKeys, j0, input, output) {
|
|
184
|
+
const counter = j0.slice();
|
|
185
|
+
const view = new DataView(counter.buffer);
|
|
186
|
+
const stream = new Uint8Array(16);
|
|
187
|
+
for (let off = 0; off < input.length; off += 16) {
|
|
188
|
+
view.setUint32(12, (view.getUint32(12) + 1) >>> 0);
|
|
189
|
+
encryptBlock(roundKeys, counter, stream);
|
|
190
|
+
const end = Math.min(off + 16, input.length);
|
|
191
|
+
for (let i = off; i < end; i++) {
|
|
192
|
+
output[i] = input[i] ^ stream[i - off];
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function setup(key, nonce) {
|
|
197
|
+
if (nonce.length !== 12) {
|
|
198
|
+
throw new Error(`AES-GCM here takes a 12-byte nonce, got ${nonce.length}`);
|
|
199
|
+
}
|
|
200
|
+
const roundKeys = expandKey(key);
|
|
201
|
+
const h = new Uint8Array(16);
|
|
202
|
+
encryptBlock(roundKeys, new Uint8Array(16), h);
|
|
203
|
+
const j0 = new Uint8Array(16);
|
|
204
|
+
j0.set(nonce);
|
|
205
|
+
j0[15] = 1;
|
|
206
|
+
return { roundKeys, h, j0 };
|
|
207
|
+
}
|
|
208
|
+
/** The tag: E(K, J0) XOR GHASH(A, C). */
|
|
209
|
+
function tagFor(g, aad, ciphertext) {
|
|
210
|
+
const tag = ghash(g.h, aad, ciphertext);
|
|
211
|
+
const mask = new Uint8Array(16);
|
|
212
|
+
encryptBlock(g.roundKeys, g.j0, mask);
|
|
213
|
+
for (let i = 0; i < 16; i++) {
|
|
214
|
+
tag[i] ^= mask[i];
|
|
215
|
+
}
|
|
216
|
+
return tag;
|
|
217
|
+
}
|
|
218
|
+
/** AES-256-GCM encryption: returns ciphertext || 16-byte tag. */
|
|
219
|
+
export function aes256GcmSeal(key, nonce, aad, plaintext) {
|
|
220
|
+
const g = setup(key, nonce);
|
|
221
|
+
const out = new Uint8Array(plaintext.length + 16);
|
|
222
|
+
ctr(g.roundKeys, g.j0, plaintext, out);
|
|
223
|
+
out.set(tagFor(g, aad, out.subarray(0, plaintext.length)), plaintext.length);
|
|
224
|
+
return out;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* AES-256-GCM decryption of ciphertext || tag. Returns the
|
|
228
|
+
* plaintext, or null when the tag does not verify; nothing is
|
|
229
|
+
* decrypted before the tag is checked.
|
|
230
|
+
*/
|
|
231
|
+
export function aes256GcmOpen(key, nonce, aad, sealed) {
|
|
232
|
+
if (sealed.length < 16) {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
const g = setup(key, nonce);
|
|
236
|
+
const ciphertext = sealed.subarray(0, sealed.length - 16);
|
|
237
|
+
const expected = tagFor(g, aad, ciphertext);
|
|
238
|
+
let diff = 0;
|
|
239
|
+
for (let i = 0; i < 16; i++) {
|
|
240
|
+
diff |= expected[i] ^ sealed[ciphertext.length + i];
|
|
241
|
+
}
|
|
242
|
+
if (diff !== 0) {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
const plaintext = new Uint8Array(ciphertext.length);
|
|
246
|
+
ctr(g.roundKeys, g.j0, ciphertext, plaintext);
|
|
247
|
+
return plaintext;
|
|
248
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const backend = "node";
|
|
2
|
+
/** HMAC-SHA-256 of the UTF-8 `message` under `key`. */
|
|
3
|
+
export declare function hmacSha256(key: string | Uint8Array, message: string): Uint8Array;
|
|
4
|
+
/** AES-256-GCM: ciphertext || 16-byte tag. */
|
|
5
|
+
export declare function aes256GcmSeal(key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, plaintext: Uint8Array): Uint8Array;
|
|
6
|
+
/** AES-256-GCM: the plaintext, or null when the tag does not verify. */
|
|
7
|
+
export declare function aes256GcmOpen(key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, sealed: Uint8Array): Uint8Array | null;
|
|
8
|
+
/** `n` bytes from OpenSSL's CSPRNG. */
|
|
9
|
+
export declare function randomBytes(n: number): Uint8Array;
|
|
10
|
+
/** Constant-time equality of two byte strings of equal length. */
|
|
11
|
+
export declare function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Node crypto backend: OpenSSL through `node:crypto`.
|
|
3
|
+
* Package resolution picks it through the `#crypto` import's
|
|
4
|
+
* `node` condition; bundles for browsers take `./portable.ts`,
|
|
5
|
+
* which exports the same functions.
|
|
6
|
+
*/
|
|
7
|
+
import { createCipheriv, createDecipheriv, createHmac, randomBytes as nodeRandomBytes, timingSafeEqual as nodeTimingSafeEqual, } from "node:crypto";
|
|
8
|
+
export const backend = "node";
|
|
9
|
+
/** HMAC-SHA-256 of the UTF-8 `message` under `key`. */
|
|
10
|
+
export function hmacSha256(key, message) {
|
|
11
|
+
return createHmac("sha256", key).update(message, "utf8").digest();
|
|
12
|
+
}
|
|
13
|
+
/** AES-256-GCM: ciphertext || 16-byte tag. */
|
|
14
|
+
export function aes256GcmSeal(key, nonce, aad, plaintext) {
|
|
15
|
+
const cipher = createCipheriv("aes-256-gcm", key, nonce);
|
|
16
|
+
cipher.setAAD(aad);
|
|
17
|
+
return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
|
|
18
|
+
}
|
|
19
|
+
/** AES-256-GCM: the plaintext, or null when the tag does not verify. */
|
|
20
|
+
export function aes256GcmOpen(key, nonce, aad, sealed) {
|
|
21
|
+
if (sealed.length < 16) {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
const decipher = createDecipheriv("aes-256-gcm", key, nonce);
|
|
25
|
+
decipher.setAAD(aad);
|
|
26
|
+
decipher.setAuthTag(sealed.subarray(sealed.length - 16));
|
|
27
|
+
try {
|
|
28
|
+
return Buffer.concat([decipher.update(sealed.subarray(0, sealed.length - 16)), decipher.final()]);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** `n` bytes from OpenSSL's CSPRNG. */
|
|
35
|
+
export function randomBytes(n) {
|
|
36
|
+
return nodeRandomBytes(n);
|
|
37
|
+
}
|
|
38
|
+
/** Constant-time equality of two byte strings of equal length. */
|
|
39
|
+
export function timingSafeEqual(a, b) {
|
|
40
|
+
return a.length === b.length && nodeTimingSafeEqual(a, b);
|
|
41
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare const backend = "portable";
|
|
2
|
+
/**
|
|
3
|
+
* HMAC-SHA-256 of the UTF-8 `message` under `key` (a string
|
|
4
|
+
* is UTF-8 encoded, as `node:crypto` does).
|
|
5
|
+
*/
|
|
6
|
+
export declare function hmacSha256(key: string | Uint8Array, message: string): Uint8Array;
|
|
7
|
+
/** AES-256-GCM: ciphertext || 16-byte tag. */
|
|
8
|
+
export declare function aes256GcmSeal(key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, plaintext: Uint8Array): Uint8Array;
|
|
9
|
+
/** AES-256-GCM: the plaintext, or null when the tag does not verify. */
|
|
10
|
+
export declare function aes256GcmOpen(key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, sealed: Uint8Array): Uint8Array | null;
|
|
11
|
+
/** `n` bytes from the platform's CSPRNG (`crypto.getRandomValues`). */
|
|
12
|
+
export declare function randomBytes(n: number): Uint8Array;
|
|
13
|
+
/** Constant-time equality of two byte strings of equal length. */
|
|
14
|
+
export declare function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The portable crypto backend: plain TypeScript, no Node
|
|
3
|
+
* built-ins. Package resolution picks it through the
|
|
4
|
+
* `#crypto` import's `browser` and `default` conditions, so
|
|
5
|
+
* browser bundles (Vite, webpack, esbuild) and edge runtimes
|
|
6
|
+
* get a working, synchronous SDK; Node takes `./node.ts`.
|
|
7
|
+
* Both modules export the same functions with the same
|
|
8
|
+
* results, which the test suite checks against `node:crypto`.
|
|
9
|
+
*/
|
|
10
|
+
import { aes256GcmOpen as open, aes256GcmSeal as seal } from "./aes-gcm.js";
|
|
11
|
+
import { hmacSha256 as hmac } from "./sha256.js";
|
|
12
|
+
export const backend = "portable";
|
|
13
|
+
const encoder = new TextEncoder();
|
|
14
|
+
/**
|
|
15
|
+
* HMAC-SHA-256 of the UTF-8 `message` under `key` (a string
|
|
16
|
+
* is UTF-8 encoded, as `node:crypto` does).
|
|
17
|
+
*/
|
|
18
|
+
export function hmacSha256(key, message) {
|
|
19
|
+
let keyBytes;
|
|
20
|
+
if (typeof key === "string") {
|
|
21
|
+
keyBytes = encoder.encode(key);
|
|
22
|
+
}
|
|
23
|
+
else if (key instanceof Uint8Array) {
|
|
24
|
+
keyBytes = key;
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
// node:crypto refuses a missing or non-string key the
|
|
28
|
+
// same way, rather than signing with "undefined".
|
|
29
|
+
throw new TypeError(`the HMAC key must be a string or a Uint8Array, got ${typeof key}`);
|
|
30
|
+
}
|
|
31
|
+
return hmac(keyBytes, encoder.encode(message));
|
|
32
|
+
}
|
|
33
|
+
/** AES-256-GCM: ciphertext || 16-byte tag. */
|
|
34
|
+
export function aes256GcmSeal(key, nonce, aad, plaintext) {
|
|
35
|
+
return seal(key, nonce, aad, plaintext);
|
|
36
|
+
}
|
|
37
|
+
/** AES-256-GCM: the plaintext, or null when the tag does not verify. */
|
|
38
|
+
export function aes256GcmOpen(key, nonce, aad, sealed) {
|
|
39
|
+
return open(key, nonce, aad, sealed);
|
|
40
|
+
}
|
|
41
|
+
/** `n` bytes from the platform's CSPRNG (`crypto.getRandomValues`). */
|
|
42
|
+
export function randomBytes(n) {
|
|
43
|
+
const source = globalThis
|
|
44
|
+
.crypto;
|
|
45
|
+
if (typeof source?.getRandomValues !== "function") {
|
|
46
|
+
throw new Error("no secure random source: crypto.getRandomValues is unavailable here");
|
|
47
|
+
}
|
|
48
|
+
return source.getRandomValues(new Uint8Array(n));
|
|
49
|
+
}
|
|
50
|
+
/** Constant-time equality of two byte strings of equal length. */
|
|
51
|
+
export function timingSafeEqual(a, b) {
|
|
52
|
+
if (a.length !== b.length) {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
let diff = 0;
|
|
56
|
+
for (let i = 0; i < a.length; i++) {
|
|
57
|
+
diff |= a[i] ^ b[i];
|
|
58
|
+
}
|
|
59
|
+
return diff === 0;
|
|
60
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SHA-256 (FIPS 180-4) and HMAC-SHA-256 (RFC 2104) in plain
|
|
3
|
+
* TypeScript, for runtimes without `node:crypto`. WebCrypto
|
|
4
|
+
* cannot stand in: `crypto.subtle` is asynchronous, and the
|
|
5
|
+
* SDK's signing functions are synchronous.
|
|
6
|
+
*
|
|
7
|
+
* All arithmetic is on 32-bit words with no data-dependent
|
|
8
|
+
* branches or table indices, so the time taken depends only
|
|
9
|
+
* on the input lengths.
|
|
10
|
+
*/
|
|
11
|
+
/** The SHA-256 digest of `data`. */
|
|
12
|
+
export declare function sha256(data: Uint8Array): Uint8Array;
|
|
13
|
+
/** HMAC-SHA-256 of `message` under `key` (RFC 2104). */
|
|
14
|
+
export declare function hmacSha256(key: Uint8Array, message: Uint8Array): Uint8Array;
|