@strimz/shared-crypto 0.1.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/LICENSE +21 -0
- package/README.md +57 -0
- package/dist/aes-gcm.cjs +94 -0
- package/dist/aes-gcm.cjs.map +1 -0
- package/dist/aes-gcm.d.cts +59 -0
- package/dist/aes-gcm.d.ts +59 -0
- package/dist/aes-gcm.js +90 -0
- package/dist/aes-gcm.js.map +1 -0
- package/dist/api-key.cjs +95 -0
- package/dist/api-key.cjs.map +1 -0
- package/dist/api-key.d.cts +32 -0
- package/dist/api-key.d.ts +32 -0
- package/dist/api-key.js +91 -0
- package/dist/api-key.js.map +1 -0
- package/dist/encoding.cjs +49 -0
- package/dist/encoding.cjs.map +1 -0
- package/dist/encoding.d.cts +12 -0
- package/dist/encoding.d.ts +12 -0
- package/dist/encoding.js +43 -0
- package/dist/encoding.js.map +1 -0
- package/dist/hash.cjs +38 -0
- package/dist/hash.cjs.map +1 -0
- package/dist/hash.d.cts +7 -0
- package/dist/hash.d.ts +7 -0
- package/dist/hash.js +35 -0
- package/dist/hash.js.map +1 -0
- package/dist/hmac.cjs +47 -0
- package/dist/hmac.cjs.map +1 -0
- package/dist/hmac.d.cts +8 -0
- package/dist/hmac.d.ts +8 -0
- package/dist/hmac.js +44 -0
- package/dist/hmac.js.map +1 -0
- package/dist/index.cjs +296 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +271 -0
- package/dist/index.js.map +1 -0
- package/dist/random.cjs +61 -0
- package/dist/random.cjs.map +1 -0
- package/dist/random.d.cts +10 -0
- package/dist/random.d.ts +10 -0
- package/dist/random.js +56 -0
- package/dist/random.js.map +1 -0
- package/dist/timing-safe.cjs +24 -0
- package/dist/timing-safe.cjs.map +1 -0
- package/dist/timing-safe.d.cts +14 -0
- package/dist/timing-safe.d.ts +14 -0
- package/dist/timing-safe.js +21 -0
- package/dist/timing-safe.js.map +1 -0
- package/dist/webhook.cjs +123 -0
- package/dist/webhook.cjs.map +1 -0
- package/dist/webhook.d.cts +31 -0
- package/dist/webhook.d.ts +31 -0
- package/dist/webhook.js +119 -0
- package/dist/webhook.js.map +1 -0
- package/package.json +105 -0
- package/src/aes-gcm.test.ts +72 -0
- package/src/aes-gcm.ts +119 -0
- package/src/api-key.test.ts +59 -0
- package/src/api-key.ts +61 -0
- package/src/encoding.test.ts +49 -0
- package/src/encoding.ts +51 -0
- package/src/hash.test.ts +29 -0
- package/src/hash.ts +23 -0
- package/src/hmac.test.ts +28 -0
- package/src/hmac.ts +40 -0
- package/src/index.ts +15 -0
- package/src/random.test.ts +45 -0
- package/src/random.ts +44 -0
- package/src/timing-safe.test.ts +38 -0
- package/src/timing-safe.ts +28 -0
- package/src/webhook.test.ts +78 -0
- package/src/webhook.ts +106 -0
package/dist/webhook.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { WEBHOOK_SIGNATURE_TOLERANCE_SECONDS } from '@strimz/shared-config/webhooks';
|
|
2
|
+
|
|
3
|
+
// src/webhook.ts
|
|
4
|
+
|
|
5
|
+
// src/encoding.ts
|
|
6
|
+
var HEX_CHARS = "0123456789abcdef";
|
|
7
|
+
function toHex(bytes) {
|
|
8
|
+
let out = "";
|
|
9
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
10
|
+
const b = bytes[i];
|
|
11
|
+
out += HEX_CHARS[b >>> 4];
|
|
12
|
+
out += HEX_CHARS[b & 15];
|
|
13
|
+
}
|
|
14
|
+
return out;
|
|
15
|
+
}
|
|
16
|
+
function fromHex(hex) {
|
|
17
|
+
const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
|
|
18
|
+
if (clean.length % 2 !== 0) {
|
|
19
|
+
throw new Error("fromHex: odd-length hex input");
|
|
20
|
+
}
|
|
21
|
+
const out = new Uint8Array(clean.length / 2);
|
|
22
|
+
for (let i = 0; i < out.length; i++) {
|
|
23
|
+
const byte = Number.parseInt(clean.substr(i * 2, 2), 16);
|
|
24
|
+
if (Number.isNaN(byte)) {
|
|
25
|
+
throw new Error("fromHex: non-hex character");
|
|
26
|
+
}
|
|
27
|
+
out[i] = byte;
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
function utf8ToBytes(str) {
|
|
32
|
+
return new TextEncoder().encode(str);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// src/hmac.ts
|
|
36
|
+
async function hmacSha256(key, message) {
|
|
37
|
+
const keyBytes = typeof key === "string" ? utf8ToBytes(key) : key;
|
|
38
|
+
const msgBytes = typeof message === "string" ? utf8ToBytes(message) : message;
|
|
39
|
+
const subtle = requireSubtle();
|
|
40
|
+
const cryptoKey = await subtle.importKey(
|
|
41
|
+
"raw",
|
|
42
|
+
keyBytes,
|
|
43
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
44
|
+
false,
|
|
45
|
+
["sign"]
|
|
46
|
+
);
|
|
47
|
+
const signature = await subtle.sign("HMAC", cryptoKey, msgBytes);
|
|
48
|
+
return new Uint8Array(signature);
|
|
49
|
+
}
|
|
50
|
+
function requireSubtle() {
|
|
51
|
+
const c = globalThis.crypto;
|
|
52
|
+
if (!c || !c.subtle) {
|
|
53
|
+
throw new Error("Web Crypto is not available in this runtime");
|
|
54
|
+
}
|
|
55
|
+
return c.subtle;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/timing-safe.ts
|
|
59
|
+
function timingSafeEqualBytes(a, b) {
|
|
60
|
+
if (a.length !== b.length) return false;
|
|
61
|
+
let diff = 0;
|
|
62
|
+
for (let i = 0; i < a.length; i++) {
|
|
63
|
+
diff |= a[i] ^ b[i];
|
|
64
|
+
}
|
|
65
|
+
return diff === 0;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/webhook.ts
|
|
69
|
+
var WEBHOOK_SIGNATURE_VERSION = "v1";
|
|
70
|
+
async function signWebhookPayload(payload, secret, options) {
|
|
71
|
+
const t = options?.timestampSeconds ?? Math.floor(Date.now() / 1e3);
|
|
72
|
+
const signedBody = `${t}.${payload}`;
|
|
73
|
+
const mac = await hmacSha256(secret, signedBody);
|
|
74
|
+
return `t=${t},${WEBHOOK_SIGNATURE_VERSION}=${toHex(mac)}`;
|
|
75
|
+
}
|
|
76
|
+
async function verifyWebhookSignature(payload, signatureHeader, secret, options = {}) {
|
|
77
|
+
const tolerance = options.toleranceSeconds ?? WEBHOOK_SIGNATURE_TOLERANCE_SECONDS;
|
|
78
|
+
const now = options.nowSeconds ?? Math.floor(Date.now() / 1e3);
|
|
79
|
+
const parsed = parseSignatureHeader(signatureHeader);
|
|
80
|
+
if (!parsed) return { valid: false, reason: "malformed_header" };
|
|
81
|
+
const { timestamp, signatureHex } = parsed;
|
|
82
|
+
if (timestamp === null) return { valid: false, reason: "missing_timestamp" };
|
|
83
|
+
if (!signatureHex) return { valid: false, reason: "missing_signature" };
|
|
84
|
+
if (Math.abs(now - timestamp) > tolerance) {
|
|
85
|
+
return { valid: false, reason: "timestamp_out_of_range" };
|
|
86
|
+
}
|
|
87
|
+
const expected = await hmacSha256(secret, `${timestamp}.${payload}`);
|
|
88
|
+
let provided;
|
|
89
|
+
try {
|
|
90
|
+
provided = fromHex(signatureHex);
|
|
91
|
+
} catch {
|
|
92
|
+
return { valid: false, reason: "signature_mismatch" };
|
|
93
|
+
}
|
|
94
|
+
return timingSafeEqualBytes(expected, provided) ? { valid: true } : { valid: false, reason: "signature_mismatch" };
|
|
95
|
+
}
|
|
96
|
+
function parseSignatureHeader(header) {
|
|
97
|
+
if (!header || typeof header !== "string") return null;
|
|
98
|
+
const parts = header.split(",");
|
|
99
|
+
let timestamp = null;
|
|
100
|
+
let signatureHex = null;
|
|
101
|
+
for (const part of parts) {
|
|
102
|
+
const eq = part.indexOf("=");
|
|
103
|
+
if (eq <= 0) return null;
|
|
104
|
+
const key = part.slice(0, eq).trim();
|
|
105
|
+
const value = part.slice(eq + 1).trim();
|
|
106
|
+
if (key === "t") {
|
|
107
|
+
const n = Number(value);
|
|
108
|
+
if (!Number.isFinite(n) || !Number.isInteger(n)) return null;
|
|
109
|
+
timestamp = n;
|
|
110
|
+
} else if (key === WEBHOOK_SIGNATURE_VERSION) {
|
|
111
|
+
signatureHex = value;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return { timestamp, signatureHex };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export { WEBHOOK_SIGNATURE_VERSION, signWebhookPayload, verifyWebhookSignature };
|
|
118
|
+
//# sourceMappingURL=webhook.js.map
|
|
119
|
+
//# sourceMappingURL=webhook.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/encoding.ts","../src/hmac.ts","../src/timing-safe.ts","../src/webhook.ts"],"names":[],"mappings":";;;;;AAMA,IAAM,SAAA,GAAY,kBAAA;AAEX,SAAS,MAAM,KAAA,EAA2B;AAC/C,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,MAAM,CAAA,GAAI,MAAM,CAAC,CAAA;AACjB,IAAA,GAAA,IAAO,SAAA,CAAU,MAAM,CAAC,CAAA;AACxB,IAAA,GAAA,IAAO,SAAA,CAAU,IAAI,EAAI,CAAA;AAAA,EAC3B;AACA,EAAA,OAAO,GAAA;AACT;AAEO,SAAS,QAAQ,GAAA,EAAyB;AAC/C,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,IAAI,IAAI,GAAA,CAAI,KAAA,CAAM,CAAC,CAAA,GAAI,GAAA;AACpD,EAAA,IAAI,KAAA,CAAM,MAAA,GAAS,CAAA,KAAM,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAI,MAAM,+BAA+B,CAAA;AAAA,EACjD;AACA,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,KAAA,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,KAAA,CAAM,GAAG,CAAA;AAC9B,EAAA,IAAI,SAAA,GAA2B,IAAA;AAC/B,EAAA,IAAI,YAAA,GAA8B,IAAA;AAClC,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAM,EAAA,GAAK,IAAA,CAAK,OAAA,CAAQ,GAAG,CAAA;AAC3B,IAAA,IAAI,EAAA,IAAM,GAAG,OAAO,IAAA;AACpB,IAAA,MAAM,MAAM,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,EAAE,EAAE,IAAA,EAAK;AACnC,IAAA,MAAM,QAAQ,IAAA,CAAK,KAAA,CAAM,EAAA,GAAK,CAAC,EAAE,IAAA,EAAK;AACtC,IAAA,IAAI,QAAQ,GAAA,EAAK;AACf,MAAA,MAAM,CAAA,GAAI,OAAO,KAAK,CAAA;AACtB,MAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,CAAC,CAAA,IAAK,CAAC,MAAA,CAAO,SAAA,CAAU,CAAC,CAAA,EAAG,OAAO,IAAA;AACxD,MAAA,SAAA,GAAY,CAAA;AAAA,IACd,CAAA,MAAA,IAAW,QAAQ,yBAAA,EAA2B;AAC5C,MAAA,YAAA,GAAe,KAAA;AAAA,IACjB;AAAA,EACF;AACA,EAAA,OAAO,EAAE,WAAW,YAAA,EAAa;AACnC","file":"webhook.js","sourcesContent":["/**\n * Byte encoders that work in every JavaScript runtime we target.\n * No Node `Buffer`, no dependency on the DOM — just Uint8Array, strings, and\n * the two TextEncoder/TextDecoder classes available everywhere.\n */\n\nconst HEX_CHARS = '0123456789abcdef'\n\nexport function toHex(bytes: Uint8Array): string {\n let out = ''\n for (let i = 0; i < bytes.length; i++) {\n const b = bytes[i] as number\n out += HEX_CHARS[b >>> 4]\n out += HEX_CHARS[b & 0x0f]\n }\n return out\n}\n\nexport function fromHex(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') ? hex.slice(2) : hex\n if (clean.length % 2 !== 0) {\n throw new Error('fromHex: odd-length hex input')\n }\n const out = new Uint8Array(clean.length / 2)\n for (let i = 0; i < out.length; i++) {\n const byte = Number.parseInt(clean.substr(i * 2, 2), 16)\n if (Number.isNaN(byte)) {\n throw new Error('fromHex: non-hex character')\n }\n out[i] = byte\n }\n return out\n}\n\nexport function toBase64Url(bytes: Uint8Array): string {\n // Build a binary string without spreading (spread can overflow on large arrays).\n // `btoa` is global in Node 16+, all Edge runtimes, and browsers.\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i] as number)\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nexport function utf8ToBytes(str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes)\n}\n","/**\n * HMAC-SHA256 via Web Crypto.\n * Keys accept either a string (UTF-8) or raw bytes.\n */\n\nimport { toHex, utf8ToBytes } from './encoding.js'\n\nexport async function hmacSha256(\n key: string | Uint8Array,\n message: string | Uint8Array,\n): Promise<Uint8Array> {\n const keyBytes = typeof key === 'string' ? utf8ToBytes(key) : key\n const msgBytes = typeof message === 'string' ? utf8ToBytes(message) : message\n const subtle = requireSubtle()\n\n const cryptoKey = await subtle.importKey(\n 'raw',\n keyBytes as BufferSource,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n )\n const signature = await subtle.sign('HMAC', cryptoKey, msgBytes as BufferSource)\n return new Uint8Array(signature)\n}\n\nexport async function hmacSha256Hex(\n key: string | Uint8Array,\n message: string | Uint8Array,\n): Promise<string> {\n return toHex(await hmacSha256(key, message))\n}\n\nfunction requireSubtle(): SubtleCrypto {\n const c = globalThis.crypto\n if (!c || !c.subtle) {\n throw new Error('Web Crypto is not available in this runtime')\n }\n return c.subtle\n}\n","/**\n * Constant-time comparison.\n *\n * The comparison must not short-circuit on the first byte mismatch, or an\n * attacker can infer the correct value byte by byte from response timings.\n *\n * Length-difference side channels are acceptable here: leaking the length of\n * a MAC tells an attacker nothing useful (both values are fixed-size in our\n * use).\n */\n\nexport function timingSafeEqualBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) {\n diff |= (a[i] as number) ^ (b[i] as number)\n }\n return diff === 0\n}\n\nexport function timingSafeEqualString(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n }\n return diff === 0\n}\n","/**\n * Webhook signing and verification.\n *\n * Signature format: `t=<unix_seconds>,v1=<hex_hmac_sha256>`\n *\n * The HMAC is computed over `\"${t}.${payload}\"` so the timestamp is bound to\n * the signature. Verification enforces a replay window (default 300 seconds,\n * matching `@strimz/shared-config`).\n */\n\nimport { WEBHOOK_SIGNATURE_TOLERANCE_SECONDS } from '@strimz/shared-config/webhooks'\nimport { fromHex, toHex } from './encoding.js'\nimport { hmacSha256 } from './hmac.js'\nimport { timingSafeEqualBytes } from './timing-safe.js'\n\nexport const WEBHOOK_SIGNATURE_VERSION = 'v1'\n\nexport interface SignWebhookOptions {\n /** Unix timestamp in seconds. Defaults to `Math.floor(Date.now() / 1000)`. */\n timestampSeconds?: number\n}\n\nexport async function signWebhookPayload(\n payload: string,\n secret: string,\n options?: SignWebhookOptions,\n): Promise<string> {\n const t = options?.timestampSeconds ?? Math.floor(Date.now() / 1000)\n const signedBody = `${t}.${payload}`\n const mac = await hmacSha256(secret, signedBody)\n return `t=${t},${WEBHOOK_SIGNATURE_VERSION}=${toHex(mac)}`\n}\n\nexport type VerifyWebhookReason =\n | 'malformed_header'\n | 'missing_timestamp'\n | 'missing_signature'\n | 'timestamp_out_of_range'\n | 'signature_mismatch'\n\nexport type VerifyWebhookResult = { valid: true } | { valid: false; reason: VerifyWebhookReason }\n\nexport interface VerifyWebhookOptions {\n /** Maximum age of a signature in seconds. Defaults to the shared-config tolerance. */\n toleranceSeconds?: number\n /** Override \"now\" for testing. Unix seconds. */\n nowSeconds?: number\n}\n\nexport async function verifyWebhookSignature(\n payload: string,\n signatureHeader: string,\n secret: string,\n options: VerifyWebhookOptions = {},\n): Promise<VerifyWebhookResult> {\n const tolerance = options.toleranceSeconds ?? WEBHOOK_SIGNATURE_TOLERANCE_SECONDS\n const now = options.nowSeconds ?? Math.floor(Date.now() / 1000)\n\n const parsed = parseSignatureHeader(signatureHeader)\n if (!parsed) return { valid: false, reason: 'malformed_header' }\n\n const { timestamp, signatureHex } = parsed\n if (timestamp === null) return { valid: false, reason: 'missing_timestamp' }\n if (!signatureHex) return { valid: false, reason: 'missing_signature' }\n if (Math.abs(now - timestamp) > tolerance) {\n return { valid: false, reason: 'timestamp_out_of_range' }\n }\n\n const expected = await hmacSha256(secret, `${timestamp}.${payload}`)\n let provided: Uint8Array\n try {\n provided = fromHex(signatureHex)\n } catch {\n return { valid: false, reason: 'signature_mismatch' }\n }\n\n return timingSafeEqualBytes(expected, provided)\n ? { valid: true }\n : { valid: false, reason: 'signature_mismatch' }\n}\n\ninterface ParsedSignatureHeader {\n timestamp: number | null\n signatureHex: string | null\n}\n\nfunction parseSignatureHeader(header: string): ParsedSignatureHeader | null {\n if (!header || typeof header !== 'string') return null\n const parts = header.split(',')\n let timestamp: number | null = null\n let signatureHex: string | null = null\n for (const part of parts) {\n const eq = part.indexOf('=')\n if (eq <= 0) return null\n const key = part.slice(0, eq).trim()\n const value = part.slice(eq + 1).trim()\n if (key === 't') {\n const n = Number(value)\n if (!Number.isFinite(n) || !Number.isInteger(n)) return null\n timestamp = n\n } else if (key === WEBHOOK_SIGNATURE_VERSION) {\n signatureHex = value\n }\n }\n return { timestamp, signatureHex }\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@strimz/shared-crypto",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Web Crypto primitives for Strimz. HMAC webhook signing, API key generation, hashing, AES-256-GCM envelope encryption, and constant-time comparison. Runs in Node 22 and Edge runtimes.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Strimz <hello@strimz.finance>",
|
|
7
|
+
"homepage": "https://github.com/StrimzLab/strimz/tree/main/packages/shared-crypto#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/StrimzLab/strimz.git",
|
|
11
|
+
"directory": "packages/shared-crypto"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/StrimzLab/strimz/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"strimz",
|
|
18
|
+
"hmac",
|
|
19
|
+
"webhook",
|
|
20
|
+
"signing",
|
|
21
|
+
"web-crypto",
|
|
22
|
+
"aes-gcm"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"type": "module",
|
|
28
|
+
"main": "./dist/index.cjs",
|
|
29
|
+
"module": "./dist/index.js",
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"import": "./dist/index.js",
|
|
36
|
+
"require": "./dist/index.cjs"
|
|
37
|
+
},
|
|
38
|
+
"./encoding": {
|
|
39
|
+
"types": "./dist/encoding.d.ts",
|
|
40
|
+
"import": "./dist/encoding.js",
|
|
41
|
+
"require": "./dist/encoding.cjs"
|
|
42
|
+
},
|
|
43
|
+
"./hash": {
|
|
44
|
+
"types": "./dist/hash.d.ts",
|
|
45
|
+
"import": "./dist/hash.js",
|
|
46
|
+
"require": "./dist/hash.cjs"
|
|
47
|
+
},
|
|
48
|
+
"./hmac": {
|
|
49
|
+
"types": "./dist/hmac.d.ts",
|
|
50
|
+
"import": "./dist/hmac.js",
|
|
51
|
+
"require": "./dist/hmac.cjs"
|
|
52
|
+
},
|
|
53
|
+
"./random": {
|
|
54
|
+
"types": "./dist/random.d.ts",
|
|
55
|
+
"import": "./dist/random.js",
|
|
56
|
+
"require": "./dist/random.cjs"
|
|
57
|
+
},
|
|
58
|
+
"./timing-safe": {
|
|
59
|
+
"types": "./dist/timing-safe.d.ts",
|
|
60
|
+
"import": "./dist/timing-safe.js",
|
|
61
|
+
"require": "./dist/timing-safe.cjs"
|
|
62
|
+
},
|
|
63
|
+
"./webhook": {
|
|
64
|
+
"types": "./dist/webhook.d.ts",
|
|
65
|
+
"import": "./dist/webhook.js",
|
|
66
|
+
"require": "./dist/webhook.cjs"
|
|
67
|
+
},
|
|
68
|
+
"./api-key": {
|
|
69
|
+
"types": "./dist/api-key.d.ts",
|
|
70
|
+
"import": "./dist/api-key.js",
|
|
71
|
+
"require": "./dist/api-key.cjs"
|
|
72
|
+
},
|
|
73
|
+
"./aes-gcm": {
|
|
74
|
+
"types": "./dist/aes-gcm.d.ts",
|
|
75
|
+
"import": "./dist/aes-gcm.js",
|
|
76
|
+
"require": "./dist/aes-gcm.cjs"
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
"files": [
|
|
80
|
+
"dist",
|
|
81
|
+
"src",
|
|
82
|
+
"README.md",
|
|
83
|
+
"LICENSE"
|
|
84
|
+
],
|
|
85
|
+
"dependencies": {
|
|
86
|
+
"@strimz/shared-config": "0.1.0"
|
|
87
|
+
},
|
|
88
|
+
"devDependencies": {
|
|
89
|
+
"eslint": "^9.18.0",
|
|
90
|
+
"tsup": "^8.3.5",
|
|
91
|
+
"typescript": "^5.7.3",
|
|
92
|
+
"vitest": "^2.1.8",
|
|
93
|
+
"@strimz/tsconfig": "0.0.0",
|
|
94
|
+
"@strimz/eslint-config": "0.0.0"
|
|
95
|
+
},
|
|
96
|
+
"scripts": {
|
|
97
|
+
"build": "tsup",
|
|
98
|
+
"dev": "tsup --watch",
|
|
99
|
+
"lint": "eslint .",
|
|
100
|
+
"typecheck": "tsc --noEmit",
|
|
101
|
+
"test": "vitest run",
|
|
102
|
+
"test:watch": "vitest",
|
|
103
|
+
"clean": "rm -rf dist .turbo *.tsbuildinfo"
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
|
|
3
|
+
import { decryptAesGcm, encryptAesGcm, generateAesGcmKey } from './aes-gcm.js'
|
|
4
|
+
|
|
5
|
+
describe('aes-gcm', () => {
|
|
6
|
+
it('round-trips an ASCII string', async () => {
|
|
7
|
+
const key = generateAesGcmKey()
|
|
8
|
+
const plaintext = 'whsec_abcdefghijklmnopqrstuvwxyz0123456789'
|
|
9
|
+
const blob = await encryptAesGcm(plaintext, key)
|
|
10
|
+
expect(await decryptAesGcm(blob, key)).toBe(plaintext)
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it('round-trips a UTF-8 string with multi-byte characters', async () => {
|
|
14
|
+
const key = generateAesGcmKey()
|
|
15
|
+
const plaintext = 'Strimz — 🔐 secret · v2 · 你好'
|
|
16
|
+
const blob = await encryptAesGcm(plaintext, key)
|
|
17
|
+
expect(await decryptAesGcm(blob, key)).toBe(plaintext)
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
it('produces a different ciphertext for the same input each call (random nonce)', async () => {
|
|
21
|
+
const key = generateAesGcmKey()
|
|
22
|
+
const plaintext = 'identical input'
|
|
23
|
+
const a = await encryptAesGcm(plaintext, key)
|
|
24
|
+
const b = await encryptAesGcm(plaintext, key)
|
|
25
|
+
expect(a).not.toBe(b)
|
|
26
|
+
expect(await decryptAesGcm(a, key)).toBe(plaintext)
|
|
27
|
+
expect(await decryptAesGcm(b, key)).toBe(plaintext)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('starts every blob with the v1: version prefix', async () => {
|
|
31
|
+
const blob = await encryptAesGcm('x', generateAesGcmKey())
|
|
32
|
+
expect(blob.startsWith('v1:')).toBe(true)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('refuses to decrypt with the wrong key', async () => {
|
|
36
|
+
const blob = await encryptAesGcm('secret', generateAesGcmKey())
|
|
37
|
+
const other = generateAesGcmKey()
|
|
38
|
+
await expect(decryptAesGcm(blob, other)).rejects.toThrow()
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('refuses to decrypt a tampered ciphertext (auth-tag enforcement)', async () => {
|
|
42
|
+
const key = generateAesGcmKey()
|
|
43
|
+
const blob = await encryptAesGcm('untampered', key)
|
|
44
|
+
// Flip the last hex digit of the ciphertext to corrupt it.
|
|
45
|
+
const tampered = blob.replace(/[0-9a-f]$/, (last) => (last === '0' ? '1' : '0'))
|
|
46
|
+
await expect(decryptAesGcm(tampered, key)).rejects.toThrow()
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('refuses to decrypt a blob with an unrecognised version prefix', async () => {
|
|
50
|
+
const blob = (await encryptAesGcm('x', generateAesGcmKey())).replace(/^v1:/, 'v2:')
|
|
51
|
+
await expect(decryptAesGcm(blob, generateAesGcmKey())).rejects.toThrow(/version prefix/)
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('refuses to decrypt a malformed blob (missing parts)', async () => {
|
|
55
|
+
await expect(decryptAesGcm('v1:onlyonepart', generateAesGcmKey())).rejects.toThrow(/malformed/)
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('rejects non-hex keys', async () => {
|
|
59
|
+
await expect(encryptAesGcm('x', 'not-hex-zzzz')).rejects.toThrow(/hex/)
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('rejects keys of wrong length', async () => {
|
|
63
|
+
// 16 bytes (AES-128) instead of 32 (AES-256).
|
|
64
|
+
const shortKey = '0'.repeat(32)
|
|
65
|
+
await expect(encryptAesGcm('x', shortKey)).rejects.toThrow(/32 bytes/)
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('generateAesGcmKey produces 32-byte hex strings', () => {
|
|
69
|
+
const key = generateAesGcmKey()
|
|
70
|
+
expect(key).toMatch(/^[0-9a-f]{64}$/)
|
|
71
|
+
})
|
|
72
|
+
})
|
package/src/aes-gcm.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AES-256-GCM authenticated symmetric encryption via Web Crypto.
|
|
3
|
+
*
|
|
4
|
+
* Used by the webhook layer to encrypt signing secrets at rest in
|
|
5
|
+
* Postgres. Sized at the smallest interface that does the job —
|
|
6
|
+
* encrypt one short string at a time, decrypt one short string at a
|
|
7
|
+
* time, with the encryption key supplied as a 32-byte hex string from
|
|
8
|
+
* environment configuration.
|
|
9
|
+
*
|
|
10
|
+
* Why Web Crypto over `node:crypto`: the rest of `@strimz/shared-crypto`
|
|
11
|
+
* targets Node 22, Vercel Edge, and Cloudflare Workers uniformly.
|
|
12
|
+
* Keeping this consistent so the package can be imported anywhere
|
|
13
|
+
* without conditional branches.
|
|
14
|
+
*
|
|
15
|
+
* Why AES-256-GCM:
|
|
16
|
+
* - Authenticated. The auth tag detects bit-flips or substitution
|
|
17
|
+
* attacks; a tampered ciphertext fails closed at decrypt time.
|
|
18
|
+
* - Standard. Available natively in Web Crypto with no third-party
|
|
19
|
+
* dependency.
|
|
20
|
+
* - 12-byte nonce + 16-byte tag is the canonical layout.
|
|
21
|
+
*
|
|
22
|
+
* Output format (string-safe so it goes into Postgres TEXT columns
|
|
23
|
+
* without re-encoding):
|
|
24
|
+
*
|
|
25
|
+
* v1:<nonce-hex>:<ciphertext-and-tag-hex>
|
|
26
|
+
*
|
|
27
|
+
* Web Crypto returns the auth tag concatenated to the ciphertext,
|
|
28
|
+
* so the on-the-wire format keeps them together rather than splitting
|
|
29
|
+
* them out. The leading `v1:` lets future schemes coexist during
|
|
30
|
+
* migration.
|
|
31
|
+
*
|
|
32
|
+
* What this is NOT:
|
|
33
|
+
* - A KMS replacement. The key lives in env. Rotating it means
|
|
34
|
+
* rotating every encrypted value (or supporting two keys for a
|
|
35
|
+
* cutover window). Graduate to a hardware-backed envelope when
|
|
36
|
+
* funded — the `KmsSigner` abstraction in the API is the parallel
|
|
37
|
+
* pattern for sign keys.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
import { fromHex, toHex } from './encoding.js'
|
|
41
|
+
|
|
42
|
+
const ALGORITHM = 'AES-GCM'
|
|
43
|
+
const KEY_LENGTH_BYTES = 32
|
|
44
|
+
const NONCE_LENGTH_BYTES = 12
|
|
45
|
+
const TAG_LENGTH_BITS = 128
|
|
46
|
+
const VERSION_PREFIX = 'v1:'
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Encrypt a plaintext string with the supplied 32-byte hex key.
|
|
50
|
+
* Returns a versioned, colon-delimited ciphertext blob safe to store
|
|
51
|
+
* in a Postgres TEXT column.
|
|
52
|
+
*/
|
|
53
|
+
export async function encryptAesGcm(plaintext: string, keyHex: string): Promise<string> {
|
|
54
|
+
const key = await importKey(keyHex)
|
|
55
|
+
const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH_BYTES))
|
|
56
|
+
const ciphertextWithTag = new Uint8Array(
|
|
57
|
+
await crypto.subtle.encrypt(
|
|
58
|
+
{ name: ALGORITHM, iv: nonce as BufferSource, tagLength: TAG_LENGTH_BITS },
|
|
59
|
+
key,
|
|
60
|
+
new TextEncoder().encode(plaintext) as BufferSource,
|
|
61
|
+
),
|
|
62
|
+
)
|
|
63
|
+
return `${VERSION_PREFIX}${toHex(nonce)}:${toHex(ciphertextWithTag)}`
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Inverse of `encryptAesGcm`. Throws on any tampering or key mismatch
|
|
68
|
+
* — there is no partial-decrypt path. The caller decides how to
|
|
69
|
+
* surface the failure (log + fail closed for storage; reject the
|
|
70
|
+
* request for hot-path use).
|
|
71
|
+
*/
|
|
72
|
+
export async function decryptAesGcm(blob: string, keyHex: string): Promise<string> {
|
|
73
|
+
if (!blob.startsWith(VERSION_PREFIX)) {
|
|
74
|
+
throw new Error('decryptAesGcm: unsupported version prefix in blob')
|
|
75
|
+
}
|
|
76
|
+
const parts = blob.slice(VERSION_PREFIX.length).split(':')
|
|
77
|
+
if (parts.length !== 2) {
|
|
78
|
+
throw new Error('decryptAesGcm: malformed blob; expected nonce:ciphertext')
|
|
79
|
+
}
|
|
80
|
+
const [nonceHex, ciphertextHex] = parts as [string, string]
|
|
81
|
+
const nonce = fromHex(nonceHex)
|
|
82
|
+
const ciphertextWithTag = fromHex(ciphertextHex)
|
|
83
|
+
if (nonce.length !== NONCE_LENGTH_BYTES) {
|
|
84
|
+
throw new Error(`decryptAesGcm: nonce must be ${NONCE_LENGTH_BYTES} bytes`)
|
|
85
|
+
}
|
|
86
|
+
const key = await importKey(keyHex)
|
|
87
|
+
const plaintextBytes = new Uint8Array(
|
|
88
|
+
await crypto.subtle.decrypt(
|
|
89
|
+
{ name: ALGORITHM, iv: nonce as BufferSource, tagLength: TAG_LENGTH_BITS },
|
|
90
|
+
key,
|
|
91
|
+
ciphertextWithTag as BufferSource,
|
|
92
|
+
),
|
|
93
|
+
)
|
|
94
|
+
return new TextDecoder().decode(plaintextBytes)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Convenience helper for generating a fresh 32-byte hex key — used
|
|
99
|
+
* by ops scripts that seed the env var. Returned as a hex string so
|
|
100
|
+
* it can be pasted into a secrets vault without binary handling.
|
|
101
|
+
*/
|
|
102
|
+
export function generateAesGcmKey(): string {
|
|
103
|
+
const bytes = crypto.getRandomValues(new Uint8Array(KEY_LENGTH_BYTES))
|
|
104
|
+
return toHex(bytes)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function importKey(keyHex: string): Promise<CryptoKey> {
|
|
108
|
+
if (!/^[0-9a-fA-F]+$/u.test(keyHex)) {
|
|
109
|
+
throw new Error('encryption key must be a hex-encoded string')
|
|
110
|
+
}
|
|
111
|
+
const bytes = fromHex(keyHex)
|
|
112
|
+
if (bytes.length !== KEY_LENGTH_BYTES) {
|
|
113
|
+
throw new Error(`encryption key must be ${KEY_LENGTH_BYTES} bytes (got ${bytes.length})`)
|
|
114
|
+
}
|
|
115
|
+
return crypto.subtle.importKey('raw', bytes as BufferSource, { name: ALGORITHM }, false, [
|
|
116
|
+
'encrypt',
|
|
117
|
+
'decrypt',
|
|
118
|
+
])
|
|
119
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { generateApiKey, hashApiKey, redactApiKey } from './api-key.js'
|
|
3
|
+
|
|
4
|
+
describe('api-key/generateApiKey', () => {
|
|
5
|
+
it('uses the right prefix for secret test keys', async () => {
|
|
6
|
+
const k = await generateApiKey('secret', 'test')
|
|
7
|
+
expect(k.secret.startsWith('sk_test_')).toBe(true)
|
|
8
|
+
expect(k.kind).toBe('secret')
|
|
9
|
+
expect(k.mode).toBe('test')
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
it('uses the right prefix for live publishable keys', async () => {
|
|
13
|
+
const k = await generateApiKey('publishable', 'live')
|
|
14
|
+
expect(k.secret.startsWith('pk_live_')).toBe(true)
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('records the hash of the full secret', async () => {
|
|
18
|
+
const k = await generateApiKey('secret', 'test')
|
|
19
|
+
expect(await hashApiKey(k.secret)).toBe(k.hash)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('produces distinct secrets on successive calls', async () => {
|
|
23
|
+
const a = await generateApiKey('secret', 'test')
|
|
24
|
+
const b = await generateApiKey('secret', 'test')
|
|
25
|
+
expect(a.secret).not.toBe(b.secret)
|
|
26
|
+
expect(a.hash).not.toBe(b.hash)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('records a display prefix and last four chars', async () => {
|
|
30
|
+
const k = await generateApiKey('secret', 'test')
|
|
31
|
+
expect(k.prefix.length).toBeGreaterThanOrEqual(8)
|
|
32
|
+
expect(k.lastFour).toHaveLength(4)
|
|
33
|
+
expect(k.secret.endsWith(k.lastFour)).toBe(true)
|
|
34
|
+
})
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
describe('api-key/hashApiKey', () => {
|
|
38
|
+
it('is deterministic', async () => {
|
|
39
|
+
const a = await hashApiKey('sk_test_example')
|
|
40
|
+
const b = await hashApiKey('sk_test_example')
|
|
41
|
+
expect(a).toBe(b)
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it('produces a 64-char lowercase hex string (32-byte sha256)', async () => {
|
|
45
|
+
const hash = await hashApiKey('anything')
|
|
46
|
+
expect(hash).toMatch(/^[0-9a-f]{64}$/)
|
|
47
|
+
})
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
describe('api-key/redactApiKey', () => {
|
|
51
|
+
it('shows prefix and last four only', () => {
|
|
52
|
+
const out = redactApiKey('sk_test_abcdefghijklmnopqrstuvwxyz1234')
|
|
53
|
+
expect(out).toBe('sk_test_abcd...1234')
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('hides very short keys entirely', () => {
|
|
57
|
+
expect(redactApiKey('short')).toBe('***')
|
|
58
|
+
})
|
|
59
|
+
})
|
package/src/api-key.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* API key generation and indexing.
|
|
3
|
+
*
|
|
4
|
+
* A key is `<prefix><random>` where random is base64url-encoded with 32 bytes
|
|
5
|
+
* of entropy (256 bits). The backend stores:
|
|
6
|
+
* - prefix (for display)
|
|
7
|
+
* - last 4 chars (for display)
|
|
8
|
+
* - sha256(key) in lowercase hex (for O(1) lookup on every request)
|
|
9
|
+
*
|
|
10
|
+
* No salt is needed: the random portion has 256 bits of entropy and brute-
|
|
11
|
+
* forcing SHA-256 preimages of uniformly random 256-bit values is infeasible.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
API_KEY_PREFIXES,
|
|
16
|
+
API_KEY_RANDOM_BYTES,
|
|
17
|
+
API_KEY_PREFIX_DISPLAY_LENGTH,
|
|
18
|
+
type ApiKeyKind,
|
|
19
|
+
type ApiKeyMode,
|
|
20
|
+
} from '@strimz/shared-config/api-keys'
|
|
21
|
+
import { sha256Hex } from './hash.js'
|
|
22
|
+
import { randomBase64Url } from './random.js'
|
|
23
|
+
|
|
24
|
+
export interface GeneratedApiKey {
|
|
25
|
+
/** The full plaintext key — display once then discard. */
|
|
26
|
+
secret: string
|
|
27
|
+
/** Stored as the index. */
|
|
28
|
+
hash: string
|
|
29
|
+
/** Stored for display / log redaction. */
|
|
30
|
+
prefix: string
|
|
31
|
+
/** Stored for display — "my key ending in ...abcd". */
|
|
32
|
+
lastFour: string
|
|
33
|
+
kind: ApiKeyKind
|
|
34
|
+
mode: ApiKeyMode
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function generateApiKey(kind: ApiKeyKind, mode: ApiKeyMode): Promise<GeneratedApiKey> {
|
|
38
|
+
const prefixStr = API_KEY_PREFIXES[kind][mode]
|
|
39
|
+
const random = randomBase64Url(API_KEY_RANDOM_BYTES)
|
|
40
|
+
const secret = `${prefixStr}${random}`
|
|
41
|
+
const hash = await sha256Hex(secret)
|
|
42
|
+
return {
|
|
43
|
+
secret,
|
|
44
|
+
hash,
|
|
45
|
+
prefix: secret.slice(0, API_KEY_PREFIX_DISPLAY_LENGTH),
|
|
46
|
+
lastFour: secret.slice(-4),
|
|
47
|
+
kind,
|
|
48
|
+
mode,
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function hashApiKey(secret: string): Promise<string> {
|
|
53
|
+
return sha256Hex(secret)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function redactApiKey(secret: string): string {
|
|
57
|
+
if (secret.length <= API_KEY_PREFIX_DISPLAY_LENGTH + 4) {
|
|
58
|
+
return '***'
|
|
59
|
+
}
|
|
60
|
+
return `${secret.slice(0, API_KEY_PREFIX_DISPLAY_LENGTH)}...${secret.slice(-4)}`
|
|
61
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { bytesToUtf8, fromHex, toBase64Url, toHex, utf8ToBytes } from './encoding.js'
|
|
3
|
+
|
|
4
|
+
describe('encoding/hex', () => {
|
|
5
|
+
it('round-trips through toHex → fromHex', () => {
|
|
6
|
+
const bytes = new Uint8Array([0, 1, 2, 254, 255, 127, 128])
|
|
7
|
+
const hex = toHex(bytes)
|
|
8
|
+
expect(hex).toBe('000102feff7f80')
|
|
9
|
+
expect(fromHex(hex)).toEqual(bytes)
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
it('accepts an optional 0x prefix on fromHex', () => {
|
|
13
|
+
expect(fromHex('0xdeadbeef')).toEqual(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('rejects odd-length hex', () => {
|
|
17
|
+
expect(() => fromHex('abc')).toThrow('odd-length')
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
it('rejects non-hex characters', () => {
|
|
21
|
+
expect(() => fromHex('xy')).toThrow('non-hex')
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('produces lowercase hex', () => {
|
|
25
|
+
expect(toHex(new Uint8Array([0xab, 0xcd]))).toBe('abcd')
|
|
26
|
+
})
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
describe('encoding/base64url', () => {
|
|
30
|
+
it('encodes without padding and with URL-safe characters', () => {
|
|
31
|
+
// Bytes chosen so stdlib base64 would emit + / =
|
|
32
|
+
const bytes = new Uint8Array([0xfb, 0xff, 0xbf])
|
|
33
|
+
const out = toBase64Url(bytes)
|
|
34
|
+
expect(out).not.toContain('+')
|
|
35
|
+
expect(out).not.toContain('/')
|
|
36
|
+
expect(out).not.toContain('=')
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('encodes empty input to empty string', () => {
|
|
40
|
+
expect(toBase64Url(new Uint8Array(0))).toBe('')
|
|
41
|
+
})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
describe('encoding/utf8', () => {
|
|
45
|
+
it('round-trips through utf8ToBytes → bytesToUtf8', () => {
|
|
46
|
+
const s = 'hello — world 🌍'
|
|
47
|
+
expect(bytesToUtf8(utf8ToBytes(s))).toBe(s)
|
|
48
|
+
})
|
|
49
|
+
})
|
package/src/encoding.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Byte encoders that work in every JavaScript runtime we target.
|
|
3
|
+
* No Node `Buffer`, no dependency on the DOM — just Uint8Array, strings, and
|
|
4
|
+
* the two TextEncoder/TextDecoder classes available everywhere.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const HEX_CHARS = '0123456789abcdef'
|
|
8
|
+
|
|
9
|
+
export function toHex(bytes: Uint8Array): string {
|
|
10
|
+
let out = ''
|
|
11
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
12
|
+
const b = bytes[i] as number
|
|
13
|
+
out += HEX_CHARS[b >>> 4]
|
|
14
|
+
out += HEX_CHARS[b & 0x0f]
|
|
15
|
+
}
|
|
16
|
+
return out
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function fromHex(hex: string): Uint8Array {
|
|
20
|
+
const clean = hex.startsWith('0x') ? hex.slice(2) : hex
|
|
21
|
+
if (clean.length % 2 !== 0) {
|
|
22
|
+
throw new Error('fromHex: odd-length hex input')
|
|
23
|
+
}
|
|
24
|
+
const out = new Uint8Array(clean.length / 2)
|
|
25
|
+
for (let i = 0; i < out.length; i++) {
|
|
26
|
+
const byte = Number.parseInt(clean.substr(i * 2, 2), 16)
|
|
27
|
+
if (Number.isNaN(byte)) {
|
|
28
|
+
throw new Error('fromHex: non-hex character')
|
|
29
|
+
}
|
|
30
|
+
out[i] = byte
|
|
31
|
+
}
|
|
32
|
+
return out
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function toBase64Url(bytes: Uint8Array): string {
|
|
36
|
+
// Build a binary string without spreading (spread can overflow on large arrays).
|
|
37
|
+
// `btoa` is global in Node 16+, all Edge runtimes, and browsers.
|
|
38
|
+
let binary = ''
|
|
39
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
40
|
+
binary += String.fromCharCode(bytes[i] as number)
|
|
41
|
+
}
|
|
42
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function utf8ToBytes(str: string): Uint8Array {
|
|
46
|
+
return new TextEncoder().encode(str)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function bytesToUtf8(bytes: Uint8Array): string {
|
|
50
|
+
return new TextDecoder().decode(bytes)
|
|
51
|
+
}
|