@strimz/shared-crypto 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +57 -0
- package/dist/aes-gcm.cjs +94 -0
- package/dist/aes-gcm.cjs.map +1 -0
- package/dist/aes-gcm.d.cts +59 -0
- package/dist/aes-gcm.d.ts +59 -0
- package/dist/aes-gcm.js +90 -0
- package/dist/aes-gcm.js.map +1 -0
- package/dist/api-key.cjs +95 -0
- package/dist/api-key.cjs.map +1 -0
- package/dist/api-key.d.cts +32 -0
- package/dist/api-key.d.ts +32 -0
- package/dist/api-key.js +91 -0
- package/dist/api-key.js.map +1 -0
- package/dist/encoding.cjs +49 -0
- package/dist/encoding.cjs.map +1 -0
- package/dist/encoding.d.cts +12 -0
- package/dist/encoding.d.ts +12 -0
- package/dist/encoding.js +43 -0
- package/dist/encoding.js.map +1 -0
- package/dist/hash.cjs +38 -0
- package/dist/hash.cjs.map +1 -0
- package/dist/hash.d.cts +7 -0
- package/dist/hash.d.ts +7 -0
- package/dist/hash.js +35 -0
- package/dist/hash.js.map +1 -0
- package/dist/hmac.cjs +47 -0
- package/dist/hmac.cjs.map +1 -0
- package/dist/hmac.d.cts +8 -0
- package/dist/hmac.d.ts +8 -0
- package/dist/hmac.js +44 -0
- package/dist/hmac.js.map +1 -0
- package/dist/index.cjs +296 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +271 -0
- package/dist/index.js.map +1 -0
- package/dist/random.cjs +61 -0
- package/dist/random.cjs.map +1 -0
- package/dist/random.d.cts +10 -0
- package/dist/random.d.ts +10 -0
- package/dist/random.js +56 -0
- package/dist/random.js.map +1 -0
- package/dist/timing-safe.cjs +24 -0
- package/dist/timing-safe.cjs.map +1 -0
- package/dist/timing-safe.d.cts +14 -0
- package/dist/timing-safe.d.ts +14 -0
- package/dist/timing-safe.js +21 -0
- package/dist/timing-safe.js.map +1 -0
- package/dist/webhook.cjs +123 -0
- package/dist/webhook.cjs.map +1 -0
- package/dist/webhook.d.cts +31 -0
- package/dist/webhook.d.ts +31 -0
- package/dist/webhook.js +119 -0
- package/dist/webhook.js.map +1 -0
- package/package.json +105 -0
- package/src/aes-gcm.test.ts +72 -0
- package/src/aes-gcm.ts +119 -0
- package/src/api-key.test.ts +59 -0
- package/src/api-key.ts +61 -0
- package/src/encoding.test.ts +49 -0
- package/src/encoding.ts +51 -0
- package/src/hash.test.ts +29 -0
- package/src/hash.ts +23 -0
- package/src/hmac.test.ts +28 -0
- package/src/hmac.ts +40 -0
- package/src/index.ts +15 -0
- package/src/random.test.ts +45 -0
- package/src/random.ts +44 -0
- package/src/timing-safe.test.ts +38 -0
- package/src/timing-safe.ts +28 -0
- package/src/webhook.test.ts +78 -0
- package/src/webhook.ts +106 -0
package/src/hash.test.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { sha256, sha256Hex } from './hash.js'
|
|
3
|
+
|
|
4
|
+
describe('hash/sha256', () => {
|
|
5
|
+
it('matches the empty-string test vector', async () => {
|
|
6
|
+
expect(await sha256Hex('')).toBe(
|
|
7
|
+
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
|
|
8
|
+
)
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
it('matches the "abc" test vector', async () => {
|
|
12
|
+
expect(await sha256Hex('abc')).toBe(
|
|
13
|
+
'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
|
|
14
|
+
)
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('accepts Uint8Array input', async () => {
|
|
18
|
+
const bytes = new TextEncoder().encode('abc')
|
|
19
|
+
expect(await sha256Hex(bytes)).toBe(
|
|
20
|
+
'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
|
|
21
|
+
)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('returns a 32-byte digest', async () => {
|
|
25
|
+
const out = await sha256('anything')
|
|
26
|
+
expect(out).toBeInstanceOf(Uint8Array)
|
|
27
|
+
expect(out.length).toBe(32)
|
|
28
|
+
})
|
|
29
|
+
})
|
package/src/hash.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SHA-256 via Web Crypto (available in Node 16+, Deno, Bun, Workers, Edge).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { toHex, utf8ToBytes } from './encoding.js'
|
|
6
|
+
|
|
7
|
+
export async function sha256(data: string | Uint8Array): Promise<Uint8Array> {
|
|
8
|
+
const bytes = typeof data === 'string' ? utf8ToBytes(data) : data
|
|
9
|
+
const digest = await subtle().digest('SHA-256', bytes as BufferSource)
|
|
10
|
+
return new Uint8Array(digest)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function sha256Hex(data: string | Uint8Array): Promise<string> {
|
|
14
|
+
return toHex(await sha256(data))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function subtle(): SubtleCrypto {
|
|
18
|
+
const c = globalThis.crypto
|
|
19
|
+
if (!c || !c.subtle) {
|
|
20
|
+
throw new Error('Web Crypto is not available in this runtime')
|
|
21
|
+
}
|
|
22
|
+
return c.subtle
|
|
23
|
+
}
|
package/src/hmac.test.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { hmacSha256, hmacSha256Hex } from './hmac.js'
|
|
3
|
+
|
|
4
|
+
describe('hmac/sha256', () => {
|
|
5
|
+
it('matches RFC 4231 test case 1', async () => {
|
|
6
|
+
// Key: 20 bytes of 0x0b; data: "Hi There"
|
|
7
|
+
const key = new Uint8Array(20).fill(0x0b)
|
|
8
|
+
const out = await hmacSha256Hex(key, 'Hi There')
|
|
9
|
+
expect(out).toBe('b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7')
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
it('matches RFC 4231 test case 2', async () => {
|
|
13
|
+
// Key: "Jefe"; data: "what do ya want for nothing?"
|
|
14
|
+
const out = await hmacSha256Hex('Jefe', 'what do ya want for nothing?')
|
|
15
|
+
expect(out).toBe('5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843')
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('returns a 32-byte signature', async () => {
|
|
19
|
+
const out = await hmacSha256('secret', 'message')
|
|
20
|
+
expect(out.length).toBe(32)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('is deterministic for the same key and message', async () => {
|
|
24
|
+
const a = await hmacSha256Hex('k', 'm')
|
|
25
|
+
const b = await hmacSha256Hex('k', 'm')
|
|
26
|
+
expect(a).toBe(b)
|
|
27
|
+
})
|
|
28
|
+
})
|
package/src/hmac.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HMAC-SHA256 via Web Crypto.
|
|
3
|
+
* Keys accept either a string (UTF-8) or raw bytes.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { toHex, utf8ToBytes } from './encoding.js'
|
|
7
|
+
|
|
8
|
+
export async function hmacSha256(
|
|
9
|
+
key: string | Uint8Array,
|
|
10
|
+
message: string | Uint8Array,
|
|
11
|
+
): Promise<Uint8Array> {
|
|
12
|
+
const keyBytes = typeof key === 'string' ? utf8ToBytes(key) : key
|
|
13
|
+
const msgBytes = typeof message === 'string' ? utf8ToBytes(message) : message
|
|
14
|
+
const subtle = requireSubtle()
|
|
15
|
+
|
|
16
|
+
const cryptoKey = await subtle.importKey(
|
|
17
|
+
'raw',
|
|
18
|
+
keyBytes as BufferSource,
|
|
19
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
20
|
+
false,
|
|
21
|
+
['sign'],
|
|
22
|
+
)
|
|
23
|
+
const signature = await subtle.sign('HMAC', cryptoKey, msgBytes as BufferSource)
|
|
24
|
+
return new Uint8Array(signature)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function hmacSha256Hex(
|
|
28
|
+
key: string | Uint8Array,
|
|
29
|
+
message: string | Uint8Array,
|
|
30
|
+
): Promise<string> {
|
|
31
|
+
return toHex(await hmacSha256(key, message))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function requireSubtle(): SubtleCrypto {
|
|
35
|
+
const c = globalThis.crypto
|
|
36
|
+
if (!c || !c.subtle) {
|
|
37
|
+
throw new Error('Web Crypto is not available in this runtime')
|
|
38
|
+
}
|
|
39
|
+
return c.subtle
|
|
40
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @strimz/shared-crypto
|
|
3
|
+
*
|
|
4
|
+
* Web Crypto primitives used across the platform.
|
|
5
|
+
* Every export runs unchanged in Node 22, Vercel Edge, and Cloudflare Workers.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export * from './encoding.js'
|
|
9
|
+
export * from './hash.js'
|
|
10
|
+
export * from './hmac.js'
|
|
11
|
+
export * from './random.js'
|
|
12
|
+
export * from './timing-safe.js'
|
|
13
|
+
export * from './webhook.js'
|
|
14
|
+
export * from './api-key.js'
|
|
15
|
+
export * from './aes-gcm.js'
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { randomBase64Url, randomBytes, randomHex, uuid } from './random.js'
|
|
3
|
+
|
|
4
|
+
describe('random/randomBytes', () => {
|
|
5
|
+
it('returns the requested length', () => {
|
|
6
|
+
expect(randomBytes(1).length).toBe(1)
|
|
7
|
+
expect(randomBytes(16).length).toBe(16)
|
|
8
|
+
expect(randomBytes(64).length).toBe(64)
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
it('rejects non-positive or non-integer inputs', () => {
|
|
12
|
+
expect(() => randomBytes(0)).toThrow()
|
|
13
|
+
expect(() => randomBytes(-1)).toThrow()
|
|
14
|
+
expect(() => randomBytes(1.5)).toThrow()
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('produces different outputs on successive calls', () => {
|
|
18
|
+
const a = randomBytes(32)
|
|
19
|
+
const b = randomBytes(32)
|
|
20
|
+
expect(a).not.toEqual(b)
|
|
21
|
+
})
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
describe('random/randomHex', () => {
|
|
25
|
+
it('returns 2 hex chars per byte', () => {
|
|
26
|
+
expect(randomHex(16)).toMatch(/^[0-9a-f]{32}$/)
|
|
27
|
+
})
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
describe('random/randomBase64Url', () => {
|
|
31
|
+
it('returns a URL-safe string with no padding', () => {
|
|
32
|
+
const out = randomBase64Url(32)
|
|
33
|
+
expect(out).toMatch(/^[A-Za-z0-9_-]+$/)
|
|
34
|
+
})
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
describe('random/uuid', () => {
|
|
38
|
+
it('matches the RFC 4122 v4 format', () => {
|
|
39
|
+
expect(uuid()).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('produces distinct values', () => {
|
|
43
|
+
expect(uuid()).not.toBe(uuid())
|
|
44
|
+
})
|
|
45
|
+
})
|
package/src/random.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Random-bytes and id generation using the Web Crypto RNG
|
|
3
|
+
* (cryptographically secure in every runtime we target).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { toBase64Url, toHex } from './encoding.js'
|
|
7
|
+
|
|
8
|
+
export function randomBytes(n: number): Uint8Array {
|
|
9
|
+
if (!Number.isInteger(n) || n <= 0) {
|
|
10
|
+
throw new Error('randomBytes: n must be a positive integer')
|
|
11
|
+
}
|
|
12
|
+
const buf = new Uint8Array(n)
|
|
13
|
+
getRandomValues(buf)
|
|
14
|
+
return buf
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function randomHex(nBytes: number): string {
|
|
18
|
+
return toHex(randomBytes(nBytes))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function randomBase64Url(nBytes: number): string {
|
|
22
|
+
return toBase64Url(randomBytes(nBytes))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function uuid(): string {
|
|
26
|
+
const c = globalThis.crypto
|
|
27
|
+
if (c && typeof c.randomUUID === 'function') {
|
|
28
|
+
return c.randomUUID()
|
|
29
|
+
}
|
|
30
|
+
// Fallback — RFC 4122 v4 from getRandomValues
|
|
31
|
+
const bytes = randomBytes(16)
|
|
32
|
+
bytes[6] = ((bytes[6] as number) & 0x0f) | 0x40
|
|
33
|
+
bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80
|
|
34
|
+
const hex = toHex(bytes)
|
|
35
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function getRandomValues(buf: Uint8Array): void {
|
|
39
|
+
const c = globalThis.crypto
|
|
40
|
+
if (!c || typeof c.getRandomValues !== 'function') {
|
|
41
|
+
throw new Error('crypto.getRandomValues is not available in this runtime')
|
|
42
|
+
}
|
|
43
|
+
c.getRandomValues(buf)
|
|
44
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timingSafeEqualBytes, timingSafeEqualString } from './timing-safe.js'
|
|
3
|
+
|
|
4
|
+
describe('timing-safe/bytes', () => {
|
|
5
|
+
it('returns true for equal byte arrays', () => {
|
|
6
|
+
const a = new Uint8Array([1, 2, 3])
|
|
7
|
+
const b = new Uint8Array([1, 2, 3])
|
|
8
|
+
expect(timingSafeEqualBytes(a, b)).toBe(true)
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
it('returns false for arrays of different length', () => {
|
|
12
|
+
expect(timingSafeEqualBytes(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3, 4]))).toBe(
|
|
13
|
+
false,
|
|
14
|
+
)
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('returns false for arrays that differ in any byte', () => {
|
|
18
|
+
expect(timingSafeEqualBytes(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 4]))).toBe(false)
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
it('handles empty arrays', () => {
|
|
22
|
+
expect(timingSafeEqualBytes(new Uint8Array(0), new Uint8Array(0))).toBe(true)
|
|
23
|
+
})
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
describe('timing-safe/string', () => {
|
|
27
|
+
it('returns true for equal strings', () => {
|
|
28
|
+
expect(timingSafeEqualString('abc', 'abc')).toBe(true)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('returns false for different-length strings', () => {
|
|
32
|
+
expect(timingSafeEqualString('abc', 'abcd')).toBe(false)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('returns false for equal-length strings that differ', () => {
|
|
36
|
+
expect(timingSafeEqualString('abc', 'abd')).toBe(false)
|
|
37
|
+
})
|
|
38
|
+
})
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Constant-time comparison.
|
|
3
|
+
*
|
|
4
|
+
* The comparison must not short-circuit on the first byte mismatch, or an
|
|
5
|
+
* attacker can infer the correct value byte by byte from response timings.
|
|
6
|
+
*
|
|
7
|
+
* Length-difference side channels are acceptable here: leaking the length of
|
|
8
|
+
* a MAC tells an attacker nothing useful (both values are fixed-size in our
|
|
9
|
+
* use).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export function timingSafeEqualBytes(a: Uint8Array, b: Uint8Array): boolean {
|
|
13
|
+
if (a.length !== b.length) return false
|
|
14
|
+
let diff = 0
|
|
15
|
+
for (let i = 0; i < a.length; i++) {
|
|
16
|
+
diff |= (a[i] as number) ^ (b[i] as number)
|
|
17
|
+
}
|
|
18
|
+
return diff === 0
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function timingSafeEqualString(a: string, b: string): boolean {
|
|
22
|
+
if (a.length !== b.length) return false
|
|
23
|
+
let diff = 0
|
|
24
|
+
for (let i = 0; i < a.length; i++) {
|
|
25
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i)
|
|
26
|
+
}
|
|
27
|
+
return diff === 0
|
|
28
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { WEBHOOK_SIGNATURE_VERSION, signWebhookPayload, verifyWebhookSignature } from './webhook.js'
|
|
3
|
+
|
|
4
|
+
const SECRET = 'whsec_test_1234567890abcdef'
|
|
5
|
+
const PAYLOAD = '{"type":"payment.completed","data":{"amount":"1000000"}}'
|
|
6
|
+
const T = 1_735_000_000
|
|
7
|
+
|
|
8
|
+
describe('webhook/signWebhookPayload', () => {
|
|
9
|
+
it('produces the expected header format', async () => {
|
|
10
|
+
const header = await signWebhookPayload(PAYLOAD, SECRET, { timestampSeconds: T })
|
|
11
|
+
expect(header).toMatch(new RegExp(`^t=${T},${WEBHOOK_SIGNATURE_VERSION}=[a-f0-9]{64}$`))
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it('uses the provided timestamp', async () => {
|
|
15
|
+
const header = await signWebhookPayload(PAYLOAD, SECRET, { timestampSeconds: 42 })
|
|
16
|
+
expect(header.startsWith('t=42,')).toBe(true)
|
|
17
|
+
})
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
describe('webhook/verifyWebhookSignature', () => {
|
|
21
|
+
it('accepts a well-formed, current signature', async () => {
|
|
22
|
+
const header = await signWebhookPayload(PAYLOAD, SECRET, { timestampSeconds: T })
|
|
23
|
+
const result = await verifyWebhookSignature(PAYLOAD, header, SECRET, { nowSeconds: T })
|
|
24
|
+
expect(result).toEqual({ valid: true })
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('rejects a signature with a different payload', async () => {
|
|
28
|
+
const header = await signWebhookPayload(PAYLOAD, SECRET, { timestampSeconds: T })
|
|
29
|
+
const result = await verifyWebhookSignature(`${PAYLOAD}x`, header, SECRET, { nowSeconds: T })
|
|
30
|
+
expect(result).toEqual({ valid: false, reason: 'signature_mismatch' })
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('rejects a signature with a different secret', async () => {
|
|
34
|
+
const header = await signWebhookPayload(PAYLOAD, SECRET, { timestampSeconds: T })
|
|
35
|
+
const result = await verifyWebhookSignature(PAYLOAD, header, `${SECRET}x`, { nowSeconds: T })
|
|
36
|
+
expect(result).toEqual({ valid: false, reason: 'signature_mismatch' })
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('rejects a stale timestamp outside the tolerance window', async () => {
|
|
40
|
+
const header = await signWebhookPayload(PAYLOAD, SECRET, { timestampSeconds: T })
|
|
41
|
+
const result = await verifyWebhookSignature(PAYLOAD, header, SECRET, {
|
|
42
|
+
nowSeconds: T + 3_600,
|
|
43
|
+
toleranceSeconds: 300,
|
|
44
|
+
})
|
|
45
|
+
expect(result).toEqual({ valid: false, reason: 'timestamp_out_of_range' })
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('rejects a future timestamp outside the tolerance window', async () => {
|
|
49
|
+
const header = await signWebhookPayload(PAYLOAD, SECRET, { timestampSeconds: T + 3_600 })
|
|
50
|
+
const result = await verifyWebhookSignature(PAYLOAD, header, SECRET, {
|
|
51
|
+
nowSeconds: T,
|
|
52
|
+
toleranceSeconds: 300,
|
|
53
|
+
})
|
|
54
|
+
expect(result).toEqual({ valid: false, reason: 'timestamp_out_of_range' })
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('rejects a missing-timestamp header', async () => {
|
|
58
|
+
const result = await verifyWebhookSignature(PAYLOAD, 'v1=abc', SECRET, { nowSeconds: T })
|
|
59
|
+
expect(result).toEqual({ valid: false, reason: 'missing_timestamp' })
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('rejects a missing-signature header', async () => {
|
|
63
|
+
const result = await verifyWebhookSignature(PAYLOAD, `t=${T}`, SECRET, { nowSeconds: T })
|
|
64
|
+
expect(result).toEqual({ valid: false, reason: 'missing_signature' })
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('rejects a malformed header', async () => {
|
|
68
|
+
const result = await verifyWebhookSignature(PAYLOAD, 'garbage', SECRET, { nowSeconds: T })
|
|
69
|
+
expect(result).toEqual({ valid: false, reason: 'malformed_header' })
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
it('rejects a non-hex signature', async () => {
|
|
73
|
+
const result = await verifyWebhookSignature(PAYLOAD, `t=${T},v1=nothexanywhere`, SECRET, {
|
|
74
|
+
nowSeconds: T,
|
|
75
|
+
})
|
|
76
|
+
expect(result.valid).toBe(false)
|
|
77
|
+
})
|
|
78
|
+
})
|
package/src/webhook.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Webhook signing and verification.
|
|
3
|
+
*
|
|
4
|
+
* Signature format: `t=<unix_seconds>,v1=<hex_hmac_sha256>`
|
|
5
|
+
*
|
|
6
|
+
* The HMAC is computed over `"${t}.${payload}"` so the timestamp is bound to
|
|
7
|
+
* the signature. Verification enforces a replay window (default 300 seconds,
|
|
8
|
+
* matching `@strimz/shared-config`).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { WEBHOOK_SIGNATURE_TOLERANCE_SECONDS } from '@strimz/shared-config/webhooks'
|
|
12
|
+
import { fromHex, toHex } from './encoding.js'
|
|
13
|
+
import { hmacSha256 } from './hmac.js'
|
|
14
|
+
import { timingSafeEqualBytes } from './timing-safe.js'
|
|
15
|
+
|
|
16
|
+
export const WEBHOOK_SIGNATURE_VERSION = 'v1'
|
|
17
|
+
|
|
18
|
+
export interface SignWebhookOptions {
|
|
19
|
+
/** Unix timestamp in seconds. Defaults to `Math.floor(Date.now() / 1000)`. */
|
|
20
|
+
timestampSeconds?: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function signWebhookPayload(
|
|
24
|
+
payload: string,
|
|
25
|
+
secret: string,
|
|
26
|
+
options?: SignWebhookOptions,
|
|
27
|
+
): Promise<string> {
|
|
28
|
+
const t = options?.timestampSeconds ?? Math.floor(Date.now() / 1000)
|
|
29
|
+
const signedBody = `${t}.${payload}`
|
|
30
|
+
const mac = await hmacSha256(secret, signedBody)
|
|
31
|
+
return `t=${t},${WEBHOOK_SIGNATURE_VERSION}=${toHex(mac)}`
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type VerifyWebhookReason =
|
|
35
|
+
| 'malformed_header'
|
|
36
|
+
| 'missing_timestamp'
|
|
37
|
+
| 'missing_signature'
|
|
38
|
+
| 'timestamp_out_of_range'
|
|
39
|
+
| 'signature_mismatch'
|
|
40
|
+
|
|
41
|
+
export type VerifyWebhookResult = { valid: true } | { valid: false; reason: VerifyWebhookReason }
|
|
42
|
+
|
|
43
|
+
export interface VerifyWebhookOptions {
|
|
44
|
+
/** Maximum age of a signature in seconds. Defaults to the shared-config tolerance. */
|
|
45
|
+
toleranceSeconds?: number
|
|
46
|
+
/** Override "now" for testing. Unix seconds. */
|
|
47
|
+
nowSeconds?: number
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function verifyWebhookSignature(
|
|
51
|
+
payload: string,
|
|
52
|
+
signatureHeader: string,
|
|
53
|
+
secret: string,
|
|
54
|
+
options: VerifyWebhookOptions = {},
|
|
55
|
+
): Promise<VerifyWebhookResult> {
|
|
56
|
+
const tolerance = options.toleranceSeconds ?? WEBHOOK_SIGNATURE_TOLERANCE_SECONDS
|
|
57
|
+
const now = options.nowSeconds ?? Math.floor(Date.now() / 1000)
|
|
58
|
+
|
|
59
|
+
const parsed = parseSignatureHeader(signatureHeader)
|
|
60
|
+
if (!parsed) return { valid: false, reason: 'malformed_header' }
|
|
61
|
+
|
|
62
|
+
const { timestamp, signatureHex } = parsed
|
|
63
|
+
if (timestamp === null) return { valid: false, reason: 'missing_timestamp' }
|
|
64
|
+
if (!signatureHex) return { valid: false, reason: 'missing_signature' }
|
|
65
|
+
if (Math.abs(now - timestamp) > tolerance) {
|
|
66
|
+
return { valid: false, reason: 'timestamp_out_of_range' }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const expected = await hmacSha256(secret, `${timestamp}.${payload}`)
|
|
70
|
+
let provided: Uint8Array
|
|
71
|
+
try {
|
|
72
|
+
provided = fromHex(signatureHex)
|
|
73
|
+
} catch {
|
|
74
|
+
return { valid: false, reason: 'signature_mismatch' }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return timingSafeEqualBytes(expected, provided)
|
|
78
|
+
? { valid: true }
|
|
79
|
+
: { valid: false, reason: 'signature_mismatch' }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
interface ParsedSignatureHeader {
|
|
83
|
+
timestamp: number | null
|
|
84
|
+
signatureHex: string | null
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function parseSignatureHeader(header: string): ParsedSignatureHeader | null {
|
|
88
|
+
if (!header || typeof header !== 'string') return null
|
|
89
|
+
const parts = header.split(',')
|
|
90
|
+
let timestamp: number | null = null
|
|
91
|
+
let signatureHex: string | null = null
|
|
92
|
+
for (const part of parts) {
|
|
93
|
+
const eq = part.indexOf('=')
|
|
94
|
+
if (eq <= 0) return null
|
|
95
|
+
const key = part.slice(0, eq).trim()
|
|
96
|
+
const value = part.slice(eq + 1).trim()
|
|
97
|
+
if (key === 't') {
|
|
98
|
+
const n = Number(value)
|
|
99
|
+
if (!Number.isFinite(n) || !Number.isInteger(n)) return null
|
|
100
|
+
timestamp = n
|
|
101
|
+
} else if (key === WEBHOOK_SIGNATURE_VERSION) {
|
|
102
|
+
signatureHex = value
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { timestamp, signatureHex }
|
|
106
|
+
}
|