@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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +57 -0
  3. package/dist/aes-gcm.cjs +94 -0
  4. package/dist/aes-gcm.cjs.map +1 -0
  5. package/dist/aes-gcm.d.cts +59 -0
  6. package/dist/aes-gcm.d.ts +59 -0
  7. package/dist/aes-gcm.js +90 -0
  8. package/dist/aes-gcm.js.map +1 -0
  9. package/dist/api-key.cjs +95 -0
  10. package/dist/api-key.cjs.map +1 -0
  11. package/dist/api-key.d.cts +32 -0
  12. package/dist/api-key.d.ts +32 -0
  13. package/dist/api-key.js +91 -0
  14. package/dist/api-key.js.map +1 -0
  15. package/dist/encoding.cjs +49 -0
  16. package/dist/encoding.cjs.map +1 -0
  17. package/dist/encoding.d.cts +12 -0
  18. package/dist/encoding.d.ts +12 -0
  19. package/dist/encoding.js +43 -0
  20. package/dist/encoding.js.map +1 -0
  21. package/dist/hash.cjs +38 -0
  22. package/dist/hash.cjs.map +1 -0
  23. package/dist/hash.d.cts +7 -0
  24. package/dist/hash.d.ts +7 -0
  25. package/dist/hash.js +35 -0
  26. package/dist/hash.js.map +1 -0
  27. package/dist/hmac.cjs +47 -0
  28. package/dist/hmac.cjs.map +1 -0
  29. package/dist/hmac.d.cts +8 -0
  30. package/dist/hmac.d.ts +8 -0
  31. package/dist/hmac.js +44 -0
  32. package/dist/hmac.js.map +1 -0
  33. package/dist/index.cjs +296 -0
  34. package/dist/index.cjs.map +1 -0
  35. package/dist/index.d.cts +9 -0
  36. package/dist/index.d.ts +9 -0
  37. package/dist/index.js +271 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/random.cjs +61 -0
  40. package/dist/random.cjs.map +1 -0
  41. package/dist/random.d.cts +10 -0
  42. package/dist/random.d.ts +10 -0
  43. package/dist/random.js +56 -0
  44. package/dist/random.js.map +1 -0
  45. package/dist/timing-safe.cjs +24 -0
  46. package/dist/timing-safe.cjs.map +1 -0
  47. package/dist/timing-safe.d.cts +14 -0
  48. package/dist/timing-safe.d.ts +14 -0
  49. package/dist/timing-safe.js +21 -0
  50. package/dist/timing-safe.js.map +1 -0
  51. package/dist/webhook.cjs +123 -0
  52. package/dist/webhook.cjs.map +1 -0
  53. package/dist/webhook.d.cts +31 -0
  54. package/dist/webhook.d.ts +31 -0
  55. package/dist/webhook.js +119 -0
  56. package/dist/webhook.js.map +1 -0
  57. package/package.json +105 -0
  58. package/src/aes-gcm.test.ts +72 -0
  59. package/src/aes-gcm.ts +119 -0
  60. package/src/api-key.test.ts +59 -0
  61. package/src/api-key.ts +61 -0
  62. package/src/encoding.test.ts +49 -0
  63. package/src/encoding.ts +51 -0
  64. package/src/hash.test.ts +29 -0
  65. package/src/hash.ts +23 -0
  66. package/src/hmac.test.ts +28 -0
  67. package/src/hmac.ts +40 -0
  68. package/src/index.ts +15 -0
  69. package/src/random.test.ts +45 -0
  70. package/src/random.ts +44 -0
  71. package/src/timing-safe.test.ts +38 -0
  72. package/src/timing-safe.ts +28 -0
  73. package/src/webhook.test.ts +78 -0
  74. package/src/webhook.ts +106 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Strimz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # @strimz/shared-crypto
