@strimz/shared-crypto 0.2.8 → 0.3.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/dist/checkout.cjs +14 -0
- package/dist/checkout.cjs.map +1 -1
- package/dist/checkout.d.cts +3 -1
- package/dist/checkout.d.ts +3 -1
- package/dist/checkout.js +13 -1
- package/dist/checkout.js.map +1 -1
- package/dist/index.cjs +14 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/checkout.test.ts +31 -1
- package/src/checkout.ts +17 -0
package/dist/checkout.cjs
CHANGED
|
@@ -15,8 +15,22 @@ function checkoutPaymentNonce(sessionId) {
|
|
|
15
15
|
)
|
|
16
16
|
);
|
|
17
17
|
}
|
|
18
|
+
var SUBSCRIPTION_INTENT_NONCE_DOMAIN = "strimz.subscription-intent-nonce.v1";
|
|
19
|
+
function subscriptionIntentNonce(planId, payer, permitNonce) {
|
|
20
|
+
if (planId.length === 0) {
|
|
21
|
+
throw new Error("subscriptionIntentNonce requires a non-empty plan id");
|
|
22
|
+
}
|
|
23
|
+
return viem.keccak256(
|
|
24
|
+
viem.encodeAbiParameters(
|
|
25
|
+
[{ type: "string" }, { type: "string" }, { type: "address" }, { type: "uint256" }],
|
|
26
|
+
[SUBSCRIPTION_INTENT_NONCE_DOMAIN, planId, payer.toLowerCase(), permitNonce]
|
|
27
|
+
)
|
|
28
|
+
);
|
|
29
|
+
}
|
|
18
30
|
|
|
19
31
|
exports.CHECKOUT_PAYMENT_NONCE_DOMAIN = CHECKOUT_PAYMENT_NONCE_DOMAIN;
|
|
32
|
+
exports.SUBSCRIPTION_INTENT_NONCE_DOMAIN = SUBSCRIPTION_INTENT_NONCE_DOMAIN;
|
|
20
33
|
exports.checkoutPaymentNonce = checkoutPaymentNonce;
|
|
34
|
+
exports.subscriptionIntentNonce = subscriptionIntentNonce;
|
|
21
35
|
//# sourceMappingURL=checkout.cjs.map
|
|
22
36
|
//# sourceMappingURL=checkout.cjs.map
|
package/dist/checkout.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/checkout.ts"],"names":["keccak256","encodeAbiParameters"],"mappings":";;;;;AAEO,IAAM,6BAAA,GAAgC;AAEtC,SAAS,qBAAqB,SAAA,EAAwB;AAC3D,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAI,MAAM,sDAAsD,CAAA;AAAA,EACxE;AACA,EAAA,OAAOA,cAAA;AAAA,IACLC,wBAAA;AAAA,MACE,CAAC,EAAE,IAAA,EAAM,QAAA,IAAY,EAAE,IAAA,EAAM,UAAU,CAAA;AAAA,MACvC,CAAC,+BAA+B,SAAS;AAAA;AAC3C,GACF;AACF","file":"checkout.cjs","sourcesContent":["import { encodeAbiParameters, keccak256, type Hex } from 'viem'\n\nexport const CHECKOUT_PAYMENT_NONCE_DOMAIN = 'strimz.checkout.payment-nonce.v1'\n\nexport function checkoutPaymentNonce(sessionId: string): Hex {\n if (sessionId.length === 0) {\n throw new Error('checkoutPaymentNonce requires a non-empty session id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }],\n [CHECKOUT_PAYMENT_NONCE_DOMAIN, sessionId],\n ),\n )\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/checkout.ts"],"names":["keccak256","encodeAbiParameters"],"mappings":";;;;;AAEO,IAAM,6BAAA,GAAgC;AAEtC,SAAS,qBAAqB,SAAA,EAAwB;AAC3D,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAI,MAAM,sDAAsD,CAAA;AAAA,EACxE;AACA,EAAA,OAAOA,cAAA;AAAA,IACLC,wBAAA;AAAA,MACE,CAAC,EAAE,IAAA,EAAM,QAAA,IAAY,EAAE,IAAA,EAAM,UAAU,CAAA;AAAA,MACvC,CAAC,+BAA+B,SAAS;AAAA;AAC3C,GACF;AACF;AAEO,IAAM,gCAAA,GAAmC;AAKzC,SAAS,uBAAA,CAAwB,MAAA,EAAgB,KAAA,EAAY,WAAA,EAA0B;AAC5F,EAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACvB,IAAA,MAAM,IAAI,MAAM,sDAAsD,CAAA;AAAA,EACxE;AACA,EAAA,OAAOD,cAAA;AAAA,IACLC,wBAAA;AAAA,MACE,CAAC,EAAE,IAAA,EAAM,QAAA,EAAS,EAAG,EAAE,IAAA,EAAM,QAAA,EAAS,EAAG,EAAE,MAAM,SAAA,EAAU,EAAG,EAAE,IAAA,EAAM,WAAW,CAAA;AAAA,MACjF,CAAC,gCAAA,EAAkC,MAAA,EAAQ,KAAA,CAAM,WAAA,IAAsB,WAAW;AAAA;AACpF,GACF;AACF","file":"checkout.cjs","sourcesContent":["import { encodeAbiParameters, keccak256, type Hex } from 'viem'\n\nexport const CHECKOUT_PAYMENT_NONCE_DOMAIN = 'strimz.checkout.payment-nonce.v1'\n\nexport function checkoutPaymentNonce(sessionId: string): Hex {\n if (sessionId.length === 0) {\n throw new Error('checkoutPaymentNonce requires a non-empty session id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }],\n [CHECKOUT_PAYMENT_NONCE_DOMAIN, sessionId],\n ),\n )\n}\n\nexport const SUBSCRIPTION_INTENT_NONCE_DOMAIN = 'strimz.subscription-intent-nonce.v1'\n\n// The token's permit nonce only moves when a permit lands, so a re-sign while\n// an enrolment is pending gets the same intent nonce and the contract rejects\n// the duplicate.\nexport function subscriptionIntentNonce(planId: string, payer: Hex, permitNonce: bigint): Hex {\n if (planId.length === 0) {\n throw new Error('subscriptionIntentNonce requires a non-empty plan id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }, { type: 'address' }, { type: 'uint256' }],\n [SUBSCRIPTION_INTENT_NONCE_DOMAIN, planId, payer.toLowerCase() as Hex, permitNonce],\n ),\n )\n}\n"]}
|
package/dist/checkout.d.cts
CHANGED
|
@@ -2,5 +2,7 @@ import { Hex } from 'viem';
|
|
|
2
2
|
|
|
3
3
|
declare const CHECKOUT_PAYMENT_NONCE_DOMAIN = "strimz.checkout.payment-nonce.v1";
|
|
4
4
|
declare function checkoutPaymentNonce(sessionId: string): Hex;
|
|
5
|
+
declare const SUBSCRIPTION_INTENT_NONCE_DOMAIN = "strimz.subscription-intent-nonce.v1";
|
|
6
|
+
declare function subscriptionIntentNonce(planId: string, payer: Hex, permitNonce: bigint): Hex;
|
|
5
7
|
|
|
6
|
-
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, checkoutPaymentNonce };
|
|
8
|
+
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, SUBSCRIPTION_INTENT_NONCE_DOMAIN, checkoutPaymentNonce, subscriptionIntentNonce };
|
package/dist/checkout.d.ts
CHANGED
|
@@ -2,5 +2,7 @@ import { Hex } from 'viem';
|
|
|
2
2
|
|
|
3
3
|
declare const CHECKOUT_PAYMENT_NONCE_DOMAIN = "strimz.checkout.payment-nonce.v1";
|
|
4
4
|
declare function checkoutPaymentNonce(sessionId: string): Hex;
|
|
5
|
+
declare const SUBSCRIPTION_INTENT_NONCE_DOMAIN = "strimz.subscription-intent-nonce.v1";
|
|
6
|
+
declare function subscriptionIntentNonce(planId: string, payer: Hex, permitNonce: bigint): Hex;
|
|
5
7
|
|
|
6
|
-
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, checkoutPaymentNonce };
|
|
8
|
+
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, SUBSCRIPTION_INTENT_NONCE_DOMAIN, checkoutPaymentNonce, subscriptionIntentNonce };
|
package/dist/checkout.js
CHANGED
|
@@ -13,7 +13,19 @@ function checkoutPaymentNonce(sessionId) {
|
|
|
13
13
|
)
|
|
14
14
|
);
|
|
15
15
|
}
|
|
16
|
+
var SUBSCRIPTION_INTENT_NONCE_DOMAIN = "strimz.subscription-intent-nonce.v1";
|
|
17
|
+
function subscriptionIntentNonce(planId, payer, permitNonce) {
|
|
18
|
+
if (planId.length === 0) {
|
|
19
|
+
throw new Error("subscriptionIntentNonce requires a non-empty plan id");
|
|
20
|
+
}
|
|
21
|
+
return keccak256(
|
|
22
|
+
encodeAbiParameters(
|
|
23
|
+
[{ type: "string" }, { type: "string" }, { type: "address" }, { type: "uint256" }],
|
|
24
|
+
[SUBSCRIPTION_INTENT_NONCE_DOMAIN, planId, payer.toLowerCase(), permitNonce]
|
|
25
|
+
)
|
|
26
|
+
);
|
|
27
|
+
}
|
|
16
28
|
|
|
17
|
-
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, checkoutPaymentNonce };
|
|
29
|
+
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, SUBSCRIPTION_INTENT_NONCE_DOMAIN, checkoutPaymentNonce, subscriptionIntentNonce };
|
|
18
30
|
//# sourceMappingURL=checkout.js.map
|
|
19
31
|
//# sourceMappingURL=checkout.js.map
|
package/dist/checkout.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/checkout.ts"],"names":[],"mappings":";;;AAEO,IAAM,6BAAA,GAAgC;AAEtC,SAAS,qBAAqB,SAAA,EAAwB;AAC3D,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAI,MAAM,sDAAsD,CAAA;AAAA,EACxE;AACA,EAAA,OAAO,SAAA;AAAA,IACL,mBAAA;AAAA,MACE,CAAC,EAAE,IAAA,EAAM,QAAA,IAAY,EAAE,IAAA,EAAM,UAAU,CAAA;AAAA,MACvC,CAAC,+BAA+B,SAAS;AAAA;AAC3C,GACF;AACF","file":"checkout.js","sourcesContent":["import { encodeAbiParameters, keccak256, type Hex } from 'viem'\n\nexport const CHECKOUT_PAYMENT_NONCE_DOMAIN = 'strimz.checkout.payment-nonce.v1'\n\nexport function checkoutPaymentNonce(sessionId: string): Hex {\n if (sessionId.length === 0) {\n throw new Error('checkoutPaymentNonce requires a non-empty session id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }],\n [CHECKOUT_PAYMENT_NONCE_DOMAIN, sessionId],\n ),\n )\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/checkout.ts"],"names":[],"mappings":";;;AAEO,IAAM,6BAAA,GAAgC;AAEtC,SAAS,qBAAqB,SAAA,EAAwB;AAC3D,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAI,MAAM,sDAAsD,CAAA;AAAA,EACxE;AACA,EAAA,OAAO,SAAA;AAAA,IACL,mBAAA;AAAA,MACE,CAAC,EAAE,IAAA,EAAM,QAAA,IAAY,EAAE,IAAA,EAAM,UAAU,CAAA;AAAA,MACvC,CAAC,+BAA+B,SAAS;AAAA;AAC3C,GACF;AACF;AAEO,IAAM,gCAAA,GAAmC;AAKzC,SAAS,uBAAA,CAAwB,MAAA,EAAgB,KAAA,EAAY,WAAA,EAA0B;AAC5F,EAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACvB,IAAA,MAAM,IAAI,MAAM,sDAAsD,CAAA;AAAA,EACxE;AACA,EAAA,OAAO,SAAA;AAAA,IACL,mBAAA;AAAA,MACE,CAAC,EAAE,IAAA,EAAM,QAAA,EAAS,EAAG,EAAE,IAAA,EAAM,QAAA,EAAS,EAAG,EAAE,MAAM,SAAA,EAAU,EAAG,EAAE,IAAA,EAAM,WAAW,CAAA;AAAA,MACjF,CAAC,gCAAA,EAAkC,MAAA,EAAQ,KAAA,CAAM,WAAA,IAAsB,WAAW;AAAA;AACpF,GACF;AACF","file":"checkout.js","sourcesContent":["import { encodeAbiParameters, keccak256, type Hex } from 'viem'\n\nexport const CHECKOUT_PAYMENT_NONCE_DOMAIN = 'strimz.checkout.payment-nonce.v1'\n\nexport function checkoutPaymentNonce(sessionId: string): Hex {\n if (sessionId.length === 0) {\n throw new Error('checkoutPaymentNonce requires a non-empty session id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }],\n [CHECKOUT_PAYMENT_NONCE_DOMAIN, sessionId],\n ),\n )\n}\n\nexport const SUBSCRIPTION_INTENT_NONCE_DOMAIN = 'strimz.subscription-intent-nonce.v1'\n\n// The token's permit nonce only moves when a permit lands, so a re-sign while\n// an enrolment is pending gets the same intent nonce and the contract rejects\n// the duplicate.\nexport function subscriptionIntentNonce(planId: string, payer: Hex, permitNonce: bigint): Hex {\n if (planId.length === 0) {\n throw new Error('subscriptionIntentNonce requires a non-empty plan id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }, { type: 'address' }, { type: 'uint256' }],\n [SUBSCRIPTION_INTENT_NONCE_DOMAIN, planId, payer.toLowerCase() as Hex, permitNonce],\n ),\n )\n}\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -280,8 +280,21 @@ function checkoutPaymentNonce(sessionId) {
|
|
|
280
280
|
)
|
|
281
281
|
);
|
|
282
282
|
}
|
|
283
|
+
var SUBSCRIPTION_INTENT_NONCE_DOMAIN = "strimz.subscription-intent-nonce.v1";
|
|
284
|
+
function subscriptionIntentNonce(planId, payer, permitNonce) {
|
|
285
|
+
if (planId.length === 0) {
|
|
286
|
+
throw new Error("subscriptionIntentNonce requires a non-empty plan id");
|
|
287
|
+
}
|
|
288
|
+
return viem.keccak256(
|
|
289
|
+
viem.encodeAbiParameters(
|
|
290
|
+
[{ type: "string" }, { type: "string" }, { type: "address" }, { type: "uint256" }],
|
|
291
|
+
[SUBSCRIPTION_INTENT_NONCE_DOMAIN, planId, payer.toLowerCase(), permitNonce]
|
|
292
|
+
)
|
|
293
|
+
);
|
|
294
|
+
}
|
|
283
295
|
|
|
284
296
|
exports.CHECKOUT_PAYMENT_NONCE_DOMAIN = CHECKOUT_PAYMENT_NONCE_DOMAIN;
|
|
297
|
+
exports.SUBSCRIPTION_INTENT_NONCE_DOMAIN = SUBSCRIPTION_INTENT_NONCE_DOMAIN;
|
|
285
298
|
exports.WEBHOOK_SIGNATURE_VERSION = WEBHOOK_SIGNATURE_VERSION;
|
|
286
299
|
exports.bytesToUtf8 = bytesToUtf8;
|
|
287
300
|
exports.checkoutPaymentNonce = checkoutPaymentNonce;
|
|
@@ -300,6 +313,7 @@ exports.redactApiKey = redactApiKey;
|
|
|
300
313
|
exports.sha256 = sha256;
|
|
301
314
|
exports.sha256Hex = sha256Hex;
|
|
302
315
|
exports.signWebhookPayload = signWebhookPayload;
|
|
316
|
+
exports.subscriptionIntentNonce = subscriptionIntentNonce;
|
|
303
317
|
exports.timingSafeEqualBytes = timingSafeEqualBytes;
|
|
304
318
|
exports.timingSafeEqualString = timingSafeEqualString;
|
|
305
319
|
exports.toBase64Url = toBase64Url;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/encoding.ts","../src/hash.ts","../src/hmac.ts","../src/random.ts","../src/timing-safe.ts","../src/webhook.ts","../src/api-key.ts","../src/aes-gcm.ts","../src/checkout.ts"],"names":["subtle","WEBHOOK_SIGNATURE_TOLERANCE_SECONDS","API_KEY_PREFIXES","API_KEY_RANDOM_BYTES","API_KEY_PREFIX_DISPLAY_LENGTH","keccak256","encodeAbiParameters"],"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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,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;ACzGO,IAAM,6BAAA,GAAgC;AAEtC,SAAS,qBAAqB,SAAA,EAAwB;AAC3D,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAI,MAAM,sDAAsD,CAAA;AAAA,EACxE;AACA,EAAA,OAAOC,cAAA;AAAA,IACLC,wBAAA;AAAA,MACE,CAAC,EAAE,IAAA,EAAM,QAAA,IAAY,EAAE,IAAA,EAAM,UAAU,CAAA;AAAA,MACvC,CAAC,+BAA+B,SAAS;AAAA;AAC3C,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Byte encoders that work in every JavaScript runtime we target.\n * No Node `Buffer`, no dependency on the DOM. Only 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 * 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 * 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 * 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","/**\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, e.g. \"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 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","/**\n * AES-256-GCM authenticated symmetric encryption via Web Crypto.\n *\n * Encrypt one short string at a time, decrypt one short string at a\n * time. The encryption key is supplied as a 32-byte hex string by the\n * caller. Suitable for envelope-encrypting small secrets where the\n * key is held outside the data store.\n *\n * AES-GCM is authenticated, so the auth tag detects bit-flips and\n * substitution attacks. A tampered ciphertext fails closed at decrypt\n * time. The 12-byte nonce and 16-byte tag are the canonical layout\n * exposed by Web Crypto.\n *\n * Output format is string-safe and suitable for any text column:\n *\n * v1:<nonce-hex>:<ciphertext-and-tag-hex>\n *\n * Web Crypto returns the auth tag concatenated to the ciphertext, so\n * 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 * This is not a KMS replacement. The key lives in caller-controlled\n * storage. Rotating it means rotating every encrypted value, or\n * supporting two keys for a cutover window. For sign keys, use a\n * hardware-backed signer pattern instead.\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 any 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 * with 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\nfunction 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","import { encodeAbiParameters, keccak256, type Hex } from 'viem'\n\nexport const CHECKOUT_PAYMENT_NONCE_DOMAIN = 'strimz.checkout.payment-nonce.v1'\n\nexport function checkoutPaymentNonce(sessionId: string): Hex {\n if (sessionId.length === 0) {\n throw new Error('checkoutPaymentNonce requires a non-empty session id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }],\n [CHECKOUT_PAYMENT_NONCE_DOMAIN, sessionId],\n ),\n )\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/encoding.ts","../src/hash.ts","../src/hmac.ts","../src/random.ts","../src/timing-safe.ts","../src/webhook.ts","../src/api-key.ts","../src/aes-gcm.ts","../src/checkout.ts"],"names":["subtle","WEBHOOK_SIGNATURE_TOLERANCE_SECONDS","API_KEY_PREFIXES","API_KEY_RANDOM_BYTES","API_KEY_PREFIX_DISPLAY_LENGTH","keccak256","encodeAbiParameters"],"mappings":";;;;;;;AAMA,IAAM,SAAA,GAAY,kBAAA;AAEX,SAAS,MAAM,KAAA,EAA2B;AAC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,sDAAsD,CAAA;AAAA,EACxE;AACA,EAAA,OAAOD,cAAA;AAAA,IACLC,wBAAA;AAAA,MACE,CAAC,EAAE,IAAA,EAAM,QAAA,EAAS,EAAG,EAAE,IAAA,EAAM,QAAA,EAAS,EAAG,EAAE,MAAM,SAAA,EAAU,EAAG,EAAE,IAAA,EAAM,WAAW,CAAA;AAAA,MACjF,CAAC,gCAAA,EAAkC,MAAA,EAAQ,KAAA,CAAM,WAAA,IAAsB,WAAW;AAAA;AACpF,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Byte encoders that work in every JavaScript runtime we target.\n * No Node `Buffer`, no dependency on the DOM. Only 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 * 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 * 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 * 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","/**\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, e.g. \"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 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","/**\n * AES-256-GCM authenticated symmetric encryption via Web Crypto.\n *\n * Encrypt one short string at a time, decrypt one short string at a\n * time. The encryption key is supplied as a 32-byte hex string by the\n * caller. Suitable for envelope-encrypting small secrets where the\n * key is held outside the data store.\n *\n * AES-GCM is authenticated, so the auth tag detects bit-flips and\n * substitution attacks. A tampered ciphertext fails closed at decrypt\n * time. The 12-byte nonce and 16-byte tag are the canonical layout\n * exposed by Web Crypto.\n *\n * Output format is string-safe and suitable for any text column:\n *\n * v1:<nonce-hex>:<ciphertext-and-tag-hex>\n *\n * Web Crypto returns the auth tag concatenated to the ciphertext, so\n * 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 * This is not a KMS replacement. The key lives in caller-controlled\n * storage. Rotating it means rotating every encrypted value, or\n * supporting two keys for a cutover window. For sign keys, use a\n * hardware-backed signer pattern instead.\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 any 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 * with 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\nfunction 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","import { encodeAbiParameters, keccak256, type Hex } from 'viem'\n\nexport const CHECKOUT_PAYMENT_NONCE_DOMAIN = 'strimz.checkout.payment-nonce.v1'\n\nexport function checkoutPaymentNonce(sessionId: string): Hex {\n if (sessionId.length === 0) {\n throw new Error('checkoutPaymentNonce requires a non-empty session id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }],\n [CHECKOUT_PAYMENT_NONCE_DOMAIN, sessionId],\n ),\n )\n}\n\nexport const SUBSCRIPTION_INTENT_NONCE_DOMAIN = 'strimz.subscription-intent-nonce.v1'\n\n// The token's permit nonce only moves when a permit lands, so a re-sign while\n// an enrolment is pending gets the same intent nonce and the contract rejects\n// the duplicate.\nexport function subscriptionIntentNonce(planId: string, payer: Hex, permitNonce: bigint): Hex {\n if (planId.length === 0) {\n throw new Error('subscriptionIntentNonce requires a non-empty plan id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }, { type: 'address' }, { type: 'uint256' }],\n [SUBSCRIPTION_INTENT_NONCE_DOMAIN, planId, payer.toLowerCase() as Hex, permitNonce],\n ),\n )\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -6,6 +6,6 @@ export { timingSafeEqualBytes, timingSafeEqualString } from './timing-safe.cjs';
|
|
|
6
6
|
export { SignWebhookOptions, VerifyWebhookOptions, VerifyWebhookReason, VerifyWebhookResult, WEBHOOK_SIGNATURE_VERSION, signWebhookPayload, verifyWebhookSignature } from './webhook.cjs';
|
|
7
7
|
export { GeneratedApiKey, generateApiKey, hashApiKey, redactApiKey } from './api-key.cjs';
|
|
8
8
|
export { decryptAesGcm, encryptAesGcm, generateAesGcmKey } from './aes-gcm.cjs';
|
|
9
|
-
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, checkoutPaymentNonce } from './checkout.cjs';
|
|
9
|
+
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, SUBSCRIPTION_INTENT_NONCE_DOMAIN, checkoutPaymentNonce, subscriptionIntentNonce } from './checkout.cjs';
|
|
10
10
|
import '@strimz/shared-config/api-keys';
|
|
11
11
|
import 'viem';
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,6 @@ export { timingSafeEqualBytes, timingSafeEqualString } from './timing-safe.js';
|
|
|
6
6
|
export { SignWebhookOptions, VerifyWebhookOptions, VerifyWebhookReason, VerifyWebhookResult, WEBHOOK_SIGNATURE_VERSION, signWebhookPayload, verifyWebhookSignature } from './webhook.js';
|
|
7
7
|
export { GeneratedApiKey, generateApiKey, hashApiKey, redactApiKey } from './api-key.js';
|
|
8
8
|
export { decryptAesGcm, encryptAesGcm, generateAesGcmKey } from './aes-gcm.js';
|
|
9
|
-
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, checkoutPaymentNonce } from './checkout.js';
|
|
9
|
+
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, SUBSCRIPTION_INTENT_NONCE_DOMAIN, checkoutPaymentNonce, subscriptionIntentNonce } from './checkout.js';
|
|
10
10
|
import '@strimz/shared-config/api-keys';
|
|
11
11
|
import 'viem';
|
package/dist/index.js
CHANGED
|
@@ -278,7 +278,19 @@ function checkoutPaymentNonce(sessionId) {
|
|
|
278
278
|
)
|
|
279
279
|
);
|
|
280
280
|
}
|
|
281
|
+
var SUBSCRIPTION_INTENT_NONCE_DOMAIN = "strimz.subscription-intent-nonce.v1";
|
|
282
|
+
function subscriptionIntentNonce(planId, payer, permitNonce) {
|
|
283
|
+
if (planId.length === 0) {
|
|
284
|
+
throw new Error("subscriptionIntentNonce requires a non-empty plan id");
|
|
285
|
+
}
|
|
286
|
+
return keccak256(
|
|
287
|
+
encodeAbiParameters(
|
|
288
|
+
[{ type: "string" }, { type: "string" }, { type: "address" }, { type: "uint256" }],
|
|
289
|
+
[SUBSCRIPTION_INTENT_NONCE_DOMAIN, planId, payer.toLowerCase(), permitNonce]
|
|
290
|
+
)
|
|
291
|
+
);
|
|
292
|
+
}
|
|
281
293
|
|
|
282
|
-
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, WEBHOOK_SIGNATURE_VERSION, bytesToUtf8, checkoutPaymentNonce, decryptAesGcm, encryptAesGcm, fromHex, generateAesGcmKey, generateApiKey, hashApiKey, hmacSha256, hmacSha256Hex, randomBase64Url, randomBytes, randomHex, redactApiKey, sha256, sha256Hex, signWebhookPayload, timingSafeEqualBytes, timingSafeEqualString, toBase64Url, toHex, utf8ToBytes, uuid, verifyWebhookSignature };
|
|
294
|
+
export { CHECKOUT_PAYMENT_NONCE_DOMAIN, SUBSCRIPTION_INTENT_NONCE_DOMAIN, WEBHOOK_SIGNATURE_VERSION, bytesToUtf8, checkoutPaymentNonce, decryptAesGcm, encryptAesGcm, fromHex, generateAesGcmKey, generateApiKey, hashApiKey, hmacSha256, hmacSha256Hex, randomBase64Url, randomBytes, randomHex, redactApiKey, sha256, sha256Hex, signWebhookPayload, subscriptionIntentNonce, timingSafeEqualBytes, timingSafeEqualString, toBase64Url, toHex, utf8ToBytes, uuid, verifyWebhookSignature };
|
|
283
295
|
//# sourceMappingURL=index.js.map
|
|
284
296
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/encoding.ts","../src/hash.ts","../src/hmac.ts","../src/random.ts","../src/timing-safe.ts","../src/webhook.ts","../src/api-key.ts","../src/aes-gcm.ts","../src/checkout.ts"],"names":["subtle"],"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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,EAAA,OAAO,MAAM,KAAK,CAAA;AACpB;AAEA,SAAS,UAAU,MAAA,EAAoC;AACrD,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;ACzGO,IAAM,6BAAA,GAAgC;AAEtC,SAAS,qBAAqB,SAAA,EAAwB;AAC3D,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAI,MAAM,sDAAsD,CAAA;AAAA,EACxE;AACA,EAAA,OAAO,SAAA;AAAA,IACL,mBAAA;AAAA,MACE,CAAC,EAAE,IAAA,EAAM,QAAA,IAAY,EAAE,IAAA,EAAM,UAAU,CAAA;AAAA,MACvC,CAAC,+BAA+B,SAAS;AAAA;AAC3C,GACF;AACF","file":"index.js","sourcesContent":["/**\n * Byte encoders that work in every JavaScript runtime we target.\n * No Node `Buffer`, no dependency on the DOM. Only 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 * 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 * 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 * 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","/**\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, e.g. \"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 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","/**\n * AES-256-GCM authenticated symmetric encryption via Web Crypto.\n *\n * Encrypt one short string at a time, decrypt one short string at a\n * time. The encryption key is supplied as a 32-byte hex string by the\n * caller. Suitable for envelope-encrypting small secrets where the\n * key is held outside the data store.\n *\n * AES-GCM is authenticated, so the auth tag detects bit-flips and\n * substitution attacks. A tampered ciphertext fails closed at decrypt\n * time. The 12-byte nonce and 16-byte tag are the canonical layout\n * exposed by Web Crypto.\n *\n * Output format is string-safe and suitable for any text column:\n *\n * v1:<nonce-hex>:<ciphertext-and-tag-hex>\n *\n * Web Crypto returns the auth tag concatenated to the ciphertext, so\n * 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 * This is not a KMS replacement. The key lives in caller-controlled\n * storage. Rotating it means rotating every encrypted value, or\n * supporting two keys for a cutover window. For sign keys, use a\n * hardware-backed signer pattern instead.\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 any 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 * with 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\nfunction 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","import { encodeAbiParameters, keccak256, type Hex } from 'viem'\n\nexport const CHECKOUT_PAYMENT_NONCE_DOMAIN = 'strimz.checkout.payment-nonce.v1'\n\nexport function checkoutPaymentNonce(sessionId: string): Hex {\n if (sessionId.length === 0) {\n throw new Error('checkoutPaymentNonce requires a non-empty session id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }],\n [CHECKOUT_PAYMENT_NONCE_DOMAIN, sessionId],\n ),\n )\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/encoding.ts","../src/hash.ts","../src/hmac.ts","../src/random.ts","../src/timing-safe.ts","../src/webhook.ts","../src/api-key.ts","../src/aes-gcm.ts","../src/checkout.ts"],"names":["subtle"],"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A,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACvB,IAAA,MAAM,IAAI,MAAM,sDAAsD,CAAA;AAAA,EACxE;AACA,EAAA,OAAO,SAAA;AAAA,IACL,mBAAA;AAAA,MACE,CAAC,EAAE,IAAA,EAAM,QAAA,EAAS,EAAG,EAAE,IAAA,EAAM,QAAA,EAAS,EAAG,EAAE,MAAM,SAAA,EAAU,EAAG,EAAE,IAAA,EAAM,WAAW,CAAA;AAAA,MACjF,CAAC,gCAAA,EAAkC,MAAA,EAAQ,KAAA,CAAM,WAAA,IAAsB,WAAW;AAAA;AACpF,GACF;AACF","file":"index.js","sourcesContent":["/**\n * Byte encoders that work in every JavaScript runtime we target.\n * No Node `Buffer`, no dependency on the DOM. Only 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 * 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 * 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 * 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","/**\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, e.g. \"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 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","/**\n * AES-256-GCM authenticated symmetric encryption via Web Crypto.\n *\n * Encrypt one short string at a time, decrypt one short string at a\n * time. The encryption key is supplied as a 32-byte hex string by the\n * caller. Suitable for envelope-encrypting small secrets where the\n * key is held outside the data store.\n *\n * AES-GCM is authenticated, so the auth tag detects bit-flips and\n * substitution attacks. A tampered ciphertext fails closed at decrypt\n * time. The 12-byte nonce and 16-byte tag are the canonical layout\n * exposed by Web Crypto.\n *\n * Output format is string-safe and suitable for any text column:\n *\n * v1:<nonce-hex>:<ciphertext-and-tag-hex>\n *\n * Web Crypto returns the auth tag concatenated to the ciphertext, so\n * 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 * This is not a KMS replacement. The key lives in caller-controlled\n * storage. Rotating it means rotating every encrypted value, or\n * supporting two keys for a cutover window. For sign keys, use a\n * hardware-backed signer pattern instead.\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 any 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 * with 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\nfunction 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","import { encodeAbiParameters, keccak256, type Hex } from 'viem'\n\nexport const CHECKOUT_PAYMENT_NONCE_DOMAIN = 'strimz.checkout.payment-nonce.v1'\n\nexport function checkoutPaymentNonce(sessionId: string): Hex {\n if (sessionId.length === 0) {\n throw new Error('checkoutPaymentNonce requires a non-empty session id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }],\n [CHECKOUT_PAYMENT_NONCE_DOMAIN, sessionId],\n ),\n )\n}\n\nexport const SUBSCRIPTION_INTENT_NONCE_DOMAIN = 'strimz.subscription-intent-nonce.v1'\n\n// The token's permit nonce only moves when a permit lands, so a re-sign while\n// an enrolment is pending gets the same intent nonce and the contract rejects\n// the duplicate.\nexport function subscriptionIntentNonce(planId: string, payer: Hex, permitNonce: bigint): Hex {\n if (planId.length === 0) {\n throw new Error('subscriptionIntentNonce requires a non-empty plan id')\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: 'string' }, { type: 'string' }, { type: 'address' }, { type: 'uint256' }],\n [SUBSCRIPTION_INTENT_NONCE_DOMAIN, planId, payer.toLowerCase() as Hex, permitNonce],\n ),\n )\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@strimz/shared-crypto",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
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
5
|
"license": "MIT",
|
|
6
6
|
"author": "Strimz <hello@strimz.finance>",
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
],
|
|
90
90
|
"dependencies": {
|
|
91
91
|
"viem": "^2.22.6",
|
|
92
|
-
"@strimz/shared-config": "0.
|
|
92
|
+
"@strimz/shared-config": "0.9.0"
|
|
93
93
|
},
|
|
94
94
|
"devDependencies": {
|
|
95
95
|
"eslint": "^9.18.0",
|
package/src/checkout.test.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, it } from 'vitest'
|
|
2
|
-
import { checkoutPaymentNonce } from './checkout.js'
|
|
2
|
+
import { checkoutPaymentNonce, subscriptionIntentNonce } from './checkout.js'
|
|
3
3
|
|
|
4
4
|
describe('checkout/checkoutPaymentNonce', () => {
|
|
5
5
|
it('matches the published vector', () => {
|
|
@@ -23,3 +23,33 @@ describe('checkout/checkoutPaymentNonce', () => {
|
|
|
23
23
|
expect(() => checkoutPaymentNonce('')).toThrow(/non-empty/)
|
|
24
24
|
})
|
|
25
25
|
})
|
|
26
|
+
|
|
27
|
+
describe('checkout/subscriptionIntentNonce', () => {
|
|
28
|
+
const payer = '0x5555555555555555555555555555555555555555'
|
|
29
|
+
|
|
30
|
+
it('matches the published vector', () => {
|
|
31
|
+
expect(subscriptionIntentNonce('cmplan0000000000000001', payer, 7n)).toBe(
|
|
32
|
+
'0x2d80b757304eaa9a00bc108190846917359b36a0e29bdef5b1ff5274646d9e00',
|
|
33
|
+
)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('ignores the case of the payer address', () => {
|
|
37
|
+
const mixed = '0xAbCdEf0000000000000000000000000000000001'
|
|
38
|
+
expect(subscriptionIntentNonce('plan', mixed, 0n)).toBe(
|
|
39
|
+
subscriptionIntentNonce('plan', mixed.toLowerCase(), 0n),
|
|
40
|
+
)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('changes with the plan, the payer and the permit nonce', () => {
|
|
44
|
+
const base = subscriptionIntentNonce('plan', payer, 0n)
|
|
45
|
+
expect(subscriptionIntentNonce('plan2', payer, 0n)).not.toBe(base)
|
|
46
|
+
expect(
|
|
47
|
+
subscriptionIntentNonce('plan', '0x6666666666666666666666666666666666666666', 0n),
|
|
48
|
+
).not.toBe(base)
|
|
49
|
+
expect(subscriptionIntentNonce('plan', payer, 1n)).not.toBe(base)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('rejects an empty plan id', () => {
|
|
53
|
+
expect(() => subscriptionIntentNonce('', payer, 0n)).toThrow(/non-empty/)
|
|
54
|
+
})
|
|
55
|
+
})
|
package/src/checkout.ts
CHANGED
|
@@ -13,3 +13,20 @@ export function checkoutPaymentNonce(sessionId: string): Hex {
|
|
|
13
13
|
),
|
|
14
14
|
)
|
|
15
15
|
}
|
|
16
|
+
|
|
17
|
+
export const SUBSCRIPTION_INTENT_NONCE_DOMAIN = 'strimz.subscription-intent-nonce.v1'
|
|
18
|
+
|
|
19
|
+
// The token's permit nonce only moves when a permit lands, so a re-sign while
|
|
20
|
+
// an enrolment is pending gets the same intent nonce and the contract rejects
|
|
21
|
+
// the duplicate.
|
|
22
|
+
export function subscriptionIntentNonce(planId: string, payer: Hex, permitNonce: bigint): Hex {
|
|
23
|
+
if (planId.length === 0) {
|
|
24
|
+
throw new Error('subscriptionIntentNonce requires a non-empty plan id')
|
|
25
|
+
}
|
|
26
|
+
return keccak256(
|
|
27
|
+
encodeAbiParameters(
|
|
28
|
+
[{ type: 'string' }, { type: 'string' }, { type: 'address' }, { type: 'uint256' }],
|
|
29
|
+
[SUBSCRIPTION_INTENT_NONCE_DOMAIN, planId, payer.toLowerCase() as Hex, permitNonce],
|
|
30
|
+
),
|
|
31
|
+
)
|
|
32
|
+
}
|