munim-billing 0.2.0 → 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.
Files changed (60) hide show
  1. package/LICENSE +42 -201
  2. package/README.md +8 -27
  3. package/lib/cjs/index.js +2 -28
  4. package/lib/cjs/react-native.js +2 -118
  5. package/lib/cjs/web.js +2 -157
  6. package/lib/esm/chunks/57OHO4KT.js +2 -0
  7. package/lib/esm/client.d.ts +0 -1
  8. package/lib/esm/errors.d.ts +0 -1
  9. package/lib/esm/index.d.ts +0 -1
  10. package/lib/esm/index.js +2 -6
  11. package/lib/esm/react-native.d.ts +0 -1
  12. package/lib/esm/react-native.js +2 -114
  13. package/lib/esm/types.d.ts +0 -1
  14. package/lib/esm/version.d.ts +1 -2
  15. package/lib/esm/web.d.ts +0 -1
  16. package/lib/esm/web.js +2 -152
  17. package/lib/esm/webhooks.d.ts +0 -1
  18. package/package.json +5 -14
  19. package/lib/cjs/client.js +0 -233
  20. package/lib/cjs/client.js.map +0 -1
  21. package/lib/cjs/errors.js +0 -55
  22. package/lib/cjs/errors.js.map +0 -1
  23. package/lib/cjs/index.js.map +0 -1
  24. package/lib/cjs/react-native.js.map +0 -1
  25. package/lib/cjs/types.js +0 -21
  26. package/lib/cjs/types.js.map +0 -1
  27. package/lib/cjs/version.js +0 -6
  28. package/lib/cjs/version.js.map +0 -1
  29. package/lib/cjs/web.js.map +0 -1
  30. package/lib/cjs/webhooks.js +0 -137
  31. package/lib/cjs/webhooks.js.map +0 -1
  32. package/lib/esm/client.d.ts.map +0 -1
  33. package/lib/esm/client.js +0 -226
  34. package/lib/esm/client.js.map +0 -1
  35. package/lib/esm/errors.d.ts.map +0 -1
  36. package/lib/esm/errors.js +0 -50
  37. package/lib/esm/errors.js.map +0 -1
  38. package/lib/esm/index.d.ts.map +0 -1
  39. package/lib/esm/index.js.map +0 -1
  40. package/lib/esm/react-native.d.ts.map +0 -1
  41. package/lib/esm/react-native.js.map +0 -1
  42. package/lib/esm/types.d.ts.map +0 -1
  43. package/lib/esm/types.js +0 -18
  44. package/lib/esm/types.js.map +0 -1
  45. package/lib/esm/version.d.ts.map +0 -1
  46. package/lib/esm/version.js +0 -3
  47. package/lib/esm/version.js.map +0 -1
  48. package/lib/esm/web.d.ts.map +0 -1
  49. package/lib/esm/web.js.map +0 -1
  50. package/lib/esm/webhooks.d.ts.map +0 -1
  51. package/lib/esm/webhooks.js +0 -129
  52. package/lib/esm/webhooks.js.map +0 -1
  53. package/src/client.ts +0 -314
  54. package/src/errors.ts +0 -74
  55. package/src/index.ts +0 -26
  56. package/src/react-native.ts +0 -154
  57. package/src/types.ts +0 -366
  58. package/src/version.ts +0 -2
  59. package/src/web.ts +0 -182
  60. package/src/webhooks.ts +0 -169