2
+
3
+ Cryptographic primitives for the Strimz platform. Built on the Web Crypto API so the same code runs unchanged in Node 22, Vercel Edge, Cloudflare Workers, and any modern browser.
4
+
5
+ ## What lives here
6
+
7
+ | Subpath | Contents |
8
+ | -------------- | ------------------------------------------------------------------------------------------------------- |
9
+ | `/encoding` | `toHex`, `fromHex`, `toBase64Url`, `utf8ToBytes`, `bytesToUtf8` |
10
+ | `/hash` | `sha256`, `sha256Hex` |
11
+ | `/hmac` | `hmacSha256`, `hmacSha256Hex` |
12
+ | `/random` | `randomBytes`, `randomHex`, `randomBase64Url`, `uuid` |
13
+ | `/timing-safe` | `timingSafeEqualBytes`, `timingSafeEqualString` |
14
+ | `/webhook` | `signWebhookPayload`, `verifyWebhookSignature` (Stripe-shaped scheme) |
15
+ | `/api-key` | `generateApiKey`, `hashApiKey`, `redactApiKey` |
16
+ | `/aes-gcm` | `encryptAesGcm`, `decryptAesGcm`, `generateAesGcmKey` (envelope encryption for webhook secrets at rest) |
17
+
18
+ The package root re-exports every subpath.
19
+
20
+ ## Webhook signing
21
+
22
+ ```ts
23
+ import { signWebhookPayload, verifyWebhookSignature } from '@strimz/shared-crypto'
24
+
25
+ // Sender
26
+ const header = await signWebhookPayload(JSON.stringify(body), secret)
27
+ // → "t=1735123456,v1=abc123...def"
28
+
29
+ // Receiver
30
+ const result = await verifyWebhookSignature(rawBodyString, header, secret)
31
+ if (!result.valid) {
32
+ throw new Error(`invalid signature: ${result.reason}`)
33
+ }
34
+ ```
35
+
36
+ Signatures are HMAC-SHA256 over `"${t}.${payload}"`. The timestamp is bound to the signature so replays are detectable; verification rejects any timestamp outside the tolerance window (default 5 minutes, configured in `@strimz/shared-config/webhooks`).
37
+
38
+ ## API key generation
39
+
40
+ ```ts
41
+ import { generateApiKey, hashApiKey } from '@strimz/shared-crypto'
42
+
43
+ const { secret, hash, prefix, lastFour } = await generateApiKey('secret', 'test')
44
+ // Persist { hash, prefix, lastFour, kind: 'secret', mode: 'test' }.
45
+ // Return `secret` to the caller once, then drop it from memory.
46
+
47
+ // On every authenticated request:
48
+ const incomingHash = await hashApiKey(req.headers.authorization.slice('Bearer '.length))
49
+ const row = await db.apiKey.findUnique({ where: { hash: incomingHash } })
50
+ ```
51
+
52
+ ## Boundaries
53
+
54
+ - **No secrets are logged.** `redactApiKey` exists specifically so any diagnostic that must include a key logs only the safe prefix and the last four characters.
55
+ - **No Node `Buffer` or `node:crypto`.** Every primitive uses `globalThis.crypto.subtle` and `Uint8Array`.
56
+ - **Constant-time compare on signatures.** Signature verification must never short-circuit on the first mismatched byte.
57
+ - **The package does not decide policy.** Tolerance windows, key prefixes, and tier thresholds come from `@strimz/shared-config`; this package consumes them.
@@ -0,0 +1,94 @@
1
+ 'use strict';
2
+
3
+ // src/encoding.ts
4
+ var HEX_CHARS = "0123456789abcdef";
5
+ function toHex(bytes) {
6
+ let out = "";
7
+ for (let i = 0; i < bytes.length; i++) {
8
+ const b = bytes[i];
9
+ out += HEX_CHARS[b >>> 4];
10
+ out += HEX_CHARS[b & 15];
11
+ }
12
+ return out;
13
+ }
14
+ function fromHex(hex) {
15
+ const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
16
+ if (clean.length % 2 !== 0) {
17
+ throw new Error("fromHex: odd-length hex input");
18
+ }
19
+ const out = new Uint8Array(clean.length / 2);
20
+ for (let i = 0; i < out.length; i++) {
21
+ const byte = Number.parseInt(clean.substr(i * 2, 2), 16);
22
+ if (Number.isNaN(byte)) {
23
+ throw new Error("fromHex: non-hex character");
24
+ }
25
+ out[i] = byte;
26
+ }
27
+ return out;
28
+ }
29
+
30
+ // src/aes-gcm.ts
31
+ var ALGORITHM = "AES-GCM";
32
+ var KEY_LENGTH_BYTES = 32;
33
+ var NONCE_LENGTH_BYTES = 12;
34
+ var TAG_LENGTH_BITS = 128;
35
+ var VERSION_PREFIX = "v1:";
36
+ async function encryptAesGcm(plaintext, keyHex) {
37
+ const key = await importKey(keyHex);
38
+ const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH_BYTES));
39
+ const ciphertextWithTag = new Uint8Array(
40
+ await crypto.subtle.encrypt(
41
+ { name: ALGORITHM, iv: nonce, tagLength: TAG_LENGTH_BITS },
42
+ key,
43
+ new TextEncoder().encode(plaintext)
44
+ )
45
+ );
46
+ return `${VERSION_PREFIX}${toHex(nonce)}:${toHex(ciphertextWithTag)}`;
47
+ }
48
+ async function decryptAesGcm(blob, keyHex) {
49
+ if (!blob.startsWith(VERSION_PREFIX)) {
50
+ throw new Error("decryptAesGcm: unsupported version prefix in blob");
51
+ }
52
+ const parts = blob.slice(VERSION_PREFIX.length).split(":");
53
+ if (parts.length !== 2) {
54
+ throw new Error("decryptAesGcm: malformed blob; expected nonce:ciphertext");
55
+ }
56
+ const [nonceHex, ciphertextHex] = parts;
57
+ const nonce = fromHex(nonceHex);
58
+ const ciphertextWithTag = fromHex(ciphertextHex);
59
+ if (nonce.length !== NONCE_LENGTH_BYTES) {
60
+ throw new Error(`decryptAesGcm: nonce must be ${NONCE_LENGTH_BYTES} bytes`);
61
+ }
62
+ const key = await importKey(keyHex);
63
+ const plaintextBytes = new Uint8Array(
64
+ await crypto.subtle.decrypt(
65
+ { name: ALGORITHM, iv: nonce, tagLength: TAG_LENGTH_BITS },
66
+ key,
67
+ ciphertextWithTag
68
+ )
69
+ );
70
+ return new TextDecoder().decode(plaintextBytes);
71
+ }
72
+ function generateAesGcmKey() {
73
+ const bytes = crypto.getRandomValues(new Uint8Array(KEY_LENGTH_BYTES));
74
+ return toHex(bytes);
75
+ }
76
+ async function importKey(keyHex) {
77
+ if (!/^[0-9a-fA-F]+$/u.test(keyHex)) {
78
+ throw new Error("encryption key must be a hex-encoded string");
79
+ }
80
+ const bytes = fromHex(keyHex);
81
+ if (bytes.length !== KEY_LENGTH_BYTES) {
82
+ throw new Error(`encryption key must be ${KEY_LENGTH_BYTES} bytes (got ${bytes.length})`);
83
+ }
84
+ return crypto.subtle.importKey("raw", bytes, { name: ALGORITHM }, false, [
85
+ "encrypt",
86
+ "decrypt"
87
+ ]);
88
+ }
89
+
90
+ exports.decryptAesGcm = decryptAesGcm;
91
+ exports.encryptAesGcm = encryptAesGcm;
92
+ exports.generateAesGcmKey = generateAesGcmKey;
93
+ //# sourceMappingURL=aes-gcm.cjs.map
94
+ //# sourceMappingURL=aes-gcm.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/encoding.ts","../src/aes-gcm.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,EAC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AAC3D,EAAA,IAAI,CAAC,iBAAA,CAAkB,IAAA,CAAK,MAAM,CAAA,EAAG;AACnC,IAAA,MAAM,IAAI,MAAM,6CAA6C,CAAA;AAAA,EAC/D;AACA,EAAA,MAAM,KAAA,GAAQ,QAAQ,MAAM,CAAA;AAC5B,EAAA,IAAI,KAAA,CAAM,WAAW,gBAAA,EAAkB;AACrC,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,uBAAA,EAA0B,gBAAgB,CAAA,YAAA,EAAe,KAAA,CAAM,MAAM,CAAA,CAAA,CAAG,CAAA;AAAA,EAC1F;AACA,EAAA,OAAO,MAAA,CAAO,OAAO,SAAA,CAAU,KAAA,EAAO,OAAuB,EAAE,IAAA,EAAM,SAAA,EAAU,EAAG,KAAA,EAAO;AAAA,IACvF,SAAA;AAAA,IACA;AAAA,GACD,CAAA;AACH","file":"aes-gcm.cjs","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 * AES-256-GCM authenticated symmetric encryption via Web Crypto.\n *\n * Used by the webhook layer to encrypt signing secrets at rest in\n * Postgres. Sized at the smallest interface that does the job —\n * encrypt one short string at a time, decrypt one short string at a\n * time, with the encryption key supplied as a 32-byte hex string from\n * environment configuration.\n *\n * Why Web Crypto over `node:crypto`: the rest of `@strimz/shared-crypto`\n * targets Node 22, Vercel Edge, and Cloudflare Workers uniformly.\n * Keeping this consistent so the package can be imported anywhere\n * without conditional branches.\n *\n * Why AES-256-GCM:\n * - Authenticated. The auth tag detects bit-flips or substitution\n * attacks; a tampered ciphertext fails closed at decrypt time.\n * - Standard. Available natively in Web Crypto with no third-party\n * dependency.\n * - 12-byte nonce + 16-byte tag is the canonical layout.\n *\n * Output format (string-safe so it goes into Postgres TEXT columns\n * without re-encoding):\n *\n * v1:<nonce-hex>:<ciphertext-and-tag-hex>\n *\n * Web Crypto returns the auth tag concatenated to the ciphertext,\n * so the on-the-wire format keeps them together rather than splitting\n * them out. The leading `v1:` lets future schemes coexist during\n * migration.\n *\n * What this is NOT:\n * - A KMS replacement. The key lives in env. Rotating it means\n * rotating every encrypted value (or supporting two keys for a\n * cutover window). Graduate to a hardware-backed envelope when\n * funded — the `KmsSigner` abstraction in the API is the parallel\n * pattern for sign keys.\n */\n\nimport { fromHex, toHex } from './encoding.js'\n\nconst ALGORITHM = 'AES-GCM'\nconst KEY_LENGTH_BYTES = 32\nconst NONCE_LENGTH_BYTES = 12\nconst TAG_LENGTH_BITS = 128\nconst VERSION_PREFIX = 'v1:'\n\n/**\n * Encrypt a plaintext string with the supplied 32-byte hex key.\n * Returns a versioned, colon-delimited ciphertext blob safe to store\n * in a Postgres TEXT column.\n */\nexport async function encryptAesGcm(plaintext: string, keyHex: string): Promise<string> {\n const key = await importKey(keyHex)\n const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH_BYTES))\n const ciphertextWithTag = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: ALGORITHM, iv: nonce as BufferSource, tagLength: TAG_LENGTH_BITS },\n key,\n new TextEncoder().encode(plaintext) as BufferSource,\n ),\n )\n return `${VERSION_PREFIX}${toHex(nonce)}:${toHex(ciphertextWithTag)}`\n}\n\n/**\n * Inverse of `encryptAesGcm`. Throws on any tampering or key mismatch\n * — there is no partial-decrypt path. The caller decides how to\n * surface the failure (log + fail closed for storage; reject the\n * request for hot-path use).\n */\nexport async function decryptAesGcm(blob: string, keyHex: string): Promise<string> {\n if (!blob.startsWith(VERSION_PREFIX)) {\n throw new Error('decryptAesGcm: unsupported version prefix in blob')\n }\n const parts = blob.slice(VERSION_PREFIX.length).split(':')\n if (parts.length !== 2) {\n throw new Error('decryptAesGcm: malformed blob; expected nonce:ciphertext')\n }\n const [nonceHex, ciphertextHex] = parts as [string, string]\n const nonce = fromHex(nonceHex)\n const ciphertextWithTag = fromHex(ciphertextHex)\n if (nonce.length !== NONCE_LENGTH_BYTES) {\n throw new Error(`decryptAesGcm: nonce must be ${NONCE_LENGTH_BYTES} bytes`)\n }\n const key = await importKey(keyHex)\n const plaintextBytes = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: ALGORITHM, iv: nonce as BufferSource, tagLength: TAG_LENGTH_BITS },\n key,\n ciphertextWithTag as BufferSource,\n ),\n )\n return new TextDecoder().decode(plaintextBytes)\n}\n\n/**\n * Convenience helper for generating a fresh 32-byte hex key — used\n * by ops scripts that seed the env var. Returned as a hex string so\n * it can be pasted into a secrets vault without binary handling.\n */\nexport function generateAesGcmKey(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(KEY_LENGTH_BYTES))\n return toHex(bytes)\n}\n\nasync function importKey(keyHex: string): Promise<CryptoKey> {\n if (!/^[0-9a-fA-F]+$/u.test(keyHex)) {\n throw new Error('encryption key must be a hex-encoded string')\n }\n const bytes = fromHex(keyHex)\n if (bytes.length !== KEY_LENGTH_BYTES) {\n throw new Error(`encryption key must be ${KEY_LENGTH_BYTES} bytes (got ${bytes.length})`)\n }\n return crypto.subtle.importKey('raw', bytes as BufferSource, { name: ALGORITHM }, false, [\n 'encrypt',\n 'decrypt',\n ])\n}\n"]}
@@ -0,0 +1,59 @@
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
+ * Encrypt a plaintext string with the supplied 32-byte hex key.
41
+ * Returns a versioned, colon-delimited ciphertext blob safe to store
42
+ * in a Postgres TEXT column.
43
+ */
44
+ declare function encryptAesGcm(plaintext: string, keyHex: string): Promise<string>;
45
+ /**
46
+ * Inverse of `encryptAesGcm`. Throws on any tampering or key mismatch
47
+ * — there is no partial-decrypt path. The caller decides how to
48
+ * surface the failure (log + fail closed for storage; reject the
49
+ * request for hot-path use).
50
+ */
51
+ declare function decryptAesGcm(blob: string, keyHex: string): Promise<string>;
52
+ /**
53
+ * Convenience helper for generating a fresh 32-byte hex key — used
54
+ * by ops scripts that seed the env var. Returned as a hex string so
55
+ * it can be pasted into a secrets vault without binary handling.
56
+ */
57
+ declare function generateAesGcmKey(): string;
58
+
59
+ export { decryptAesGcm, encryptAesGcm, generateAesGcmKey };
@@ -0,0 +1,59 @@
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
+ * Encrypt a plaintext string with the supplied 32-byte hex key.
41
+ * Returns a versioned, colon-delimited ciphertext blob safe to store
42
+ * in a Postgres TEXT column.
43
+ */
44
+ declare function encryptAesGcm(plaintext: string, keyHex: string): Promise<string>;
45
+ /**
46
+ * Inverse of `encryptAesGcm`. Throws on any tampering or key mismatch
47
+ * — there is no partial-decrypt path. The caller decides how to
48
+ * surface the failure (log + fail closed for storage; reject the
49
+ * request for hot-path use).
50
+ */
51
+ declare function decryptAesGcm(blob: string, keyHex: string): Promise<string>;
52
+ /**
53
+ * Convenience helper for generating a fresh 32-byte hex key — used
54
+ * by ops scripts that seed the env var. Returned as a hex string so
55
+ * it can be pasted into a secrets vault without binary handling.
56
+ */
57
+ declare function generateAesGcmKey(): string;
58
+
59
+ export { decryptAesGcm, encryptAesGcm, generateAesGcmKey };
@@ -0,0 +1,90 @@
1
+ // src/encoding.ts
2
+ var HEX_CHARS = "0123456789abcdef";
3
+ function toHex(bytes) {
4
+ let out = "";
5
+ for (let i = 0; i < bytes.length; i++) {
6
+ const b = bytes[i];
7
+ out += HEX_CHARS[b >>> 4];
8
+ out += HEX_CHARS[b & 15];
9
+ }
10
+ return out;
11
+ }
12
+ function fromHex(hex) {
13
+ const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
14
+ if (clean.length % 2 !== 0) {
15
+ throw new Error("fromHex: odd-length hex input");
16
+ }
17
+ const out = new Uint8Array(clean.length / 2);
18
+ for (let i = 0; i < out.length; i++) {
19
+ const byte = Number.parseInt(clean.substr(i * 2, 2), 16);
20
+ if (Number.isNaN(byte)) {
21
+ throw new Error("fromHex: non-hex character");
22
+ }
23
+ out[i] = byte;
24
+ }
25
+ return out;
26
+ }
27
+
28
+ // src/aes-gcm.ts
29
+ var ALGORITHM = "AES-GCM";
30
+ var KEY_LENGTH_BYTES = 32;
31
+ var NONCE_LENGTH_BYTES = 12;
32
+ var TAG_LENGTH_BITS = 128;
33
+ var VERSION_PREFIX = "v1:";
34
+ async function encryptAesGcm(plaintext, keyHex) {
35
+ const key = await importKey(keyHex);
36
+ const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH_BYTES));
37
+ const ciphertextWithTag = new Uint8Array(
38
+ await crypto.subtle.encrypt(
39
+ { name: ALGORITHM, iv: nonce, tagLength: TAG_LENGTH_BITS },
40
+ key,
41
+ new TextEncoder().encode(plaintext)
42
+ )
43
+ );
44
+ return `${VERSION_PREFIX}${toHex(nonce)}:${toHex(ciphertextWithTag)}`;
45
+ }
46
+ async function decryptAesGcm(blob, keyHex) {
47
+ if (!blob.startsWith(VERSION_PREFIX)) {
48
+ throw new Error("decryptAesGcm: unsupported version prefix in blob");
49
+ }
50
+ const parts = blob.slice(VERSION_PREFIX.length).split(":");
51
+ if (parts.length !== 2) {
52
+ throw new Error("decryptAesGcm: malformed blob; expected nonce:ciphertext");
53
+ }
54
+ const [nonceHex, ciphertextHex] = parts;
55
+ const nonce = fromHex(nonceHex);
56
+ const ciphertextWithTag = fromHex(ciphertextHex);
57
+ if (nonce.length !== NONCE_LENGTH_BYTES) {
58
+ throw new Error(`decryptAesGcm: nonce must be ${NONCE_LENGTH_BYTES} bytes`);
59
+ }
60
+ const key = await importKey(keyHex);
61
+ const plaintextBytes = new Uint8Array(
62
+ await crypto.subtle.decrypt(
63
+ { name: ALGORITHM, iv: nonce, tagLength: TAG_LENGTH_BITS },
64
+ key,
65
+ ciphertextWithTag
66
+ )
67
+ );
68
+ return new TextDecoder().decode(plaintextBytes);
69
+ }
70
+ function generateAesGcmKey() {
71
+ const bytes = crypto.getRandomValues(new Uint8Array(KEY_LENGTH_BYTES));
72
+ return toHex(bytes);
73
+ }
74
+ async function importKey(keyHex) {
75
+ if (!/^[0-9a-fA-F]+$/u.test(keyHex)) {
76
+ throw new Error("encryption key must be a hex-encoded string");
77
+ }
78
+ const bytes = fromHex(keyHex);
79
+ if (bytes.length !== KEY_LENGTH_BYTES) {
80
+ throw new Error(`encryption key must be ${KEY_LENGTH_BYTES} bytes (got ${bytes.length})`);
81
+ }
82
+ return crypto.subtle.importKey("raw", bytes, { name: ALGORITHM }, false, [
83
+ "encrypt",
84
+ "decrypt"
85
+ ]);
86
+ }
87
+
88
+ export { decryptAesGcm, encryptAesGcm, generateAesGcmKey };
89
+ //# sourceMappingURL=aes-gcm.js.map
90
+ //# sourceMappingURL=aes-gcm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/encoding.ts","../src/aes-gcm.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,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AAC,iBAAA,CAAkB,IAAA,CAAK,MAAM,CAAA,EAAG;AACnC,IAAA,MAAM,IAAI,MAAM,6CAA6C,CAAA;AAAA,EAC/D;AACA,EAAA,MAAM,KAAA,GAAQ,QAAQ,MAAM,CAAA;AAC5B,EAAA,IAAI,KAAA,CAAM,WAAW,gBAAA,EAAkB;AACrC,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,uBAAA,EAA0B,gBAAgB,CAAA,YAAA,EAAe,KAAA,CAAM,MAAM,CAAA,CAAA,CAAG,CAAA;AAAA,EAC1F;AACA,EAAA,OAAO,MAAA,CAAO,OAAO,SAAA,CAAU,KAAA,EAAO,OAAuB,EAAE,IAAA,EAAM,SAAA,EAAU,EAAG,KAAA,EAAO;AAAA,IACvF,SAAA;AAAA,IACA;AAAA,GACD,CAAA;AACH","file":"aes-gcm.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 * AES-256-GCM authenticated symmetric encryption via Web Crypto.\n *\n * Used by the webhook layer to encrypt signing secrets at rest in\n * Postgres. Sized at the smallest interface that does the job —\n * encrypt one short string at a time, decrypt one short string at a\n * time, with the encryption key supplied as a 32-byte hex string from\n * environment configuration.\n *\n * Why Web Crypto over `node:crypto`: the rest of `@strimz/shared-crypto`\n * targets Node 22, Vercel Edge, and Cloudflare Workers uniformly.\n * Keeping this consistent so the package can be imported anywhere\n * without conditional branches.\n *\n * Why AES-256-GCM:\n * - Authenticated. The auth tag detects bit-flips or substitution\n * attacks; a tampered ciphertext fails closed at decrypt time.\n * - Standard. Available natively in Web Crypto with no third-party\n * dependency.\n * - 12-byte nonce + 16-byte tag is the canonical layout.\n *\n * Output format (string-safe so it goes into Postgres TEXT columns\n * without re-encoding):\n *\n * v1:<nonce-hex>:<ciphertext-and-tag-hex>\n *\n * Web Crypto returns the auth tag concatenated to the ciphertext,\n * so the on-the-wire format keeps them together rather than splitting\n * them out. The leading `v1:` lets future schemes coexist during\n * migration.\n *\n * What this is NOT:\n * - A KMS replacement. The key lives in env. Rotating it means\n * rotating every encrypted value (or supporting two keys for a\n * cutover window). Graduate to a hardware-backed envelope when\n * funded — the `KmsSigner` abstraction in the API is the parallel\n * pattern for sign keys.\n */\n\nimport { fromHex, toHex } from './encoding.js'\n\nconst ALGORITHM = 'AES-GCM'\nconst KEY_LENGTH_BYTES = 32\nconst NONCE_LENGTH_BYTES = 12\nconst TAG_LENGTH_BITS = 128\nconst VERSION_PREFIX = 'v1:'\n\n/**\n * Encrypt a plaintext string with the supplied 32-byte hex key.\n * Returns a versioned, colon-delimited ciphertext blob safe to store\n * in a Postgres TEXT column.\n */\nexport async function encryptAesGcm(plaintext: string, keyHex: string): Promise<string> {\n const key = await importKey(keyHex)\n const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH_BYTES))\n const ciphertextWithTag = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: ALGORITHM, iv: nonce as BufferSource, tagLength: TAG_LENGTH_BITS },\n key,\n new TextEncoder().encode(plaintext) as BufferSource,\n ),\n )\n return `${VERSION_PREFIX}${toHex(nonce)}:${toHex(ciphertextWithTag)}`\n}\n\n/**\n * Inverse of `encryptAesGcm`. Throws on any tampering or key mismatch\n * — there is no partial-decrypt path. The caller decides how to\n * surface the failure (log + fail closed for storage; reject the\n * request for hot-path use).\n */\nexport async function decryptAesGcm(blob: string, keyHex: string): Promise<string> {\n if (!blob.startsWith(VERSION_PREFIX)) {\n throw new Error('decryptAesGcm: unsupported version prefix in blob')\n }\n const parts = blob.slice(VERSION_PREFIX.length).split(':')\n if (parts.length !== 2) {\n throw new Error('decryptAesGcm: malformed blob; expected nonce:ciphertext')\n }\n const [nonceHex, ciphertextHex] = parts as [string, string]\n const nonce = fromHex(nonceHex)\n const ciphertextWithTag = fromHex(ciphertextHex)\n if (nonce.length !== NONCE_LENGTH_BYTES) {\n throw new Error(`decryptAesGcm: nonce must be ${NONCE_LENGTH_BYTES} bytes`)\n }\n const key = await importKey(keyHex)\n const plaintextBytes = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: ALGORITHM, iv: nonce as BufferSource, tagLength: TAG_LENGTH_BITS },\n key,\n ciphertextWithTag as BufferSource,\n ),\n )\n return new TextDecoder().decode(plaintextBytes)\n}\n\n/**\n * Convenience helper for generating a fresh 32-byte hex key — used\n * by ops scripts that seed the env var. Returned as a hex string so\n * it can be pasted into a secrets vault without binary handling.\n */\nexport function generateAesGcmKey(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(KEY_LENGTH_BYTES))\n return toHex(bytes)\n}\n\nasync function importKey(keyHex: string): Promise<CryptoKey> {\n if (!/^[0-9a-fA-F]+$/u.test(keyHex)) {\n throw new Error('encryption key must be a hex-encoded string')\n }\n const bytes = fromHex(keyHex)\n if (bytes.length !== KEY_LENGTH_BYTES) {\n throw new Error(`encryption key must be ${KEY_LENGTH_BYTES} bytes (got ${bytes.length})`)\n }\n return crypto.subtle.importKey('raw', bytes as BufferSource, { name: ALGORITHM }, false, [\n 'encrypt',\n 'decrypt',\n ])\n}\n"]}
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+
3
+ var apiKeys = require('@strimz/shared-config/api-keys');
4
+
5
+ // src/api-key.ts
6
+
7
+ // src/encoding.ts
8
+ var HEX_CHARS = "0123456789abcdef";
9
+ function toHex(bytes) {
10
+ let out = "";
11
+ for (let i = 0; i < bytes.length; i++) {
12
+ const b = bytes[i];
13
+ out += HEX_CHARS[b >>> 4];
14
+ out += HEX_CHARS[b & 15];
15
+ }
16
+ return out;
17
+ }
18
+ function toBase64Url(bytes) {
19
+ let binary = "";
20
+ for (let i = 0; i < bytes.length; i++) {
21
+ binary += String.fromCharCode(bytes[i]);
22
+ }
23
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
24
+ }
25
+ function utf8ToBytes(str) {
26
+ return new TextEncoder().encode(str);
27
+ }
28
+
29
+ // src/hash.ts
30
+ async function sha256(data) {
31
+ const bytes = typeof data === "string" ? utf8ToBytes(data) : data;
32
+ const digest = await subtle().digest("SHA-256", bytes);
33
+ return new Uint8Array(digest);
34
+ }
35
+ async function sha256Hex(data) {
36
+ return toHex(await sha256(data));
37
+ }
38
+ function subtle() {
39
+ const c = globalThis.crypto;
40
+ if (!c || !c.subtle) {
41
+ throw new Error("Web Crypto is not available in this runtime");
42
+ }
43
+ return c.subtle;
44
+ }
45
+
46
+ // src/random.ts
47
+ function randomBytes(n) {
48
+ if (!Number.isInteger(n) || n <= 0) {
49
+ throw new Error("randomBytes: n must be a positive integer");
50
+ }
51
+ const buf = new Uint8Array(n);
52
+ getRandomValues(buf);
53
+ return buf;
54
+ }
55
+ function randomBase64Url(nBytes) {
56
+ return toBase64Url(randomBytes(nBytes));
57
+ }
58
+ function getRandomValues(buf) {
59
+ const c = globalThis.crypto;
60
+ if (!c || typeof c.getRandomValues !== "function") {
61
+ throw new Error("crypto.getRandomValues is not available in this runtime");
62
+ }
63
+ c.getRandomValues(buf);
64
+ }
65
+
66
+ // src/api-key.ts
67
+ async function generateApiKey(kind, mode) {
68
+ const prefixStr = apiKeys.API_KEY_PREFIXES[kind][mode];
69
+ const random = randomBase64Url(apiKeys.API_KEY_RANDOM_BYTES);
70
+ const secret = `${prefixStr}${random}`;
71
+ const hash = await sha256Hex(secret);
72
+ return {
73
+ secret,
74
+ hash,
75
+ prefix: secret.slice(0, apiKeys.API_KEY_PREFIX_DISPLAY_LENGTH),
76
+ lastFour: secret.slice(-4),
77
+ kind,
78
+ mode
79
+ };
80
+ }
81
+ async function hashApiKey(secret) {
82
+ return sha256Hex(secret);
83
+ }
84
+ function redactApiKey(secret) {
85
+ if (secret.length <= apiKeys.API_KEY_PREFIX_DISPLAY_LENGTH + 4) {
86
+ return "***";
87
+ }
88
+ return `${secret.slice(0, apiKeys.API_KEY_PREFIX_DISPLAY_LENGTH)}...${secret.slice(-4)}`;
89
+ }
90
+
91
+ exports.generateApiKey = generateApiKey;
92
+ exports.hashApiKey = hashApiKey;
93
+ exports.redactApiKey = redactApiKey;
94
+ //# sourceMappingURL=api-key.cjs.map
95
+ //# sourceMappingURL=api-key.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/encoding.ts","../src/hash.ts","../src/random.ts","../src/api-key.ts"],"names":["API_KEY_PREFIXES","API_KEY_RANDOM_BYTES","API_KEY_PREFIX_DISPLAY_LENGTH"],"mappings":";;;;;;;AAMA,IAAM,SAAA,GAAY,kBAAA;AAEX,SAAS,MAAM,KAAA,EAA2B;AAC/C,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,IAAS,CAAA,GAAI,CAA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AAA,EAAGC,qCAA6B,CAAA;AAAA,IACrD,QAAA,EAAU,MAAA,CAAO,KAAA,CAAM,EAAE,CAAA;AAAA,IACzB,IAAA;AAAA,IACA;AAAA,GACF;AACF;AAEA,eAAsB,WAAW,MAAA,EAAiC;AAChE,EAAA,OAAO,UAAU,MAAM,CAAA;AACzB;AAEO,SAAS,aAAa,MAAA,EAAwB;AACnD,EAAA,IAAI,MAAA,CAAO,MAAA,IAAUA,qCAAA,GAAgC,CAAA,EAAG;AACtD,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,CAAA,EAAG,MAAA,CAAO,KAAA,CAAM,CAAA,EAAGA,qCAA6B,CAAC,CAAA,GAAA,EAAM,MAAA,CAAO,KAAA,CAAM,EAAE,CAAC,CAAA,CAAA;AAChF","file":"api-key.cjs","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 * SHA-256 via Web Crypto (available in Node 16+, Deno, Bun, Workers, Edge).\n */\n\nimport { toHex, utf8ToBytes } from './encoding.js'\n\nexport async function sha256(data: string | Uint8Array): Promise<Uint8Array> {\n const bytes = typeof data === 'string' ? utf8ToBytes(data) : data\n const digest = await subtle().digest('SHA-256', bytes as BufferSource)\n return new Uint8Array(digest)\n}\n\nexport async function sha256Hex(data: string | Uint8Array): Promise<string> {\n return toHex(await sha256(data))\n}\n\nfunction subtle(): 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 * Random-bytes and id generation using the Web Crypto RNG\n * (cryptographically secure in every runtime we target).\n */\n\nimport { toBase64Url, toHex } from './encoding.js'\n\nexport function randomBytes(n: number): Uint8Array {\n if (!Number.isInteger(n) || n <= 0) {\n throw new Error('randomBytes: n must be a positive integer')\n }\n const buf = new Uint8Array(n)\n getRandomValues(buf)\n return buf\n}\n\nexport function randomHex(nBytes: number): string {\n return toHex(randomBytes(nBytes))\n}\n\nexport function randomBase64Url(nBytes: number): string {\n return toBase64Url(randomBytes(nBytes))\n}\n\nexport function uuid(): string {\n const c = globalThis.crypto\n if (c && typeof c.randomUUID === 'function') {\n return c.randomUUID()\n }\n // Fallback — RFC 4122 v4 from getRandomValues\n const bytes = randomBytes(16)\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x40\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80\n const hex = toHex(bytes)\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n\nfunction getRandomValues(buf: Uint8Array): void {\n const c = globalThis.crypto\n if (!c || typeof c.getRandomValues !== 'function') {\n throw new Error('crypto.getRandomValues is not available in this runtime')\n }\n c.getRandomValues(buf)\n}\n","/**\n * API key generation and indexing.\n *\n * A key is `<prefix><random>` where random is base64url-encoded with 32 bytes\n * of entropy (256 bits). The backend stores:\n * - prefix (for display)\n * - last 4 chars (for display)\n * - sha256(key) in lowercase hex (for O(1) lookup on every request)\n *\n * No salt is needed: the random portion has 256 bits of entropy and brute-\n * forcing SHA-256 preimages of uniformly random 256-bit values is infeasible.\n */\n\nimport {\n API_KEY_PREFIXES,\n API_KEY_RANDOM_BYTES,\n API_KEY_PREFIX_DISPLAY_LENGTH,\n type ApiKeyKind,\n type ApiKeyMode,\n} from '@strimz/shared-config/api-keys'\nimport { sha256Hex } from './hash.js'\nimport { randomBase64Url } from './random.js'\n\nexport interface GeneratedApiKey {\n /** The full plaintext key — display once then discard. */\n secret: string\n /** Stored as the index. */\n hash: string\n /** Stored for display / log redaction. */\n prefix: string\n /** Stored for display — \"my key ending in ...abcd\". */\n lastFour: string\n kind: ApiKeyKind\n mode: ApiKeyMode\n}\n\nexport async function generateApiKey(kind: ApiKeyKind, mode: ApiKeyMode): Promise<GeneratedApiKey> {\n const prefixStr = API_KEY_PREFIXES[kind][mode]\n const random = randomBase64Url(API_KEY_RANDOM_BYTES)\n const secret = `${prefixStr}${random}`\n const hash = await sha256Hex(secret)\n return {\n secret,\n hash,\n prefix: secret.slice(0, API_KEY_PREFIX_DISPLAY_LENGTH),\n lastFour: secret.slice(-4),\n kind,\n mode,\n }\n}\n\nexport async function hashApiKey(secret: string): Promise<string> {\n return sha256Hex(secret)\n}\n\nexport function redactApiKey(secret: string): string {\n if (secret.length <= API_KEY_PREFIX_DISPLAY_LENGTH + 4) {\n return '***'\n }\n return `${secret.slice(0, API_KEY_PREFIX_DISPLAY_LENGTH)}...${secret.slice(-4)}`\n}\n"]}
@@ -0,0 +1,32 @@
1
+ import { ApiKeyKind, ApiKeyMode } from '@strimz/shared-config/api-keys';
2
+
3
+ /**
4
+ * API key generation and indexing.
5
+ *
6
+ * A key is `<prefix><random>` where random is base64url-encoded with 32 bytes
7
+ * of entropy (256 bits). The backend stores:
8
+ * - prefix (for display)
9
+ * - last 4 chars (for display)
10
+ * - sha256(key) in lowercase hex (for O(1) lookup on every request)
11
+ *
12
+ * No salt is needed: the random portion has 256 bits of entropy and brute-
13
+ * forcing SHA-256 preimages of uniformly random 256-bit values is infeasible.
14
+ */
15
+
16
+ interface GeneratedApiKey {
17
+ /** The full plaintext key — display once then discard. */
18
+ secret: string;
19
+ /** Stored as the index. */
20
+ hash: string;
21
+ /** Stored for display / log redaction. */
22
+ prefix: string;
23
+ /** Stored for display — "my key ending in ...abcd". */
24
+ lastFour: string;
25
+ kind: ApiKeyKind;
26
+ mode: ApiKeyMode;
27
+ }
28
+ declare function generateApiKey(kind: ApiKeyKind, mode: ApiKeyMode): Promise<GeneratedApiKey>;
29
+ declare function hashApiKey(secret: string): Promise<string>;
30
+ declare function redactApiKey(secret: string): string;
31
+
32
+ export { type GeneratedApiKey, generateApiKey, hashApiKey, redactApiKey };
@@ -0,0 +1,32 @@
1
+ import { ApiKeyKind, ApiKeyMode } from '@strimz/shared-config/api-keys';
2
+
3
+ /**
4
+ * API key generation and indexing.
5
+ *
6
+ * A key is `<prefix><random>` where random is base64url-encoded with 32 bytes
7
+ * of entropy (256 bits). The backend stores:
8
+ * - prefix (for display)
9
+ * - last 4 chars (for display)
10
+ * - sha256(key) in lowercase hex (for O(1) lookup on every request)
11
+ *
12
+ * No salt is needed: the random portion has 256 bits of entropy and brute-
13
+ * forcing SHA-256 preimages of uniformly random 256-bit values is infeasible.
14
+ */
15
+
16
+ interface GeneratedApiKey {
17
+ /** The full plaintext key — display once then discard. */
18
+ secret: string;
19
+ /** Stored as the index. */
20
+ hash: string;
21
+ /** Stored for display / log redaction. */
22
+ prefix: string;
23
+ /** Stored for display — "my key ending in ...abcd". */
24
+ lastFour: string;
25
+ kind: ApiKeyKind;
26
+ mode: ApiKeyMode;
27
+ }
28
+ declare function generateApiKey(kind: ApiKeyKind, mode: ApiKeyMode): Promise<GeneratedApiKey>;
29
+ declare function hashApiKey(secret: string): Promise<string>;
30
+ declare function redactApiKey(secret: string): string;
31
+
32
+ export { type GeneratedApiKey, generateApiKey, hashApiKey, redactApiKey };