package/src/webhooks.ts DELETED
@@ -1,169 +0,0 @@
1
- import { MunimBillingError } from './errors.js'
2
- import type { Event } from './types.js'
3
-
4
- /**
5
- * Webhook signatures.
6
- *
7
- * Munim signs each delivery with the endpoint's secret (`whsec_…`):
8
- *
9
- * Munim-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, `${t}.${rawBody}`)>
10
- *
11
- * The HMAC key is the whole secret string, `whsec_` prefix included, as
12
- * UTF-8. A header may carry several `v1=` values (while a secret rotates);
13
- * any one matching is enough.
14
- *
15
- * Uses WebCrypto (`crypto.subtle`), so it runs in Node 20+, Deno, Bun,
16
- * edge runtimes, Convex and browsers. Node 18 needs
17
- * `--experimental-global-webcrypto`.
18
- */
19
-
20
- export const SIGNATURE_HEADER = 'Munim-Signature'
21
- export const EVENT_ID_HEADER = 'Munim-Event-Id'
22
- export const DEFAULT_TOLERANCE_SECONDS = 300
23
-
24
- const encoder = new TextEncoder()
25
-
26
- function subtle(): SubtleCrypto {
27
- const value = (globalThis as { crypto?: Crypto }).crypto?.subtle
28
- if (!value) {
29
- throw new MunimBillingError(
30
- 'Web Crypto (crypto.subtle) is not available in this runtime. Use Node 20+ or another runtime with WebCrypto.',
31
- { type: 'internal' }
32
- )
33
- }
34
- return value
35
- }
36
-
37
- function toHex(buffer: ArrayBuffer): string {
38
- return Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, '0')).join('')
39
- }
40
-
41
- function asString(body: string | Uint8Array): string {
42
- return typeof body === 'string' ? body : new TextDecoder().decode(body)
43
- }
44
-
45
- /** Hex HMAC-SHA256 of `${timestamp}.${rawBody}` with `secret` as the key. */
46
- export async function computeSignature(
47
- secret: string,
48
- rawBody: string | Uint8Array,
49
- timestamp: number
50
- ): Promise<string> {
51
- const key = await subtle().importKey(
52
- 'raw',
53
- encoder.encode(secret),
54
- { name: 'HMAC', hash: 'SHA-256' },
55
- false,
56
- ['sign']
57
- )
58
- const mac = await subtle().sign('HMAC', key, encoder.encode(`${timestamp}.${asString(rawBody)}`))
59
- return toHex(mac)
60
- }
61
-
62
- /**
63
- * The `Munim-Signature` header value for a payload: `t=<timestamp>,v1=<hex>`.
64
- *
65
- * @param timestamp Unix **seconds**. Defaults to now.
66
- */
67
- export async function signWebhookPayload(
68
- secret: string,
69
- rawBody: string | Uint8Array,
70
- timestamp: number = Math.floor(Date.now() / 1000)
71
- ): Promise<string> {
72
- const t = Math.floor(timestamp)
73
- return `t=${t},v1=${await computeSignature(secret, rawBody, t)}`
74
- }
75
-
76
- /** Splits `t=…,v1=…,v1=…` into its timestamp and signatures. */
77
- export function parseSignatureHeader(header: string): { timestamp: number | null; signatures: string[] } {
78
- let timestamp: number | null = null
79
- const signatures: string[] = []
80
- for (const part of header.split(',')) {
81
- const index = part.indexOf('=')
82
- if (index < 0) continue
83
- const key = part.slice(0, index).trim()
84
- const value = part.slice(index + 1).trim()
85
- if (key === 't' && /^\d+$/.test(value)) {
86
- timestamp = Number(value)
87
- } else if (key === 'v1' && value) {
88
- signatures.push(value.toLowerCase())
89
- }
90
- }
91
- return { timestamp, signatures }
92
- }
93
-
94
- /** Compares two strings in time that depends only on their length. */
95
- export function timingSafeEqual(a: string, b: string): boolean {
96
- if (a.length !== b.length) return false
97
- let diff = 0
98
- for (let i = 0; i < a.length; i++) {
99
- diff |= a.charCodeAt(i) ^ b.charCodeAt(i)
100
- }
101
- return diff === 0
102
- }
103
-
104
- export type VerifyWebhookOptions = {
105
- /** How far the signature's timestamp may be from now. Default 300. `0` turns the check off. */
106
- toleranceSeconds?: number
107
- /** "Now" in Unix milliseconds, for tests. Defaults to `Date.now()`. */
108
- now?: number
109
- }
110
-
111
- function fail(message: string): never {
112
- throw new MunimBillingError(message, { type: 'signature_verification', status: 400 })
113
- }
114
-
115
- /**
116
- * Checks a webhook delivery and returns its event.
117
- *
118
- * Pass the request body exactly as received (before any JSON parsing), the
119
- * `Munim-Signature` header, and the endpoint's `whsec_…` secret. Throws a
120
- * `MunimBillingError` with `type: 'signature_verification'` when the
121
- * signature doesn't match or the timestamp is outside the tolerance.
122
- */
123
- export async function verifyWebhook(
124
- rawBody: string | Uint8Array,
125
- signatureHeader: string | null | undefined,
126
- secret: string,
127
- options: VerifyWebhookOptions = {}
128
- ): Promise<Event> {
129
- if (!secret) fail('No webhook secret was given.')
130
- if (!signatureHeader) fail(`Missing ${SIGNATURE_HEADER} header.`)
131
-
132
- const { timestamp, signatures } = parseSignatureHeader(signatureHeader)
133
- if (timestamp === null || signatures.length === 0) {
134
- fail(`Malformed ${SIGNATURE_HEADER} header.`)
135
- }
136
-
137
- const expected = await computeSignature(secret, rawBody, timestamp)
138
- if (!signatures.some((signature) => timingSafeEqual(signature, expected))) {
139
- fail('Webhook signature does not match. Check the secret and that the body is the raw, unparsed request body.')
140
- }
141
-
142
- const tolerance = options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS
143
- if (tolerance > 0) {
144
- const nowSeconds = Math.floor((options.now ?? Date.now()) / 1000)
145
- if (Math.abs(nowSeconds - timestamp) > tolerance) {
146
- fail('Webhook timestamp is outside the tolerance.')
147
- }
148
- }
149
-
150
- try {
151
- return JSON.parse(asString(rawBody)) as Event
152
- } catch (cause) {
153
- throw new MunimBillingError('Webhook body is not valid JSON.', {
154
- type: 'signature_verification',
155
- status: 400,
156
- cause,
157
- })
158
- }
159
- }
160
-
161
- /** `munim.webhooks` / `MunimBilling.webhooks`. */
162
- export const webhooks = {
163
- verify: verifyWebhook,
164
- sign: signWebhookPayload,
165
- computeSignature,
166
- parseHeader: parseSignatureHeader,
167
- SIGNATURE_HEADER,
168
- EVENT_ID_HEADER,
169
- } as const